Skip to content

Commit

Permalink
externalterm: add externalterm_to_term_copy
Browse files Browse the repository at this point in the history
Works like externalterm_to_term, but it makes a copy of data stored in
the buffer, so it can be safely used from NIFs.

Signed-off-by: Davide Bettio <[email protected]>
  • Loading branch information
bettio committed Oct 13, 2024
1 parent 74775d4 commit 9624f63
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ also non string parameters (e.g. `Enum.join([1, 2], ",")`
- Make external term serialize functions available without using `externalterm_to_binary` so terms
can be written directly to a buffer.
- Support for `erlang:list_to_integer/2`
- Add `externalterm_to_term_copy` that can be safely used from NIFs taking temporary buffers

### Changed

Expand Down
6 changes: 6 additions & 0 deletions src/libAtomVM/externalterm.c
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ term externalterm_to_term(const void *external_term, size_t size, Context *ctx,
return externalterm_to_term_internal(external_term, size, ctx, opts, &bytes_read, false);
}

term externalterm_to_term_copy(const void *external_term, size_t size, Context *ctx, ExternalTermOpts opts)
{
size_t bytes_read = 0;
return externalterm_to_term_internal(external_term, size, ctx, opts, &bytes_read, true);
}

enum ExternalTermResult externalterm_from_binary(Context *ctx, term *dst, term binary, size_t *bytes_read)
{
if (!term_is_binary(binary)) {
Expand Down
16 changes: 16 additions & 0 deletions src/libAtomVM/externalterm.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,22 @@ typedef enum
term externalterm_to_term(
const void *external_term, size_t size, Context *ctx, ExternalTermOpts opts);

/**
* @brief Gets a term from external term data, and makes a copy of all data.
*
* @details Deserialize an external term from external format and returns a term.
* @param external_term the external term that will be deserialized.
* @param size to allocate for term.
* @param ctx the context that owns the memory that will be allocated.
* @param opts if non-zero, use a heap fragment to store the generated
* terms. Otherwise, use the heap in the provided context. Note that when using the
* context heap, this function may call the GC, if there is insufficient space to
* store the generated terms.
* @returns a term.
*/
term externalterm_to_term_copy(
const void *external_term, size_t size, Context *ctx, ExternalTermOpts opts);

/**
* @brief Create a term from a binary.
*
Expand Down

0 comments on commit 9624f63

Please sign in to comment.