- Common Lisp allows to work directly from the input string, without the need to create intermediate sub-sequences. We need to keep an index into the string. Many string/sequence related functions allow
:startand:endparameters, to limit the range. - Recursion might have problems with a limited stack depth. For portable and efficient code, loops might be better.
Function PARSE-NETSTRING:
(defun parse-netstring (string &aux (string-length (length string)))
(when (plusp string-length)
(loop for start = 0 then (+ end-pos 1)
for colon-pos = (position #\: string :start start)
for length = (if colon-pos
(parse-integer string :start start :end colon-pos)
(error "Colon missing after ~a in \"~a\""
start string))
for end-pos = (when length
(+ colon-pos length 1))
for sstring = (when end-pos
(when (> end-pos string-length)
(error "Wrong substring size ~a in \"~a\""
length string))
(subseq string (1+ colon-pos) end-pos))
collect sstring
while (and colon-pos
end-pos
(< (+ end-pos 1) string-length)))))