moontalk/server/eventloop-server-experiment/sendbuffer.4th

58 lines
1.5 KiB
Plaintext
Raw Permalink Normal View History

2024-02-17 13:26:14 -05:00
require util.4th
require configuration.4th
0 variable! sendbuffer-len
2024-02-03 14:15:37 -05:00
4096 constant SENDBUFFER_SIZE
2024-02-03 12:37:01 -05:00
create sendbuffer SENDBUFFER_SIZE allot
2024-02-17 13:26:14 -05:00
CONFIG_C_FFI invert [IF]
variable last-is-newline
: (last) ( c-addr u -- c-addr )
1- + ;
: (sanitize-char) ( c-addr -- )
dup c@ dup 32 < swap 126 > or IF
[char] ? swap c!
ELSE
drop
THEN ;
: sanitize ( c-addr u -- )
dup 0<= IF
2drop EXIT
THEN
2dup (last) c@ 10 = last-is-newline !
2dup
bounds DO
I (sanitize-char)
LOOP
last-is-newline @ IF
(last) 10 swap c!
ELSE
2drop
THEN ;
[ELSE]
\ Calling C here is just optimization.
c-library sanitizelib
\c void sanitize(char *buffer, int buffersize) {
\c int lastIsNewline = buffer[buffersize-1] == '\n' ? 1 : 0;
\c for(int i = 0; i<buffersize; i++) {
\c if(buffer[i]<32 || buffer[i]>126) { buffer[i] = '?'; }
\c }
\c if(lastIsNewline) { buffer[buffersize-1] = '\n'; }
\c return;
\c }
c-function sanitize sanitize a n -- void
end-c-library
[THEN]
2024-02-03 12:37:01 -05:00
: sendbuffer-reset ( -- ) 0 sendbuffer-len ! ;
: (overflow?) ( n -- flag )
sendbuffer-len @ + SENDBUFFER_SIZE u> ;
: (append) ( str -- )
dup -rot sendbuffer sendbuffer-len @ + swap move
sendbuffer-len +! ;
: sendbuffer-append ( str -- )
dup (overflow?) abort" sendbuffer overflow" (append) ;
: sendbuffer-sanitize ( -- )
2024-02-17 13:26:14 -05:00
sendbuffer sendbuffer-len @ sanitize ;
2024-02-03 12:37:01 -05:00
: sendbuffer@ ( -- str ) sendbuffer sendbuffer-len @ ;