I need to handle C style ('\0'
delimited) strings from/to a socket and came up with this as a first attempt:
#lang racket
(require racket/tcp)
(define (read-c-str inp)
(define (read-to-zero acc)
(define b (read-byte inp))
(cond
[(equal? b 0) (bytes->string/utf-8 (apply bytes (reverse acc)))]
[else (read-to-zero (cons b acc))]))
(read-to-zero null))
(define (write-c-str val p)
(write-bytes (bytes-append (string->bytes/utf-8 val) (bytes 0)) p)
(flush-output p))
Writing is pretty simple, but I have the feeling I'm missing a more simple way to handle the accumulator there, and mainly looking for feedback on read-c-str
. I'm suspicious of having to reverse, making me think there is a better way.
Here was my second attempt which I'm not convinced is a better way:
(define (blist->string blist)
(bytes->string/utf-8 (foldr (lambda (inb l) (bytes-append l (bytes inb))) #"" blist)))
(define (read-c-str inp)
(define (read-to-zero acc)
(define b (read-byte inp))
(if (equal? b 0)
(blist->string acc)
(read-to-zero (cons b acc))))
(read-to-zero null))