buffer.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. /**
  2. * @file buffer.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * Synopsis:
  32. * buffer([string data])
  33. *
  34. * Variables:
  35. * string (empty) - data in the buffer
  36. * string length - number of bytes in the buffer
  37. *
  38. * Description:
  39. * Implements an array of bytes which supports appending bytes and removing
  40. * bytes from the beginning. The buffer is implemented using chunks;
  41. * the time complexity of operations depends on the number of chunks affected,
  42. * and not on the actual number of bytes. Each append operation produces a single
  43. * chunk. In particular:
  44. *
  45. * Complexity of append and construction:
  46. * log(total number of chunks) + (time for copying data).
  47. * Complexity of consume:
  48. * log(total number of chunks) * (1 + (number of chunks in consumed range))
  49. * Complexity of referencing and unreferencing a range:
  50. * log(total number of chunks) * (1 + (number of chunks in referenced range))
  51. *
  52. * Synopsis:
  53. * buffer::append(string data)
  54. *
  55. * Description:
  56. * Appends the given data to the end of the buffer.
  57. *
  58. * Synopsis:
  59. * buffer::consume(string amount)
  60. *
  61. * Description:
  62. * Removes the specified number of bytes from the beginning of the buffer.
  63. * 'amount' must not be larger than the current length of the buffer.
  64. */
  65. #include <stddef.h>
  66. #include <string.h>
  67. #include <limits.h>
  68. #include <misc/debug.h>
  69. #include <misc/balloc.h>
  70. #include <misc/compare.h>
  71. #include <misc/offset.h>
  72. #include <structure/SAvl.h>
  73. #include <ncd/NCDModule.h>
  74. #include <ncd/static_strings.h>
  75. #include <ncd/extra/value_utils.h>
  76. #include <generated/blog_channel_ncd_buffer.h>
  77. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  78. struct chunk;
  79. #include "buffer_chunks_tree.h"
  80. #include <structure/SAvl_decl.h>
  81. struct buffer {
  82. struct instance *inst;
  83. ChunksTree chunks_tree;
  84. int refcnt;
  85. };
  86. struct chunk {
  87. struct buffer *buf;
  88. size_t offset;
  89. size_t length;
  90. ChunksTreeNode chunks_tree_node;
  91. int refcnt;
  92. char data[];
  93. };
  94. struct reference {
  95. struct chunk *first_chunk;
  96. size_t first_offset;
  97. size_t length;
  98. BRefTarget ref_target;
  99. };
  100. struct instance {
  101. NCDModuleInst *i;
  102. size_t offset;
  103. size_t total_length;
  104. struct buffer *buf;
  105. };
  106. #include "buffer_chunks_tree.h"
  107. #include <structure/SAvl_impl.h>
  108. static void instance_assert (struct instance *inst);
  109. static int instance_append (struct instance *inst, NCDValRef string);
  110. static void instance_consume (struct instance *inst, size_t amount);
  111. static struct buffer * buffer_init (struct instance *inst, NCDModuleInst *i);
  112. static void buffer_free (struct buffer *buf);
  113. static void buffer_detach (struct buffer *buf);
  114. static struct chunk * buffer_get_existing_chunk (struct buffer *buf, size_t offset);
  115. static struct chunk * chunk_init (struct instance *inst, size_t length);
  116. static void chunk_unref (struct chunk *c);
  117. static void chunk_assert (struct chunk *c);
  118. static struct reference * reference_init (struct instance *inst, size_t offset, size_t length, NCDValComposedStringResource *out_resource);
  119. static void reference_ref_target_func_release (BRefTarget *ref_target);
  120. static void reference_assert (struct reference *ref);
  121. static void reference_resource_func_getptr (void *user, size_t offset, const char **out_data, size_t *out_length);
  122. static void instance_assert (struct instance *inst)
  123. {
  124. ASSERT(inst->buf->inst == inst)
  125. }
  126. static int instance_append (struct instance *inst, NCDValRef string)
  127. {
  128. instance_assert(inst);
  129. ASSERT(NCDVal_IsString(string))
  130. size_t length = NCDVal_StringLength(string);
  131. // if string is empty do nothing, we can't make an empty chunk
  132. if (length == 0) {
  133. return 1;
  134. }
  135. // init chunk
  136. struct chunk *c = chunk_init(inst, length);
  137. if (!c) {
  138. return 0;
  139. }
  140. // copy data to chunk
  141. NCDVal_StringCopyOut(string, 0, length, c->data);
  142. return 1;
  143. }
  144. static void instance_consume (struct instance *inst, size_t amount)
  145. {
  146. instance_assert(inst);
  147. ASSERT(amount <= inst->total_length - inst->offset)
  148. // nothing do to if amount is zero
  149. if (amount == 0) {
  150. return;
  151. }
  152. // find chunk where the byte in the buffer resides
  153. struct chunk *c = buffer_get_existing_chunk(inst->buf, inst->offset);
  154. // increment buffer offset
  155. inst->offset += amount;
  156. // unreference chunks which no longer contain buffer contents
  157. while (c && c->offset + c->length <= inst->offset) {
  158. struct chunk *next_c = ChunksTree_GetNext(&inst->buf->chunks_tree, 0, c);
  159. chunk_unref(c);
  160. c = next_c;
  161. }
  162. }
  163. static struct buffer * buffer_init (struct instance *inst, NCDModuleInst *i)
  164. {
  165. ASSERT(inst)
  166. // allocate structure
  167. struct buffer *buf = BAlloc(sizeof(*buf));
  168. if (!buf) {
  169. ModuleLog(i, BLOG_ERROR, "BAlloc failed");
  170. return NULL;
  171. }
  172. // set instance pointer
  173. buf->inst = inst;
  174. // init chunks tree
  175. ChunksTree_Init(&buf->chunks_tree);
  176. // set refcnt to 0 (number of reference objects)
  177. buf->refcnt = 0;
  178. return buf;
  179. }
  180. static void buffer_free (struct buffer *buf)
  181. {
  182. ASSERT(!buf->inst)
  183. ASSERT(ChunksTree_IsEmpty(&buf->chunks_tree))
  184. ASSERT(buf->refcnt == 0)
  185. // free structure
  186. BFree(buf);
  187. }
  188. static void buffer_detach (struct buffer *buf)
  189. {
  190. ASSERT(buf->inst)
  191. struct instance *inst = buf->inst;
  192. // consume entire buffer to free any chunks that aren't referenced
  193. instance_consume(inst, inst->total_length - inst->offset);
  194. // clear instance pointer
  195. buf->inst = NULL;
  196. // free buffer if there are no more chunks
  197. if (ChunksTree_IsEmpty(&buf->chunks_tree)) {
  198. buffer_free(buf);
  199. }
  200. }
  201. static struct chunk * buffer_get_existing_chunk (struct buffer *buf, size_t offset)
  202. {
  203. struct chunk *c = ChunksTree_GetLastLesserEqual(&buf->chunks_tree, 0, offset);
  204. ASSERT(c)
  205. chunk_assert(c);
  206. ASSERT(offset >= c->offset)
  207. ASSERT(offset < c->offset + c->length)
  208. return c;
  209. }
  210. static struct chunk * chunk_init (struct instance *inst, size_t length)
  211. {
  212. instance_assert(inst);
  213. ASSERT(length > 0)
  214. struct buffer *buf = inst->buf;
  215. // make sure length is not too large
  216. if (length >= SIZE_MAX - inst->total_length) {
  217. ModuleLog(inst->i, BLOG_ERROR, "length overflow");
  218. return NULL;
  219. }
  220. // allocate structure
  221. bsize_t size = bsize_add(bsize_fromsize(sizeof(struct chunk)), bsize_fromsize(length));
  222. struct chunk *c = BAllocSize(size);
  223. if (!c) {
  224. ModuleLog(inst->i, BLOG_ERROR, "BAllocSize failed");
  225. return NULL;
  226. }
  227. // set some members
  228. c->buf = buf;
  229. c->offset = inst->total_length;
  230. c->length = length;
  231. // insert into chunks tree
  232. int res = ChunksTree_Insert(&buf->chunks_tree, 0, c, NULL);
  233. B_ASSERT_USE(res)
  234. // set reference count to 1 (referenced by buffer contents)
  235. c->refcnt = 1;
  236. // increment buffer length
  237. inst->total_length += length;
  238. chunk_assert(c);
  239. return c;
  240. }
  241. static void chunk_unref (struct chunk *c)
  242. {
  243. chunk_assert(c);
  244. // decrement reference count
  245. c->refcnt--;
  246. // if reference count is not yet zero, do nothing else
  247. if (c->refcnt > 0) {
  248. return;
  249. }
  250. // remove from chunks tree
  251. ChunksTree_Remove(&c->buf->chunks_tree, 0, c);
  252. // free structure
  253. BFree(c);
  254. }
  255. static void chunk_assert (struct chunk *c)
  256. {
  257. ASSERT(c->buf)
  258. ASSERT(c->length > 0)
  259. ASSERT(!c->buf->inst || c->offset <= c->buf->inst->total_length)
  260. ASSERT(!c->buf->inst || c->length <= c->buf->inst->total_length - c->offset)
  261. ASSERT(c->refcnt > 0)
  262. }
  263. static struct reference * reference_init (struct instance *inst, size_t offset, size_t length, NCDValComposedStringResource *out_resource)
  264. {
  265. instance_assert(inst);
  266. struct buffer *buf = inst->buf;
  267. ASSERT(offset >= inst->offset)
  268. ASSERT(offset <= inst->total_length)
  269. ASSERT(length <= inst->total_length - offset)
  270. ASSERT(length > 0)
  271. ASSERT(out_resource)
  272. // check buffer reference count. This ensures we can always increment the
  273. // chunk reference counts, below. We use (INT_MAX - 1) here because the buffer
  274. // itself can also own references to chunks.
  275. if (buf->refcnt == INT_MAX - 1) {
  276. ModuleLog(inst->i, BLOG_ERROR, "too many references");
  277. return NULL;
  278. }
  279. // allocate structure
  280. struct reference *ref = BAlloc(sizeof(*ref));
  281. if (!ref) {
  282. ModuleLog(inst->i, BLOG_ERROR, "BAlloc failed");
  283. return NULL;
  284. }
  285. // find chunk where the first byte of the interval resides
  286. struct chunk *c = buffer_get_existing_chunk(buf, offset);
  287. // set some members
  288. ref->first_chunk = c;
  289. ref->first_offset = offset - c->offset;
  290. ref->length = length;
  291. // increment buffer reference count
  292. buf->refcnt++;
  293. // reference chunks
  294. do {
  295. struct chunk *next_c = ChunksTree_GetNext(&buf->chunks_tree, 0, c);
  296. ASSERT(c->refcnt < INT_MAX)
  297. c->refcnt++;
  298. c = next_c;
  299. } while (c && c->offset < offset + length);
  300. // init reference target
  301. BRefTarget_Init(&ref->ref_target, reference_ref_target_func_release);
  302. // write resource
  303. out_resource->func_getptr = reference_resource_func_getptr;
  304. out_resource->user = ref;
  305. out_resource->ref_target = &ref->ref_target;
  306. reference_assert(ref);
  307. return ref;
  308. }
  309. static void reference_ref_target_func_release (BRefTarget *ref_target)
  310. {
  311. struct reference *ref = UPPER_OBJECT(ref_target, struct reference, ref_target);
  312. reference_assert(ref);
  313. struct buffer *buf = ref->first_chunk->buf;
  314. // compute offset
  315. size_t offset = ref->first_chunk->offset + ref->first_offset;
  316. // unreference chunks
  317. struct chunk *c = ref->first_chunk;
  318. do {
  319. struct chunk *next_c = ChunksTree_GetNext(&buf->chunks_tree, 0, c);
  320. chunk_unref(c);
  321. c = next_c;
  322. } while (c && c->offset < offset + ref->length);
  323. // decrement buffer reference count
  324. ASSERT(buf->refcnt > 0)
  325. buf->refcnt--;
  326. // free structure
  327. BFree(ref);
  328. // if the instance has died and there are no more chunks, free buffer
  329. if (!buf->inst && ChunksTree_IsEmpty(&buf->chunks_tree)) {
  330. buffer_free(buf);
  331. }
  332. }
  333. static void reference_assert (struct reference *ref)
  334. {
  335. ASSERT(ref->first_chunk)
  336. ASSERT(ref->first_offset < ref->first_chunk->length)
  337. ASSERT(ref->length > 0)
  338. chunk_assert(ref->first_chunk);
  339. }
  340. static void reference_resource_func_getptr (void *user, size_t offset, const char **out_data, size_t *out_length)
  341. {
  342. struct reference *ref = user;
  343. reference_assert(ref);
  344. ASSERT(offset < ref->length)
  345. ASSERT(out_data)
  346. ASSERT(out_length)
  347. // compute absolute offset of request
  348. size_t abs_offset = ref->first_chunk->offset + ref->first_offset + offset;
  349. // find chunk where the byte at the requested offset resides
  350. struct chunk *c = buffer_get_existing_chunk(ref->first_chunk->buf, abs_offset);
  351. // compute offset of this byte within the chunk
  352. size_t chunk_offset = abs_offset - c->offset;
  353. // return the data from this byte to the end of the chunk
  354. *out_data = c->data + chunk_offset;
  355. *out_length = c->length - chunk_offset;
  356. }
  357. static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  358. {
  359. struct instance *o = vo;
  360. o->i = i;
  361. // pass instance pointer to methods
  362. NCDModuleInst_Backend_PassMemToMethods(i);
  363. // read arguments
  364. NCDValRef data_arg = NCDVal_NewInvalid();
  365. if (!NCDVal_ListRead(params->args, 0) &&
  366. !NCDVal_ListRead(params->args, 1, &data_arg)
  367. ) {
  368. ModuleLog(i, BLOG_ERROR, "wrong arity");
  369. goto fail0;
  370. }
  371. if (!NCDVal_IsInvalid(data_arg) && !NCDVal_IsString(data_arg)) {
  372. ModuleLog(i, BLOG_ERROR, "wrong type");
  373. goto fail0;
  374. }
  375. // set offset and total length
  376. o->offset = 0;
  377. o->total_length = 0;
  378. // allocate buffer
  379. o->buf = buffer_init(o, i);
  380. if (!o->buf) {
  381. goto fail0;
  382. }
  383. // append initial data
  384. if (!NCDVal_IsInvalid(data_arg)) {
  385. if (!instance_append(o, data_arg)) {
  386. goto fail1;
  387. }
  388. }
  389. // signal up
  390. NCDModuleInst_Backend_Up(i);
  391. return;
  392. fail1:
  393. o->buf->inst = NULL;
  394. buffer_free(o->buf);
  395. fail0:
  396. NCDModuleInst_Backend_DeadError(i);
  397. }
  398. static void func_die (void *vo)
  399. {
  400. struct instance *o = vo;
  401. instance_assert(o);
  402. // detach buffer from instance
  403. buffer_detach(o->buf);
  404. // die
  405. NCDModuleInst_Backend_Dead(o->i);
  406. }
  407. static int func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  408. {
  409. struct instance *o = vo;
  410. instance_assert(o);
  411. if (name == NCD_STRING_EMPTY) {
  412. if (o->total_length - o->offset == 0) {
  413. *out = NCDVal_NewStringUninitialized(mem, 0);
  414. } else {
  415. NCDValComposedStringResource resource;
  416. struct reference *ref = reference_init(o, o->offset, o->total_length - o->offset, &resource);
  417. if (!ref) {
  418. goto fail;
  419. }
  420. *out = NCDVal_NewComposedString(mem, resource, 0, ref->length);
  421. BRefTarget_Deref(resource.ref_target);
  422. }
  423. return 1;
  424. }
  425. if (name == NCD_STRING_LENGTH) {
  426. *out = ncd_make_uintmax(mem, o->total_length - o->offset);
  427. return 1;
  428. }
  429. return 0;
  430. fail:
  431. *out = NCDVal_NewInvalid();
  432. return 1;
  433. }
  434. static void append_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  435. {
  436. // read arguments
  437. NCDValRef data_arg;
  438. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  439. ModuleLog(i, BLOG_ERROR, "wrong arity");
  440. goto fail0;
  441. }
  442. if (!NCDVal_IsString(data_arg)) {
  443. ModuleLog(i, BLOG_ERROR, "wrong type");
  444. goto fail0;
  445. }
  446. // get instance
  447. struct instance *inst = params->method_user;
  448. // append
  449. if (!instance_append(inst, data_arg)) {
  450. ModuleLog(i, BLOG_ERROR, "instance_append failed");
  451. goto fail0;
  452. }
  453. // go up
  454. NCDModuleInst_Backend_Up(i);
  455. return;
  456. fail0:
  457. NCDModuleInst_Backend_DeadError(i);
  458. }
  459. static void consume_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  460. {
  461. // read arguments
  462. NCDValRef amount_arg;
  463. if (!NCDVal_ListRead(params->args, 1, &amount_arg)) {
  464. ModuleLog(i, BLOG_ERROR, "wrong arity");
  465. goto fail0;
  466. }
  467. if (!NCDVal_IsString(amount_arg)) {
  468. ModuleLog(i, BLOG_ERROR, "wrong type");
  469. goto fail0;
  470. }
  471. // parse amount
  472. uintmax_t amount;
  473. if (!ncd_read_uintmax(amount_arg, &amount)) {
  474. ModuleLog(i, BLOG_ERROR, "wrong amount");
  475. goto fail0;
  476. }
  477. // get instance
  478. struct instance *inst = params->method_user;
  479. // check amount
  480. if (amount > inst->total_length - inst->offset) {
  481. ModuleLog(i, BLOG_ERROR, "amount is more than buffer length");
  482. goto fail0;
  483. }
  484. // consume
  485. instance_consume(inst, amount);
  486. // go up
  487. NCDModuleInst_Backend_Up(i);
  488. return;
  489. fail0:
  490. NCDModuleInst_Backend_DeadError(i);
  491. }
  492. static struct NCDModule modules[] = {
  493. {
  494. .type = "buffer",
  495. .func_new2 = func_new,
  496. .func_die = func_die,
  497. .func_getvar2 = func_getvar,
  498. .alloc_size = sizeof(struct instance),
  499. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  500. }, {
  501. .type = "buffer::append",
  502. .func_new2 = append_func_new,
  503. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  504. }, {
  505. .type = "buffer::consume",
  506. .func_new2 = consume_func_new,
  507. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  508. }, {
  509. .type = NULL
  510. }
  511. };
  512. const struct NCDModuleGroup ncdmodule_buffer = {
  513. .modules = modules
  514. };