Пример #1
0
DUK_EXTERNAL void *duk_steal_buffer(duk_context *ctx, duk_idx_t index, duk_size_t *out_size) {
	duk_hthread *thr = (duk_hthread *) ctx;
	duk_hbuffer_dynamic *h;
	void *ptr;
	duk_size_t sz;

	DUK_ASSERT(ctx != NULL);

	h = (duk_hbuffer_dynamic *) duk_require_hbuffer(ctx, index);
	DUK_ASSERT(h != NULL);

	if (!DUK_HBUFFER_HAS_DYNAMIC(h)) {
		DUK_ERROR(thr, DUK_ERR_TYPE_ERROR, DUK_STR_BUFFER_NOT_DYNAMIC);
	}

	/* Forget the previous allocation, setting size to 0 and alloc to
	 * NULL.  Caller is responsible for freeing the previous allocation.
	 * Getting the allocation and clearing it is done in the same API
	 * call to avoid any chance of a realloc.
	 */
	ptr = DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(thr->heap, h);
	sz = DUK_HBUFFER_DYNAMIC_GET_SIZE(h);
	if (out_size) {
		*out_size = sz;
	}
	DUK_HBUFFER_DYNAMIC_SET_DATA_PTR_NULL(thr->heap, h);
	DUK_HBUFFER_DYNAMIC_SET_SIZE(h, 0);
	DUK_HBUFFER_DYNAMIC_SET_ALLOC_SIZE(h, 0);

	return ptr;
}
Пример #2
0
DUK_LOCAL void duk__print_hbuffer(duk__dprint_state *st, duk_hbuffer *h) {
	duk_fixedbuffer *fb = st->fb;
	duk_size_t i, n;
	duk_uint8_t *p;

	if (duk_fb_is_full(fb)) {
		return;
	}

	/* terminal type: no depth check */

	if (!h) {
		duk_fb_put_cstring(fb, "NULL");
		return;
	}

	if (DUK_HBUFFER_HAS_DYNAMIC(h)) {
		if (DUK_HBUFFER_HAS_EXTERNAL(h)) {
			duk_hbuffer_external *g = (duk_hbuffer_external *) h;
			duk_fb_sprintf(fb, "buffer:external:%p:%ld",
			               (void *) DUK_HBUFFER_EXTERNAL_GET_DATA_PTR(NULL, g),
			               (long) DUK_HBUFFER_EXTERNAL_GET_SIZE(g));
		} else {
			duk_hbuffer_dynamic *g = (duk_hbuffer_dynamic *) h;
			duk_fb_sprintf(fb, "buffer:dynamic:%p:%ld",
			               (void *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(NULL, g),
			               (long) DUK_HBUFFER_DYNAMIC_GET_SIZE(g));
		}
	} else {
		duk_fb_sprintf(fb, "buffer:fixed:%ld", (long) DUK_HBUFFER_GET_SIZE(h));
	}

#if defined(DUK_USE_REFERENCE_COUNTING)
	duk_fb_sprintf(fb, "/%lu", (unsigned long) DUK_HEAPHDR_GET_REFCOUNT(&h->hdr));
#endif

	if (st->hexdump) {
		duk_fb_sprintf(fb, "=[");
		n = DUK_HBUFFER_GET_SIZE(h);
		p = (duk_uint8_t *) DUK_HBUFFER_GET_DATA_PTR(NULL, h);
		for (i = 0; i < n; i++) {
			duk_fb_sprintf(fb, "%02lx", (unsigned long) p[i]);
		}
		duk_fb_sprintf(fb, "]");
	}
}