Skip to content

Instantly share code, notes, and snippets.

@lispm
Last active July 18, 2016 21:26
Show Gist options
  • Select an option

  • Save lispm/c8f622b661613338c0c7e70f20650311 to your computer and use it in GitHub Desktop.

Select an option

Save lispm/c8f622b661613338c0c7e70f20650311 to your computer and use it in GitHub Desktop.
(defun parse-netstring (string
&key (field-separator #\,)
(length/string-separator #\:)
(create-displaced-strings-p nil)
&aux (string-length (length string)))
(when (plusp string-length)
(loop for start = 0 then (+ end-pos 1)
for colon-pos = (position length/string-separator 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))
(if create-displaced-strings-p
(make-array (- end-pos (1+ colon-pos))
:element-type (array-element-type string)
:displaced-to string
:displaced-index-offset (1+ colon-pos))
(subseq string (1+ colon-pos) end-pos)))
do (unless (>= end-pos string-length)
(assert (char= (aref string end-pos) field-separator)))
collect sstring
while (and colon-pos
end-pos
(< (+ end-pos 1) string-length)))))
; (parse-netstring "3:abc,2:12,4:qwer")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment