ext_buffer.html 23 KB

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