Repository navigation
Expand file tree
/
Copy pathneat-bencode.el
More file actions
214 lines (184 loc) · 7.92 KB
/
Copy pathneat-bencode.el
File metadata and controls
214 lines (184 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
;;; neat-bencode.el --- Bencode codec for nREPL -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Bozhidar Batsov
;; Author: Bozhidar Batsov <bozhidar@batsov.dev>
;; URL: https://github.com/nrepl/neat
;; Version: 0.1.0
;; Keywords: languages, tools
;; SPDX-License-Identifier: GPL-3.0-or-later
;; This file is not part of GNU Emacs.
;;; Commentary:
;; Bencode is the wire format used by nREPL. This module is a pure,
;; dependency-free codec: it does no I/O of its own. Callers feed in
;; byte strings (typically accumulated from a network process filter)
;; and get parsed elisp values back, or pass elisp values in to get
;; back a byte string suitable for shipping to a server.
;;
;; Decoding is iterative and stack-based so deeply nested messages
;; can't blow the elisp call stack. When the input is truncated
;; mid-value the decoder returns nil rather than signalling an error,
;; which makes it easy to drive from a streaming filter.
;;; Code:
(require 'cl-lib)
(define-error 'neat-bencode-error "bencode error")
;;;; Encoding
(defun neat-bencode-encode (obj)
"Encode OBJ as a bencode byte string (unibyte).
OBJ may be:
- an integer
- a string (encoded as a bytestring; multibyte strings are UTF-8 encoded)
- a list or vector of encodable values
- an alist whose keys are strings or symbols (encoded as a bencode dict
with keys sorted lexicographically by their byte representation)
A list whose every element is a cons headed by a string or symbol
looks like an alist, so it goes out as a dict; use a vector to send
a list of lists. nil is rejected rather than guessed at, since it
could stand for an empty list, an empty dict or a missing value.
Send [] for an empty list.
Signals `neat-bencode-error' for values that do not match any of the
above."
(cond
((null obj)
(signal 'neat-bencode-error (list "cannot encode nil")))
((integerp obj)
(neat-bencode--ascii (format "i%de" obj)))
((stringp obj)
(let ((bytes (neat-bencode--to-bytes obj)))
(concat (neat-bencode--ascii (number-to-string (length bytes)))
(neat-bencode--ascii ":")
bytes)))
((neat-bencode-dict-p obj)
(let ((pairs (cl-sort (mapcar (lambda (cell)
(cons (neat-bencode--key-string (car cell))
(cdr cell)))
obj)
#'string< :key #'car)))
(apply #'concat
`(,(neat-bencode--ascii "d")
,@(mapcar (lambda (cell)
(concat (neat-bencode-encode (car cell))
(neat-bencode-encode (cdr cell))))
pairs)
,(neat-bencode--ascii "e")))))
((or (listp obj) (vectorp obj))
(apply #'concat
`(,(neat-bencode--ascii "l")
,@(mapcar #'neat-bencode-encode obj)
,(neat-bencode--ascii "e"))))
(t (signal 'neat-bencode-error (list "cannot encode" obj)))))
(defun neat-bencode--ascii (s)
"Force ASCII string S to a unibyte representation."
(if (multibyte-string-p s)
(encode-coding-string s 'us-ascii t)
s))
(defun neat-bencode--to-bytes (s)
"Return string S as a unibyte byte sequence (UTF-8)."
(if (multibyte-string-p s)
(encode-coding-string s 'utf-8 t)
s))
(defun neat-bencode--key-string (k)
"Coerce K (a string or symbol) into a string usable as a dict key."
(cond
((stringp k) k)
((symbolp k) (symbol-name k))
(t (signal 'neat-bencode-error (list "non-string dict key" k)))))
(defun neat-bencode-dict-p (obj)
"Return non-nil if OBJ has the shape of a bencode dict.
That is, every cell of OBJ is a cons whose car is a string or symbol:
what `neat-bencode-encode' sends as a dict, and what a decoded dict
looks like. An empty list is not a dict (it encodes as a list)."
(and (consp obj)
(consp (car obj))
(cl-every (lambda (cell)
(and (consp cell)
(let ((k (car cell)))
(or (stringp k) (symbolp k)))))
obj)))
;;;; Decoding
(defun neat-bencode-decode (str &optional start)
"Decode the bencode value at position START (default 0) in STR.
STR should be a unibyte string of bencoded bytes. Returns a cons
\(VALUE . NEXT-INDEX), where NEXT-INDEX is the position immediately
after the consumed bytes. Returns nil if STR is truncated mid-value;
callers driving a streaming decoder can append more bytes and retry.
Signals `neat-bencode-error' on malformed input.
Decoded shapes:
- integers -> integers
- bytestrings -> multibyte strings (UTF-8 decoded)
- lists -> lists
- dicts -> alists with string keys, in wire order
(which is sorted, per the spec)"
(catch 'neat-bencode--incomplete
(let ((pos (or start 0))
(len (length str))
(stack nil))
(cl-labels
((require-byte ()
(when (>= pos len)
(throw 'neat-bencode--incomplete nil))
(aref str pos))
(emit (value)
(if stack
(push value (cdr (car stack)))
(throw 'neat-bencode--result (cons value pos)))))
(catch 'neat-bencode--result
(while t
(let ((ch (require-byte)))
(cond
;; integer: i<digits>e
((eq ch ?i)
(cl-incf pos)
(let ((end (cl-position ?e str :start pos)))
(unless end (throw 'neat-bencode--incomplete nil))
(let ((n (string-to-number (substring str pos end))))
(setq pos (1+ end))
(emit n))))
;; bytestring: <length>:<bytes>
((and (>= ch ?0) (<= ch ?9))
(let ((colon (cl-position ?: str :start pos)))
(unless colon (throw 'neat-bencode--incomplete nil))
(let* ((blen (string-to-number (substring str pos colon)))
(data-start (1+ colon))
(data-end (+ data-start blen)))
(when (> data-end len)
(throw 'neat-bencode--incomplete nil))
(let ((bytes (substring str data-start data-end)))
(setq pos data-end)
(emit (decode-coding-string bytes 'utf-8))))))
;; list: l...e
((eq ch ?l)
(cl-incf pos)
(push (cons 'list nil) stack))
;; dict: d...e
((eq ch ?d)
(cl-incf pos)
(push (cons 'dict nil) stack))
;; close current container
((eq ch ?e)
(unless stack
(signal 'neat-bencode-error
(list "unexpected 'e' at" pos)))
(cl-incf pos)
(let* ((frame (pop stack))
(type (car frame))
(items (nreverse (cdr frame))))
(emit (pcase type
('list items)
('dict (neat-bencode--items-to-alist items))))))
(t (signal 'neat-bencode-error
(list "unexpected byte" ch "at" pos)))))))))))
(defun neat-bencode--items-to-alist (items)
"Pair a flat sequence of (key value key value ...) ITEMS into an alist."
(when (cl-oddp (length items))
(signal 'neat-bencode-error (list "odd number of items in dict")))
(cl-loop for (k v) on items by #'cddr collect (cons k v)))
;;;; Convenience accessors
(defsubst neat-bencode-get (dict key &optional default)
"Look up KEY in DICT (an alist with string keys).
Return the associated value, or DEFAULT (nil by default) if absent."
(let ((cell (assoc key dict)))
(if cell (cdr cell) default)))
(defun neat-bencode-keys (dict)
"Return the list of keys in DICT, in the order they appear."
(mapcar #'car dict))
(provide 'neat-bencode)
;;; neat-bencode.el ends here