]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | /* |
2 | * Buffer | |
3 | */ | |
4 | ||
5 | #include "duk_internal.h" | |
6 | ||
7 | DUK_EXTERNAL void *duk_resize_buffer(duk_context *ctx, duk_idx_t index, duk_size_t new_size) { | |
8 | duk_hthread *thr = (duk_hthread *) ctx; | |
9 | duk_hbuffer_dynamic *h; | |
10 | ||
11 | DUK_ASSERT_CTX_VALID(ctx); | |
12 | ||
13 | h = (duk_hbuffer_dynamic *) duk_require_hbuffer(ctx, index); | |
14 | DUK_ASSERT(h != NULL); | |
15 | ||
16 | if (!(DUK_HBUFFER_HAS_DYNAMIC(h) && !DUK_HBUFFER_HAS_EXTERNAL(h))) { | |
17 | DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_WRONG_BUFFER_TYPE); | |
18 | } | |
19 | ||
20 | /* maximum size check is handled by callee */ | |
21 | duk_hbuffer_resize(thr, h, new_size); | |
22 | ||
23 | return DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, h); | |
24 | } | |
25 | ||
26 | DUK_EXTERNAL void *duk_steal_buffer(duk_context *ctx, duk_idx_t index, duk_size_t *out_size) { | |
27 | duk_hthread *thr = (duk_hthread *) ctx; | |
28 | duk_hbuffer_dynamic *h; | |
29 | void *ptr; | |
30 | duk_size_t sz; | |
31 | ||
32 | DUK_ASSERT(ctx != NULL); | |
33 | ||
34 | h = (duk_hbuffer_dynamic *) duk_require_hbuffer(ctx, index); | |
35 | DUK_ASSERT(h != NULL); | |
36 | ||
37 | if (!(DUK_HBUFFER_HAS_DYNAMIC(h) && !DUK_HBUFFER_HAS_EXTERNAL(h))) { | |
38 | DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_WRONG_BUFFER_TYPE); | |
39 | } | |
40 | ||
41 | /* Forget the previous allocation, setting size to 0 and alloc to | |
42 | * NULL. Caller is responsible for freeing the previous allocation. | |
43 | * Getting the allocation and clearing it is done in the same API | |
44 | * call to avoid any chance of a realloc. | |
45 | */ | |
46 | ptr = DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, h); | |
47 | sz = DUK_HBUFFER_DYNAMIC_GET_SIZE(h); | |
48 | if (out_size) { | |
49 | *out_size = sz; | |
50 | } | |
51 | DUK_HBUFFER_DYNAMIC_SET_DATA_PTR_NULL(thr->heap, h); | |
52 | DUK_HBUFFER_DYNAMIC_SET_SIZE(h, 0); | |
53 | ||
54 | return ptr; | |
55 | } | |
56 | ||
57 | DUK_EXTERNAL void duk_config_buffer(duk_context *ctx, duk_idx_t index, void *ptr, duk_size_t len) { | |
58 | duk_hthread *thr = (duk_hthread *) ctx; | |
59 | duk_hbuffer_external *h; | |
60 | ||
61 | DUK_ASSERT(ctx != NULL); | |
62 | ||
63 | h = (duk_hbuffer_external *) duk_require_hbuffer(ctx, index); | |
64 | DUK_ASSERT(h != NULL); | |
65 | ||
66 | if (!DUK_HBUFFER_HAS_EXTERNAL(h)) { | |
67 | DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_WRONG_BUFFER_TYPE); | |
68 | } | |
69 | DUK_ASSERT(DUK_HBUFFER_HAS_DYNAMIC(h)); | |
70 | ||
71 | DUK_HBUFFER_EXTERNAL_SET_DATA_PTR(thr->heap, h, ptr); | |
72 | DUK_HBUFFER_EXTERNAL_SET_SIZE(h, len); | |
73 | } |