Files
quip/include/common/ptrbox.h
2026-03-21 19:01:30 -04:00

82 lines
1.7 KiB
C

/*
* Copyright (c) 2026, Mirocom Laboratories
* Provided under the BSD-3 clause
*
* Abtract:
* This file implements pointer boxes used to provide RAII-like
* allocation behavior.
* Author:
* Ian M. Moffett <ian@mirocom.org>
*/
#ifndef COMMON_PTRBOX_H
#define COMMON_PTRBOX_H 1
#include <stdint.h>
#include <stddef.h>
/*
* Represents a pointer box entry which stores
* a reference to allocated data and a next pointer.
*
* @data: Allocated data reference
* @next: Next entry
*/
struct ptrbox_entry {
void *data;
struct ptrbox_entry *next;
};
/*
* Represents a pointer box which holds a list of pointer
* box entries
*
* @head: Pointer box entry list head
* @entry_count: Number of entries
*/
struct ptrbox {
struct ptrbox_entry *head;
struct ptrbox_entry *tail;
size_t entry_count;
};
/*
* Initialize a pointer box
*
* @ptrbox: Pointer box to initialize
*
* Returns zero on success
*/
int ptrbox_init(struct ptrbox *ptrbox);
/*
* Duplicate a string and store the reference in a pointer box
*
* @ptrbox: Pointerbox to store reference within
* @s: String to duplicate
*
* Returns the duplicated string on success, otherwise a value
* of NULL on failure.
*/
char *ptrbox_strdup(struct ptrbox *ptrbox, const char *s);
/*
* Allocate a number of bytes on the heap and store the reference
*
* @ptrbox: Pointer box
* @length: Number of bytes to allocate
*
* Returns the base of the allocated memory on success, otherwise
* NULL on failure.
*/
void *ptrbox_malloc(struct ptrbox *ptrbox, size_t length);
/*
* Destroy all elements within a pointer box
*
* @ptrbox: Pointer box to destroy
*/
void ptrbox_destroy(struct ptrbox *ptrbox);
#endif /* !COMMON_PTRBOX_H */