xref: /curl/docs/internals/BUFREF.md (revision 20aa8d8f)
1<!--
2Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
3
4SPDX-License-Identifier: curl
5-->
6
7# bufref
8
9This is an internal module for handling buffer references. A referenced
10buffer is associated with its destructor function that is implicitly called
11when the reference is invalidated. Once referenced, a buffer cannot be
12reallocated.
13
14A data length is stored within the reference for binary data handling
15purposes; it is not used by the bufref API.
16
17The `struct bufref` is used to hold data referencing a buffer. The members of
18that structure **MUST NOT** be accessed or modified without using the dedicated
19bufref API.
20
21## `init`
22
23```c
24void Curl_bufref_init(struct bufref *br);
25```
26
27Initializes a `bufref` structure. This function **MUST** be called before any
28other operation is performed on the structure.
29
30Upon completion, the referenced buffer is `NULL` and length is zero.
31
32This function may also be called to bypass referenced buffer destruction while
33invalidating the current reference.
34
35## `free`
36
37```c
38void Curl_bufref_free(struct bufref *br);
39```
40
41Destroys the previously referenced buffer using its destructor and
42reinitializes the structure for a possible subsequent reuse.
43
44## `set`
45
46```c
47void Curl_bufref_set(struct bufref *br, const void *buffer, size_t length,
48                     void (*destructor)(void *));
49```
50
51Releases the previously referenced buffer, then assigns the new `buffer` to
52the structure, associated with its `destructor` function. The latter can be
53specified as `NULL`: this is the case when the referenced buffer is static.
54
55if `buffer` is NULL, `length` must be zero.
56
57## `memdup`
58
59```c
60CURLcode Curl_bufref_memdup(struct bufref *br, const void *data, size_t length);
61```
62
63Releases the previously referenced buffer, then duplicates the `length`-byte
64`data` into a buffer allocated via `malloc()` and references the latter
65associated with destructor `curl_free()`.
66
67An additional trailing byte is allocated and set to zero as a possible string
68null-terminator; it is not counted in the stored length.
69
70Returns `CURLE_OK` if successful, else `CURLE_OUT_OF_MEMORY`.
71
72## `ptr`
73
74```c
75const unsigned char *Curl_bufref_ptr(const struct bufref *br);
76```
77
78Returns a `const unsigned char *` to the referenced buffer.
79
80## `len`
81
82```c
83size_t Curl_bufref_len(const struct bufref *br);
84```
85
86Returns the stored length of the referenced buffer.
87