1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
27 #include "curl_memory.h"
30 #define SIGNATURE 0x5c48e9b2 /* Random pattern. */
33 * Init a bufref struct.
35 void Curl_bufref_init(struct bufref *br)
43 br->signature = SIGNATURE;
48 * Free the buffer and re-init the necessary fields. It doesn't touch the
49 * 'signature' field and thus this buffer reference can be reused.
52 void Curl_bufref_free(struct bufref *br)
55 DEBUGASSERT(br->signature == SIGNATURE);
56 DEBUGASSERT(br->ptr || !br->len);
58 if(br->ptr && br->dtor)
59 br->dtor((void *) br->ptr);
67 * Set the buffer reference to new values. The previously referenced buffer
68 * is released before assignment.
70 void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len,
73 DEBUGASSERT(ptr || !len);
74 DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
77 br->ptr = (const unsigned char *) ptr;
83 * Get a pointer to the referenced buffer.
85 const unsigned char *Curl_bufref_ptr(const struct bufref *br)
88 DEBUGASSERT(br->signature == SIGNATURE);
89 DEBUGASSERT(br->ptr || !br->len);
95 * Get the length of the referenced buffer data.
97 size_t Curl_bufref_len(const struct bufref *br)
100 DEBUGASSERT(br->signature == SIGNATURE);
101 DEBUGASSERT(br->ptr || !br->len);
106 CURLcode Curl_bufref_memdup(struct bufref *br, const void *ptr, size_t len)
108 unsigned char *cpy = NULL;
111 DEBUGASSERT(br->signature == SIGNATURE);
112 DEBUGASSERT(br->ptr || !br->len);
113 DEBUGASSERT(ptr || !len);
114 DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
117 cpy = malloc(len + 1);
119 return CURLE_OUT_OF_MEMORY;
121 memcpy(cpy, ptr, len);
125 Curl_bufref_set(br, cpy, len, curl_free);