Re: Mixing text and binary data
- From: pjb@xxxxxxxxxxxxxxxxx (Pascal J. Bourguignon)
- Date: Fri, 29 Feb 2008 14:40:48 +0100
nicolas.edel@xxxxxxxxx writes:
I would like to read/write both text and binary data on sockets and
(*stdandard-input* *standard-output*). Are there idioms in Lisp to
mix text and binary ?
Use a binary stream and encode and decode explicitely.
(defconstant +ascii-code+ " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~")
(defconstant +ascii-base+ 32)
(defconstant +ascii-linefeed+ 10)
(defun ascii-encode (string)
(map 'vector
(lambda (ch)
(if (char= ch #\newline)
+ascii-linefeed+
(let ((pos (position ch +ascii-code+)))
(if pos
(+ +ascii-base+ pos)
(error "Cannot encode in ASCII the character ~C" ch)))))
string))
(defun ascii-decode (codes)
(map 'string
(lambda (code)
(cond
((= +ascii-linefeed+ code) #\newline)
((<= +ascii-base+ code (+ +ascii-base+ (length +ascii-code+) -1))
(aref +ascii-code+ (- code +ascii-base+)))
((< code 128) (error "The ASCII code ~D doesn't correspond to any character." code))
(t (error "The coed ~D is not an ASCII code." code))))))
Note that most functions you usually apply on strings are actually
defined on vectors or even sequences, so you can use them as well on
code vectors.
(read-sequence buffer)
(cond
((= 5 (mismatch #.(ascii-encode "HELO ") buffer)) (process-helo (subseq buffer 5)))
((= 10 (mismatch #.(ascii-encode "MAIL FROM ") buffer)) (process-mail-from (subseq buffer 10)))
...)
For more complex encoding, you could avoid implementing your own
unicode encode/decode using implementation dependant functions such as
#+clisp ext:convert-string-to-bytes, or dig for some 'portability'
sub-library (eg. there's something in arnesi). But most protocol take
care to specify ASCII for the active strings.
--
__Pascal Bourguignon__
.
- References:
- Mixing text and binary data
- From: nicolas . edel
- Mixing text and binary data
- Prev by Date: Re: Mixing text and binary data
- Next by Date: Re: The Master Is Not Pleased
- Previous by thread: Re: Mixing text and binary data
- Next by thread: Re: Mixing text and binary data
- Index(es):
Relevant Pages
|