1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2021 - 2022, 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 * SPDX-License-Identifier: curl
23 ***************************************************************************/
25 #include "curl_setup.h"
29 #include "curl_memory.h"
32 #define SIGNATURE 0x5c48e9b2 /* Random pattern. */
35 * Init a bufref struct.
37 void Curl_bufref_init(struct bufref *br)
45 br->signature = SIGNATURE;
50 * Free the buffer and re-init the necessary fields. It doesn't touch the
51 * 'signature' field and thus this buffer reference can be reused.
54 void Curl_bufref_free(struct bufref *br)
57 DEBUGASSERT(br->signature == SIGNATURE);
58 DEBUGASSERT(br->ptr || !br->len);
60 if(br->ptr && br->dtor)
61 br->dtor((void *) br->ptr);
69 * Set the buffer reference to new values. The previously referenced buffer
70 * is released before assignment.
72 void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len,
75 DEBUGASSERT(ptr || !len);
76 DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
79 br->ptr = (const unsigned char *) ptr;
85 * Get a pointer to the referenced buffer.
87 const unsigned char *Curl_bufref_ptr(const struct bufref *br)
90 DEBUGASSERT(br->signature == SIGNATURE);
91 DEBUGASSERT(br->ptr || !br->len);
97 * Get the length of the referenced buffer data.
99 size_t Curl_bufref_len(const struct bufref *br)
102 DEBUGASSERT(br->signature == SIGNATURE);
103 DEBUGASSERT(br->ptr || !br->len);
108 CURLcode Curl_bufref_memdup(struct bufref *br, const void *ptr, size_t len)
110 unsigned char *cpy = NULL;
113 DEBUGASSERT(br->signature == SIGNATURE);
114 DEBUGASSERT(br->ptr || !br->len);
115 DEBUGASSERT(ptr || !len);
116 DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
119 cpy = malloc(len + 1);
121 return CURLE_OUT_OF_MEMORY;
123 memcpy(cpy, ptr, len);
127 Curl_bufref_set(br, cpy, len, curl_free);