(module netstring (netstring-write netstring-read string->netstring netstring->string) (import chicken scheme) (use (only extras read-string read-token) (only ports with-output-to-port with-output-to-string with-input-from-string)) (define (netstring-write str #!optional (port (current-output-port))) (with-output-to-port port (lambda () (display (string-length str)) (display #\:) (display str) (display #\,)))) (define (netstring-read #!optional (port (current-input-port))) (let* ((len (read-token char-numeric? port)) (len (or (string->number len) (error 'netstring-read "missing length header"))) (string (if (eq? #\: (read-char port)) (read-string len port) (error 'netstring-read "missing length delimiter")))) (if (eq? #\, (read-char port)) string (error 'netstring-read "missing terminator")))) (define (string->netstring str) (with-output-to-string (lambda () (netstring-write str)))) (define (netstring->string ns) (with-input-from-string ns netstring-read)) )