diff options
Diffstat (limited to 'doc/ext_buffer.html')
-rw-r--r-- | doc/ext_buffer.html | 697 |
1 files changed, 697 insertions, 0 deletions
diff --git a/doc/ext_buffer.html b/doc/ext_buffer.html new file mode 100644 index 00000000..7b874f57 --- /dev/null +++ b/doc/ext_buffer.html | |||
@@ -0,0 +1,697 @@ | |||
1 | <!DOCTYPE html> | ||
2 | <html> | ||
3 | <head> | ||
4 | <title>String Buffer Library</title> | ||
5 | <meta charset="utf-8"> | ||
6 | <meta name="Copyright" content="Copyright (C) 2005-2022"> | ||
7 | <meta name="Language" content="en"> | ||
8 | <link rel="stylesheet" type="text/css" href="bluequad.css" media="screen"> | ||
9 | <link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print"> | ||
10 | <style type="text/css"> | ||
11 | .lib { | ||
12 | vertical-align: middle; | ||
13 | margin-left: 5px; | ||
14 | padding: 0 5px; | ||
15 | font-size: 60%; | ||
16 | border-radius: 5px; | ||
17 | background: #c5d5ff; | ||
18 | color: #000; | ||
19 | } | ||
20 | </style> | ||
21 | </head> | ||
22 | <body> | ||
23 | <div id="site"> | ||
24 | <a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a> | ||
25 | </div> | ||
26 | <div id="head"> | ||
27 | <h1>String Buffer Library</h1> | ||
28 | </div> | ||
29 | <div id="nav"> | ||
30 | <ul><li> | ||
31 | <a href="luajit.html">LuaJIT</a> | ||
32 | <ul><li> | ||
33 | <a href="https://luajit.org/download.html">Download <span class="ext">»</span></a> | ||
34 | </li><li> | ||
35 | <a href="install.html">Installation</a> | ||
36 | </li><li> | ||
37 | <a href="running.html">Running</a> | ||
38 | </li></ul> | ||
39 | </li><li> | ||
40 | <a href="extensions.html">Extensions</a> | ||
41 | <ul><li> | ||
42 | <a href="ext_ffi.html">FFI Library</a> | ||
43 | <ul><li> | ||
44 | <a href="ext_ffi_tutorial.html">FFI Tutorial</a> | ||
45 | </li><li> | ||
46 | <a href="ext_ffi_api.html">ffi.* API</a> | ||
47 | </li><li> | ||
48 | <a href="ext_ffi_semantics.html">FFI Semantics</a> | ||
49 | </li></ul> | ||
50 | </li><li> | ||
51 | <a class="current" href="ext_buffer.html">String Buffers</a> | ||
52 | </li><li> | ||
53 | <a href="ext_jit.html">jit.* Library</a> | ||
54 | </li><li> | ||
55 | <a href="ext_c_api.html">Lua/C API</a> | ||
56 | </li><li> | ||
57 | <a href="ext_profiler.html">Profiler</a> | ||
58 | </li></ul> | ||
59 | </li><li> | ||
60 | <a href="status.html">Status</a> | ||
61 | </li><li> | ||
62 | <a href="faq.html">FAQ</a> | ||
63 | </li><li> | ||
64 | <a href="http://wiki.luajit.org/">Wiki <span class="ext">»</span></a> | ||
65 | </li><li> | ||
66 | <a href="https://luajit.org/list.html">Mailing List <span class="ext">»</span></a> | ||
67 | </li></ul> | ||
68 | </div> | ||
69 | <div id="main"> | ||
70 | <p> | ||
71 | The string buffer library allows <b>high-performance manipulation of | ||
72 | string-like data</b>. | ||
73 | </p> | ||
74 | <p> | ||
75 | Unlike Lua strings, which are constants, string buffers are | ||
76 | <b>mutable</b> sequences of 8-bit (binary-transparent) characters. Data | ||
77 | can be stored, formatted and encoded into a string buffer and later | ||
78 | converted, extracted or decoded. | ||
79 | </p> | ||
80 | <p> | ||
81 | The convenient string buffer API simplifies common string manipulation | ||
82 | tasks, that would otherwise require creating many intermediate strings. | ||
83 | String buffers improve performance by eliminating redundant memory | ||
84 | copies, object creation, string interning and garbage collection | ||
85 | overhead. In conjunction with the FFI library, they allow zero-copy | ||
86 | operations. | ||
87 | </p> | ||
88 | <p> | ||
89 | The string buffer libary also includes a high-performance | ||
90 | <a href="serialize">serializer</a> for Lua objects. | ||
91 | </p> | ||
92 | |||
93 | <h2 id="wip" style="color:#ff0000">Work in Progress</h2> | ||
94 | <p> | ||
95 | <b style="color:#ff0000">This library is a work in progress. More | ||
96 | functionality will be added soon.</b> | ||
97 | </p> | ||
98 | |||
99 | <h2 id="use">Using the String Buffer Library</h2> | ||
100 | <p> | ||
101 | The string buffer library is built into LuaJIT by default, but it's not | ||
102 | loaded by default. Add this to the start of every Lua file that needs | ||
103 | one of its functions: | ||
104 | </p> | ||
105 | <pre class="code"> | ||
106 | local buffer = require("string.buffer") | ||
107 | </pre> | ||
108 | <p> | ||
109 | The convention for the syntax shown on this page is that <tt>buffer</tt> | ||
110 | refers to the buffer library and <tt>buf</tt> refers to an individual | ||
111 | buffer object. | ||
112 | </p> | ||
113 | <p> | ||
114 | Please note the difference between a Lua function call, e.g. | ||
115 | <tt>buffer.new()</tt> (with a dot) and a Lua method call, e.g. | ||
116 | <tt>buf:reset()</tt> (with a colon). | ||
117 | </p> | ||
118 | |||
119 | <h3 id="buffer_object">Buffer Objects</h3> | ||
120 | <p> | ||
121 | A buffer object is a garbage-collected Lua object. After creation with | ||
122 | <tt>buffer.new()</tt>, it can (and should) be reused for many operations. | ||
123 | When the last reference to a buffer object is gone, it will eventually | ||
124 | be freed by the garbage collector, along with the allocated buffer | ||
125 | space. | ||
126 | </p> | ||
127 | <p> | ||
128 | Buffers operate like a FIFO (first-in first-out) data structure. Data | ||
129 | can be appended (written) to the end of the buffer and consumed (read) | ||
130 | from the front of the buffer. These operations may be freely mixed. | ||
131 | </p> | ||
132 | <p> | ||
133 | The buffer space that holds the characters is managed automatically | ||
134 | — it grows as needed and already consumed space is recycled. Use | ||
135 | <tt>buffer.new(size)</tt> and <tt>buf:free()</tt>, if you need more | ||
136 | control. | ||
137 | </p> | ||
138 | <p> | ||
139 | The maximum size of a single buffer is the same as the maximum size of a | ||
140 | Lua string, which is slightly below two gigabytes. For huge data sizes, | ||
141 | neither strings nor buffers are the right data structure — use the | ||
142 | FFI library to directly map memory or files up to the virtual memory | ||
143 | limit of your OS. | ||
144 | </p> | ||
145 | |||
146 | <h3 id="buffer_overview">Buffer Method Overview</h3> | ||
147 | <ul> | ||
148 | <li> | ||
149 | The <tt>buf:put*()</tt>-like methods append (write) characters to the | ||
150 | end of the buffer. | ||
151 | </li> | ||
152 | <li> | ||
153 | The <tt>buf:get*()</tt>-like methods consume (read) characters from the | ||
154 | front of the buffer. | ||
155 | </li> | ||
156 | <li> | ||
157 | Other methods, like <tt>buf:tostring()</tt> only read the buffer | ||
158 | contents, but don't change the buffer. | ||
159 | </li> | ||
160 | <li> | ||
161 | The <tt>buf:set()</tt> method allows zero-copy consumption of a string | ||
162 | or an FFI cdata object as a buffer. | ||
163 | </li> | ||
164 | <li> | ||
165 | The FFI-specific methods allow zero-copy read/write-style operations or | ||
166 | modifying the buffer contents in-place. Please check the | ||
167 | <a href="#ffi_caveats">FFI caveats</a> below, too. | ||
168 | </li> | ||
169 | <li> | ||
170 | Methods that don't need to return anything specific, return the buffer | ||
171 | object itself as a convenience. This allows method chaining, e.g.: | ||
172 | <tt>buf:reset():encode(obj)</tt> or <tt>buf:skip(len):get()</tt> | ||
173 | </li> | ||
174 | </ul> | ||
175 | |||
176 | <h2 id="create">Buffer Creation and Management</h2> | ||
177 | |||
178 | <h3 id="buffer_new"><tt>local buf = buffer.new([size [,options]])<br> | ||
179 | local buf = buffer.new([options])</tt></h3> | ||
180 | <p> | ||
181 | Creates a new buffer object. | ||
182 | </p> | ||
183 | <p> | ||
184 | The optional <tt>size</tt> argument ensures a minimum initial buffer | ||
185 | size. This is strictly an optimization when the required buffer size is | ||
186 | known beforehand. The buffer space will grow as needed, in any case. | ||
187 | </p> | ||
188 | <p> | ||
189 | The optional table <tt>options</tt> sets various | ||
190 | <a href="#serialize_options">serialization options</a>. | ||
191 | </p> | ||
192 | |||
193 | <h3 id="buffer_reset"><tt>buf = buf:reset()</tt></h3> | ||
194 | <p> | ||
195 | Reset (empty) the buffer. The allocated buffer space is not freed and | ||
196 | may be reused. | ||
197 | </p> | ||
198 | |||
199 | <h3 id="buffer_free"><tt>buf = buf:free()</tt></h3> | ||
200 | <p> | ||
201 | The buffer space of the buffer object is freed. The object itself | ||
202 | remains intact, empty and may be reused. | ||
203 | </p> | ||
204 | <p> | ||
205 | Note: you normally don't need to use this method. The garbage collector | ||
206 | automatically frees the buffer space, when the buffer object is | ||
207 | collected. Use this method, if you need to free the associated memory | ||
208 | immediately. | ||
209 | </p> | ||
210 | |||
211 | <h2 id="write">Buffer Writers</h2> | ||
212 | |||
213 | <h3 id="buffer_put"><tt>buf = buf:put([str|num|obj] [,…])</tt></h3> | ||
214 | <p> | ||
215 | Appends a string <tt>str</tt>, a number <tt>num</tt> or any object | ||
216 | <tt>obj</tt> with a <tt>__tostring</tt> metamethod to the buffer. | ||
217 | Multiple arguments are appended in the given order. | ||
218 | </p> | ||
219 | <p> | ||
220 | Appending a buffer to a buffer is possible and short-circuited | ||
221 | internally. But it still involves a copy. Better combine the buffer | ||
222 | writes to use a single buffer. | ||
223 | </p> | ||
224 | |||
225 | <h3 id="buffer_putf"><tt>buf = buf:putf(format, …)</tt></h3> | ||
226 | <p> | ||
227 | Appends the formatted arguments to the buffer. The <tt>format</tt> | ||
228 | string supports the same options as <tt>string.format()</tt>. | ||
229 | </p> | ||
230 | |||
231 | <h3 id="buffer_putcdata"><tt>buf = buf:putcdata(cdata, len)</tt><span class="lib">FFI</span></h3> | ||
232 | <p> | ||
233 | Appends the given <tt>len</tt> number of bytes from the memory pointed | ||
234 | to by the FFI <tt>cdata</tt> object to the buffer. The object needs to | ||
235 | be convertible to a (constant) pointer. | ||
236 | </p> | ||
237 | |||
238 | <h3 id="buffer_set"><tt>buf = buf:set(str)<br> | ||
239 | buf = buf:set(cdata, len)</tt><span class="lib">FFI</span></h3> | ||
240 | <p> | ||
241 | This method allows zero-copy consumption of a string or an FFI cdata | ||
242 | object as a buffer. It stores a reference to the passed string | ||
243 | <tt>str</tt> or the FFI <tt>cdata</tt> object in the buffer. Any buffer | ||
244 | space originally allocated is freed. This is <i>not</i> an append | ||
245 | operation, unlike the <tt>buf:put*()</tt> methods. | ||
246 | </p> | ||
247 | <p> | ||
248 | After calling this method, the buffer behaves as if | ||
249 | <tt>buf:free():put(str)</tt> or <tt>buf:free():put(cdata, len)</tt> | ||
250 | had been called. However, the data is only referenced and not copied, as | ||
251 | long as the buffer is only consumed. | ||
252 | </p> | ||
253 | <p> | ||
254 | In case the buffer is written to later on, the referenced data is copied | ||
255 | and the object reference is removed (copy-on-write semantics). | ||
256 | </p> | ||
257 | <p> | ||
258 | The stored reference is an anchor for the garbage collector and keeps the | ||
259 | originally passed string or FFI cdata object alive. | ||
260 | </p> | ||
261 | |||
262 | <h3 id="buffer_reserve"><tt>ptr, len = buf:reserve(size)</tt><span class="lib">FFI</span><br> | ||
263 | <tt>buf = buf:commit(used)</tt><span class="lib">FFI</span></h3> | ||
264 | <p> | ||
265 | The <tt>reserve</tt> method reserves at least <tt>size</tt> bytes of | ||
266 | write space in the buffer. It returns an <tt>uint8_t *</tt> FFI | ||
267 | cdata pointer <tt>ptr</tt> that points to this space. | ||
268 | </p> | ||
269 | <p> | ||
270 | The available length in bytes is returned in <tt>len</tt>. This is at | ||
271 | least <tt>size</tt> bytes, but may be more to facilitate efficient | ||
272 | buffer growth. You can either make use of the additional space or ignore | ||
273 | <tt>len</tt> and only use <tt>size</tt> bytes. | ||
274 | </p> | ||
275 | <p> | ||
276 | The <tt>commit</tt> method appends the <tt>used</tt> bytes of the | ||
277 | previously returned write space to the buffer data. | ||
278 | </p> | ||
279 | <p> | ||
280 | This pair of methods allows zero-copy use of C read-style APIs: | ||
281 | </p> | ||
282 | <pre class="code"> | ||
283 | local MIN_SIZE = 65536 | ||
284 | repeat | ||
285 | local ptr, len = buf:reserve(MIN_SIZE) | ||
286 | local n = C.read(fd, ptr, len) | ||
287 | if n == 0 then break end -- EOF. | ||
288 | if n < 0 then error("read error") end | ||
289 | buf:commit(n) | ||
290 | until false | ||
291 | </pre> | ||
292 | <p> | ||
293 | The reserved write space is <i>not</i> initialized. At least the | ||
294 | <tt>used</tt> bytes <b>must</b> be written to before calling the | ||
295 | <tt>commit</tt> method. There's no need to call the <tt>commit</tt> | ||
296 | method, if nothing is added to the buffer (e.g. on error). | ||
297 | </p> | ||
298 | |||
299 | <h2 id="read">Buffer Readers</h2> | ||
300 | |||
301 | <h3 id="buffer_length"><tt>len = #buf</tt></h3> | ||
302 | <p> | ||
303 | Returns the current length of the buffer data in bytes. | ||
304 | </p> | ||
305 | |||
306 | <h3 id="buffer_concat"><tt>res = str|num|buf .. str|num|buf […]</tt></h3> | ||
307 | <p> | ||
308 | The Lua concatenation operator <tt>..</tt> also accepts buffers, just | ||
309 | like strings or numbers. It always returns a string and not a buffer. | ||
310 | </p> | ||
311 | <p> | ||
312 | Note that although this is supported for convenience, this thwarts one | ||
313 | of the main reasons to use buffers, which is to avoid string | ||
314 | allocations. Rewrite it with <tt>buf:put()</tt> and <tt>buf:get()</tt>. | ||
315 | </p> | ||
316 | <p> | ||
317 | Mixing this with unrelated objects that have a <tt>__concat</tt> | ||
318 | metamethod may not work, since these probably only expect strings. | ||
319 | </p> | ||
320 | |||
321 | <h3 id="buffer_skip"><tt>buf = buf:skip(len)</tt></h3> | ||
322 | <p> | ||
323 | Skips (consumes) <tt>len</tt> bytes from the buffer up to the current | ||
324 | length of the buffer data. | ||
325 | </p> | ||
326 | |||
327 | <h3 id="buffer_get"><tt>str, … = buf:get([len|nil] [,…])</tt></h3> | ||
328 | <p> | ||
329 | Consumes the buffer data and returns one or more strings. If called | ||
330 | without arguments, the whole buffer data is consumed. If called with a | ||
331 | number, up to <tt>len</tt> bytes are consumed. A <tt>nil</tt> argument | ||
332 | consumes the remaining buffer space (this only makes sense as the last | ||
333 | argument). Multiple arguments consume the buffer data in the given | ||
334 | order. | ||
335 | </p> | ||
336 | <p> | ||
337 | Note: a zero length or no remaining buffer data returns an empty string | ||
338 | and not <tt>nil</tt>. | ||
339 | </p> | ||
340 | |||
341 | <h3 id="buffer_tostring"><tt>str = buf:tostring()<br> | ||
342 | str = tostring(buf)</tt></h3> | ||
343 | <p> | ||
344 | Creates a string from the buffer data, but doesn't consume it. The | ||
345 | buffer remains unchanged. | ||
346 | </p> | ||
347 | <p> | ||
348 | Buffer objects also define a <tt>__tostring</tt> metamethod. This means | ||
349 | buffers can be passed to the global <tt>tostring()</tt> function and | ||
350 | many other functions that accept this in place of strings. The important | ||
351 | internal uses in functions like <tt>io.write()</tt> are short-circuited | ||
352 | to avoid the creation of an intermediate string object. | ||
353 | </p> | ||
354 | |||
355 | <h3 id="buffer_ref"><tt>ptr, len = buf:ref()</tt><span class="lib">FFI</span></h3> | ||
356 | <p> | ||
357 | Returns an <tt>uint8_t *</tt> FFI cdata pointer <tt>ptr</tt> that | ||
358 | points to the buffer data. The length of the buffer data in bytes is | ||
359 | returned in <tt>len</tt>. | ||
360 | </p> | ||
361 | <p> | ||
362 | The returned pointer can be directly passed to C functions that expect a | ||
363 | buffer and a length. You can also do bytewise reads | ||
364 | (<tt>local x = ptr[i]</tt>) or writes | ||
365 | (<tt>ptr[i] = 0x40</tt>) of the buffer data. | ||
366 | </p> | ||
367 | <p> | ||
368 | In conjunction with the <tt>skip</tt> method, this allows zero-copy use | ||
369 | of C write-style APIs: | ||
370 | </p> | ||
371 | <pre class="code"> | ||
372 | repeat | ||
373 | local ptr, len = buf:ref() | ||
374 | if len == 0 then break end | ||
375 | local n = C.write(fd, ptr, len) | ||
376 | if n < 0 then error("write error") end | ||
377 | buf:skip(n) | ||
378 | until n >= len | ||
379 | </pre> | ||
380 | <p> | ||
381 | Unlike Lua strings, buffer data is <i>not</i> implicitly | ||
382 | zero-terminated. It's not safe to pass <tt>ptr</tt> to C functions that | ||
383 | expect zero-terminated strings. If you're not using <tt>len</tt>, then | ||
384 | you're doing something wrong. | ||
385 | </p> | ||
386 | |||
387 | <h2 id="serialize">Serialization of Lua Objects</h2> | ||
388 | <p> | ||
389 | The following functions and methods allow <b>high-speed serialization</b> | ||
390 | (encoding) of a Lua object into a string and decoding it back to a Lua | ||
391 | object. This allows convenient storage and transport of <b>structured | ||
392 | data</b>. | ||
393 | </p> | ||
394 | <p> | ||
395 | The encoded data is in an <a href="#serialize_format">internal binary | ||
396 | format</a>. The data can be stored in files, binary-transparent | ||
397 | databases or transmitted to other LuaJIT instances across threads, | ||
398 | processes or networks. | ||
399 | </p> | ||
400 | <p> | ||
401 | Encoding speed can reach up to 1 Gigabyte/second on a modern desktop- or | ||
402 | server-class system, even when serializing many small objects. Decoding | ||
403 | speed is mostly constrained by object creation cost. | ||
404 | </p> | ||
405 | <p> | ||
406 | The serializer handles most Lua types, common FFI number types and | ||
407 | nested structures. Functions, thread objects, other FFI cdata and full | ||
408 | userdata cannot be serialized (yet). | ||
409 | </p> | ||
410 | <p> | ||
411 | The encoder serializes nested structures as trees. Multiple references | ||
412 | to a single object will be stored separately and create distinct objects | ||
413 | after decoding. Circular references cause an error. | ||
414 | </p> | ||
415 | |||
416 | <h3 id="serialize_methods">Serialization Functions and Methods</h3> | ||
417 | |||
418 | <h3 id="buffer_encode"><tt>str = buffer.encode(obj)<br> | ||
419 | buf = buf:encode(obj)</tt></h3> | ||
420 | <p> | ||
421 | Serializes (encodes) the Lua object <tt>obj</tt>. The stand-alone | ||
422 | function returns a string <tt>str</tt>. The buffer method appends the | ||
423 | encoding to the buffer. | ||
424 | </p> | ||
425 | <p> | ||
426 | <tt>obj</tt> can be any of the supported Lua types — it doesn't | ||
427 | need to be a Lua table. | ||
428 | </p> | ||
429 | <p> | ||
430 | This function may throw an error when attempting to serialize | ||
431 | unsupported object types, circular references or deeply nested tables. | ||
432 | </p> | ||
433 | |||
434 | <h3 id="buffer_decode"><tt>obj = buffer.decode(str)<br> | ||
435 | obj = buf:decode()</tt></h3> | ||
436 | <p> | ||
437 | The stand-alone function de-serializes (decodes) the string | ||
438 | <tt>str</tt>, the buffer method de-serializes one object from the | ||
439 | buffer. Both return a Lua object <tt>obj</tt>. | ||
440 | </p> | ||
441 | <p> | ||
442 | The returned object may be any of the supported Lua types — | ||
443 | even <tt>nil</tt>. | ||
444 | </p> | ||
445 | <p> | ||
446 | This function may throw an error when fed with malformed or incomplete | ||
447 | encoded data. The stand-alone function throws when there's left-over | ||
448 | data after decoding a single top-level object. The buffer method leaves | ||
449 | any left-over data in the buffer. | ||
450 | </p> | ||
451 | <p> | ||
452 | Attempting to de-serialize an FFI type will throw an error, if the FFI | ||
453 | library is not built-in or has not been loaded, yet. | ||
454 | </p> | ||
455 | |||
456 | <h3 id="serialize_options">Serialization Options</h3> | ||
457 | <p> | ||
458 | The <tt>options</tt> table passed to <tt>buffer.new()</tt> may contain | ||
459 | the following members (all optional): | ||
460 | </p> | ||
461 | <ul> | ||
462 | <li> | ||
463 | <tt>dict</tt> is a Lua table holding a <b>dictionary of strings</b> that | ||
464 | commonly occur as table keys of objects you are serializing. These keys | ||
465 | are compactly encoded as indexes during serialization. A well chosen | ||
466 | dictionary saves space and improves serialization performance. | ||
467 | </li> | ||
468 | <li> | ||
469 | <tt>metatable</tt> is a Lua table holding a <b>dictionary of metatables</b> | ||
470 | for the table objects you are serializing. | ||
471 | </li> | ||
472 | </ul> | ||
473 | <p> | ||
474 | <tt>dict</tt> needs to be an array of strings and <tt>metatable</tt> needs | ||
475 | to be an array of tables. Both starting at index 1 and without holes (no | ||
476 | <tt>nil</tt> inbetween). The tables are anchored in the buffer object and | ||
477 | internally modified into a two-way index (don't do this yourself, just pass | ||
478 | a plain array). The tables must not be modified after they have been passed | ||
479 | to <tt>buffer.new()</tt>. | ||
480 | </p> | ||
481 | <p> | ||
482 | The <tt>dict</tt> and <tt>metatable</tt> tables used by the encoder and | ||
483 | decoder must be the same. Put the most common entries at the front. Extend | ||
484 | at the end to ensure backwards-compatibility — older encodings can | ||
485 | then still be read. You may also set some indexes to <tt>false</tt> to | ||
486 | explicitly drop backwards-compatibility. Old encodings that use these | ||
487 | indexes will throw an error when decoded. | ||
488 | </p> | ||
489 | <p> | ||
490 | Metatables that are not found in the <tt>metatable</tt> dictionary are | ||
491 | ignored when encoding. Decoding returns a table with a <tt>nil</tt> | ||
492 | metatable. | ||
493 | </p> | ||
494 | <p> | ||
495 | Note: parsing and preparation of the options table is somewhat | ||
496 | expensive. Create a buffer object only once and recycle it for multiple | ||
497 | uses. Avoid mixing encoder and decoder buffers, since the | ||
498 | <tt>buf:set()</tt> method frees the already allocated buffer space: | ||
499 | </p> | ||
500 | <pre class="code"> | ||
501 | local options = { | ||
502 | dict = { "commonly", "used", "string", "keys" }, | ||
503 | } | ||
504 | local buf_enc = buffer.new(options) | ||
505 | local buf_dec = buffer.new(options) | ||
506 | |||
507 | local function encode(obj) | ||
508 | return buf_enc:reset():encode(obj):get() | ||
509 | end | ||
510 | |||
511 | local function decode(str) | ||
512 | return buf_dec:set(str):decode() | ||
513 | end | ||
514 | </pre> | ||
515 | |||
516 | <h3 id="serialize_stream">Streaming Serialization</h3> | ||
517 | <p> | ||
518 | In some contexts, it's desirable to do piecewise serialization of large | ||
519 | datasets, also known as <i>streaming</i>. | ||
520 | </p> | ||
521 | <p> | ||
522 | This serialization format can be safely concatenated and supports streaming. | ||
523 | Multiple encodings can simply be appended to a buffer and later decoded | ||
524 | individually: | ||
525 | </p> | ||
526 | <pre class="code"> | ||
527 | local buf = buffer.new() | ||
528 | buf:encode(obj1) | ||
529 | buf:encode(obj2) | ||
530 | local copy1 = buf:decode() | ||
531 | local copy2 = buf:decode() | ||
532 | </pre> | ||
533 | <p> | ||
534 | Here's how to iterate over a stream: | ||
535 | </p> | ||
536 | <pre class="code"> | ||
537 | while #buf ~= 0 do | ||
538 | local obj = buf:decode() | ||
539 | -- Do something with obj. | ||
540 | end | ||
541 | </pre> | ||
542 | <p> | ||
543 | Since the serialization format doesn't prepend a length to its encoding, | ||
544 | network applications may need to transmit the length, too. | ||
545 | </p> | ||
546 | |||
547 | <h3 id="serialize_format">Serialization Format Specification</h3> | ||
548 | <p> | ||
549 | This serialization format is designed for <b>internal use</b> by LuaJIT | ||
550 | applications. Serialized data is upwards-compatible and portable across | ||
551 | all supported LuaJIT platforms. | ||
552 | </p> | ||
553 | <p> | ||
554 | It's an <b>8-bit binary format</b> and not human-readable. It uses e.g. | ||
555 | embedded zeroes and stores embedded Lua string objects unmodified, which | ||
556 | are 8-bit-clean, too. Encoded data can be safely concatenated for | ||
557 | streaming and later decoded one top-level object at a time. | ||
558 | </p> | ||
559 | <p> | ||
560 | The encoding is reasonably compact, but tuned for maximum performance, | ||
561 | not for minimum space usage. It compresses well with any of the common | ||
562 | byte-oriented data compression algorithms. | ||
563 | </p> | ||
564 | <p> | ||
565 | Although documented here for reference, this format is explicitly | ||
566 | <b>not</b> intended to be a 'public standard' for structured data | ||
567 | interchange across computer languages (like JSON or MessagePack). Please | ||
568 | do not use it as such. | ||
569 | </p> | ||
570 | <p> | ||
571 | The specification is given below as a context-free grammar with a | ||
572 | top-level <tt>object</tt> as the starting point. Alternatives are | ||
573 | separated by the <tt>|</tt> symbol and <tt>*</tt> indicates repeats. | ||
574 | Grouping is implicit or indicated by <tt>{…}</tt>. Terminals are | ||
575 | either plain hex numbers, encoded as bytes, or have a <tt>.format</tt> | ||
576 | suffix. | ||
577 | </p> | ||
578 | <pre> | ||
579 | object → nil | false | true | ||
580 | | null | lightud32 | lightud64 | ||
581 | | int | num | tab | tab_mt | ||
582 | | int64 | uint64 | complex | ||
583 | | string | ||
584 | |||
585 | nil → 0x00 | ||
586 | false → 0x01 | ||
587 | true → 0x02 | ||
588 | |||
589 | null → 0x03 // NULL lightuserdata | ||
590 | lightud32 → 0x04 data.I // 32 bit lightuserdata | ||
591 | lightud64 → 0x05 data.L // 64 bit lightuserdata | ||
592 | |||
593 | int → 0x06 int.I // int32_t | ||
594 | num → 0x07 double.L | ||
595 | |||
596 | tab → 0x08 // Empty table | ||
597 | | 0x09 h.U h*{object object} // Key/value hash | ||
598 | | 0x0a a.U a*object // 0-based array | ||
599 | | 0x0b a.U a*object h.U h*{object object} // Mixed | ||
600 | | 0x0c a.U (a-1)*object // 1-based array | ||
601 | | 0x0d a.U (a-1)*object h.U h*{object object} // Mixed | ||
602 | tab_mt → 0x0e (index-1).U tab // Metatable dict entry | ||
603 | |||
604 | int64 → 0x10 int.L // FFI int64_t | ||
605 | uint64 → 0x11 uint.L // FFI uint64_t | ||
606 | complex → 0x12 re.L im.L // FFI complex | ||
607 | |||
608 | string → (0x20+len).U len*char.B | ||
609 | | 0x0f (index-1).U // String dict entry | ||
610 | |||
611 | .B = 8 bit | ||
612 | .I = 32 bit little-endian | ||
613 | .L = 64 bit little-endian | ||
614 | .U = prefix-encoded 32 bit unsigned number n: | ||
615 | 0x00..0xdf → n.B | ||
616 | 0xe0..0x1fdf → (0xe0|(((n-0xe0)>>8)&0x1f)).B ((n-0xe0)&0xff).B | ||
617 | 0x1fe0.. → 0xff n.I | ||
618 | </pre> | ||
619 | |||
620 | <h2 id="error">Error handling</h2> | ||
621 | <p> | ||
622 | Many of the buffer methods can throw an error. Out-of-memory or usage | ||
623 | errors are best caught with an outer wrapper for larger parts of code. | ||
624 | There's not much one can do after that, anyway. | ||
625 | </p> | ||
626 | <p> | ||
627 | OTOH you may want to catch some errors individually. Buffer methods need | ||
628 | to receive the buffer object as the first argument. The Lua colon-syntax | ||
629 | <tt>obj:method()</tt> does that implicitly. But to wrap a method with | ||
630 | <tt>pcall()</tt>, the arguments need to be passed like this: | ||
631 | </p> | ||
632 | <pre class="code"> | ||
633 | local ok, err = pcall(buf.encode, buf, obj) | ||
634 | if not ok then | ||
635 | -- Handle error in err. | ||
636 | end | ||
637 | </pre> | ||
638 | |||
639 | <h2 id="ffi_caveats">FFI caveats</h2> | ||
640 | <p> | ||
641 | The string buffer library has been designed to work well together with | ||
642 | the FFI library. But due to the low-level nature of the FFI library, | ||
643 | some care needs to be taken: | ||
644 | </p> | ||
645 | <p> | ||
646 | First, please remember that FFI pointers are zero-indexed. The space | ||
647 | returned by <tt>buf:reserve()</tt> and <tt>buf:ref()</tt> starts at the | ||
648 | returned pointer and ends before <tt>len</tt> bytes after that. | ||
649 | </p> | ||
650 | <p> | ||
651 | I.e. the first valid index is <tt>ptr[0]</tt> and the last valid index | ||
652 | is <tt>ptr[len-1]</tt>. If the returned length is zero, there's no valid | ||
653 | index at all. The returned pointer may even be <tt>NULL</tt>. | ||
654 | </p> | ||
655 | <p> | ||
656 | The space pointed to by the returned pointer is only valid as long as | ||
657 | the buffer is not modified in any way (neither append, nor consume, nor | ||
658 | reset, etc.). The pointer is also not a GC anchor for the buffer object | ||
659 | itself. | ||
660 | </p> | ||
661 | <p> | ||
662 | Buffer data is only guaranteed to be byte-aligned. Casting the returned | ||
663 | pointer to a data type with higher alignment may cause unaligned | ||
664 | accesses. It depends on the CPU architecture whether this is allowed or | ||
665 | not (it's always OK on x86/x64 and mostly OK on other modern | ||
666 | architectures). | ||
667 | </p> | ||
668 | <p> | ||
669 | FFI pointers or references do not count as GC anchors for an underlying | ||
670 | object. E.g. an <tt>array</tt> allocated with <tt>ffi.new()</tt> is | ||
671 | anchored by <tt>buf:set(array, len)</tt>, but not by | ||
672 | <tt>buf:set(array+offset, len)</tt>. The addition of the offset | ||
673 | creates a new pointer, even when the offset is zero. In this case, you | ||
674 | need to make sure there's still a reference to the original array as | ||
675 | long as its contents are in use by the buffer. | ||
676 | </p> | ||
677 | <p> | ||
678 | Even though each LuaJIT VM instance is single-threaded (but you can | ||
679 | create multiple VMs), FFI data structures can be accessed concurrently. | ||
680 | Be careful when reading/writing FFI cdata from/to buffers to avoid | ||
681 | concurrent accesses or modifications. In particular, the memory | ||
682 | referenced by <tt>buf:set(cdata, len)</tt> must not be modified | ||
683 | while buffer readers are working on it. Shared, but read-only memory | ||
684 | mappings of files are OK, but only if the file does not change. | ||
685 | </p> | ||
686 | <br class="flush"> | ||
687 | </div> | ||
688 | <div id="foot"> | ||
689 | <hr class="hide"> | ||
690 | Copyright © 2005-2022 | ||
691 | <span class="noprint"> | ||
692 | · | ||
693 | <a href="contact.html">Contact</a> | ||
694 | </span> | ||
695 | </div> | ||
696 | </body> | ||
697 | </html> | ||