stretchy_buffer.h
This file
Path
deprecated/stretchy_buffer.h
263 lines · 11.3 KiB · C
Last changed by
stb_hexwave added, stretchy_buffer.h deprecatedSean Barrettbefore adoption559d759
History of this fileTake it
1// stretchy_buffer.h - v1.04 - public domain - nothings.org/stb2// a vector<>-like dynamic array for C3//4// version history:5// 1.04 - fix warning6// 1.03 - compile as C++ maybe7// 1.02 - tweaks to syntax for no good reason8// 1.01 - added a "common uses" documentation section9// 1.0 - fixed bug in the version I posted prematurely10// 0.9 - rewrite to try to avoid strict-aliasing optimization11// issues, but won't compile as C++12//13// Will probably not work correctly with strict-aliasing optimizations.14//15// The idea:16//17// This implements an approximation to C++ vector<> for C, in that it18// provides a generic definition for dynamic arrays which you can19// still access in a typesafe way using arr[i] or *(arr+i). However,20// it is simply a convenience wrapper around the common idiom of21// of keeping a set of variables (in a struct or globals) which store22// - pointer to array23// - the length of the "in-use" part of the array24// - the current size of the allocated array25//26// I find it to be the single most useful non-built-in-structure when27// programming in C (hash tables a close second), but to be clear28// it lacks many of the capabilities of C++ vector<>: there is no29// range checking, the object address isn't stable (see next section30// for details), the set of methods available is small (although31// the file stb.h has another implementation of stretchy buffers32// called 'stb_arr' which provides more methods, e.g. for insertion33// and deletion).34//35// How to use:36//37// Unlike other stb header file libraries, there is no need to38// define an _IMPLEMENTATION symbol. Every #include creates as39// much implementation is needed.40//41// stretchy_buffer.h does not define any types, so you do not42// need to #include it to before defining data types that are43// stretchy buffers, only in files that *manipulate* stretchy44// buffers.45//46// If you want a stretchy buffer aka dynamic array containing47// objects of TYPE, declare such an array as:48//49// TYPE *myarray = NULL;50//51// (There is no typesafe way to distinguish between stretchy52// buffers and regular arrays/pointers; this is necessary to53// make ordinary array indexing work on these objects.)54//55// Unlike C++ vector<>, the stretchy_buffer has the same56// semantics as an object that you manually malloc and realloc.57// The pointer may relocate every time you add a new object58// to it, so you:59//60// 1. can't take long-term pointers to elements of the array61// 2. have to return the pointer from functions which might expand it62// (either as a return value or by storing it to a ptr-to-ptr)63//64// Now you can do the following things with this array:65//66// sb_free(TYPE *a) free the array67// sb_count(TYPE *a) the number of elements in the array68// sb_push(TYPE *a, TYPE v) adds v on the end of the array, a la push_back69// sb_add(TYPE *a, int n) adds n uninitialized elements at end of array & returns pointer to first added70// sb_last(TYPE *a) returns an lvalue of the last item in the array71// a[n] access the nth (counting from 0) element of the array72//73// #define STRETCHY_BUFFER_NO_SHORT_NAMES to only export74// names of the form 'stb_sb_' if you have a name that would75// otherwise collide.76//77// Note that these are all macros and many of them evaluate78// their arguments more than once, so the arguments should79// be side-effect-free.80//81// Note that 'TYPE *a' in sb_push and sb_add must be lvalues82// so that the library can overwrite the existing pointer if83// the object has to be reallocated.84//85// In an out-of-memory condition, the code will try to86// set up a null-pointer or otherwise-invalid-pointer87// exception to happen later. It's possible optimizing88// compilers could detect this write-to-null statically89// and optimize away some of the code, but it should only90// be along the failure path. Nevertheless, for more security91// in the face of such compilers, #define STRETCHY_BUFFER_OUT_OF_MEMORY92// to a statement such as assert(0) or exit(1) or something93// to force a failure when out-of-memory occurs.94//95// Common use:96//97// The main application for this is when building a list of98// things with an unknown quantity, either due to loading from99// a file or through a process which produces an unpredictable100// number.101//102// My most common idiom is something like:103//104// SomeStruct *arr = NULL;105// while (something)106// {107// SomeStruct new_one;108// new_one.whatever = whatever;109// new_one.whatup = whatup;110// new_one.foobar = barfoo;111// sb_push(arr, new_one);112// }113//114// and various closely-related factorings of that. For example,115// you might have several functions to create/init new SomeStructs,116// and if you use the above idiom, you might prefer to make them117// return structs rather than take non-const-pointers-to-structs,118// so you can do things like:119//120// SomeStruct *arr = NULL;121// while (something)122// {123// if (case_A) {124// sb_push(arr, some_func1());125// } else if (case_B) {126// sb_push(arr, some_func2());127// } else {128// sb_push(arr, some_func3());129// }130// }131//132// Note that the above relies on the fact that sb_push doesn't133// evaluate its second argument more than once. The macros do134// evaluate the *array* argument multiple times, and numeric135// arguments may be evaluated multiple times, but you can rely136// on the second argument of sb_push being evaluated only once.137//138// Of course, you don't have to store bare objects in the array;139// if you need the objects to have stable pointers, store an array140// of pointers instead:141//142// SomeStruct **arr = NULL;143// while (something)144// {145// SomeStruct *new_one = malloc(sizeof(*new_one));146// new_one->whatever = whatever;147// new_one->whatup = whatup;148// new_one->foobar = barfoo;149// sb_push(arr, new_one);150// }151//152// How it works:153//154// A long-standing tradition in things like malloc implementations155// is to store extra data before the beginning of the block returned156// to the user. The stretchy buffer implementation here uses the157// same trick; the current-count and current-allocation-size are158// stored before the beginning of the array returned to the user.159// (This means you can't directly free() the pointer, because the160// allocated pointer is different from the type-safe pointer provided161// to the user.)162//163// The details are trivial and implementation is straightforward;164// the main trick is in realizing in the first place that it's165// possible to do this in a generic, type-safe way in C.166//167// Contributors:168//169// Timothy Wright (github:ZenToad)170//171// LICENSE172//173// See end of file for license information.174175#ifndef STB_STRETCHY_BUFFER_H_INCLUDED176#define STB_STRETCHY_BUFFER_H_INCLUDED177178#ifndef NO_STRETCHY_BUFFER_SHORT_NAMES179#define sb_free stb_sb_free180#define sb_push stb_sb_push181#define sb_count stb_sb_count182#define sb_add stb_sb_add183#define sb_last stb_sb_last184#endif185186#define stb_sb_free(a) ((a) ? free(stb__sbraw(a)),0 : 0)187#define stb_sb_push(a,v) (stb__sbmaybegrow(a,1), (a)[stb__sbn(a)++] = (v))188#define stb_sb_count(a) ((a) ? stb__sbn(a) : 0)189#define stb_sb_add(a,n) (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])190#define stb_sb_last(a) ((a)[stb__sbn(a)-1])191192#define stb__sbraw(a) ((int *) (void *) (a) - 2)193#define stb__sbm(a) stb__sbraw(a)[0]194#define stb__sbn(a) stb__sbraw(a)[1]195196#define stb__sbneedgrow(a,n) ((a)==0 || stb__sbn(a)+(n) >= stb__sbm(a))197#define stb__sbmaybegrow(a,n) (stb__sbneedgrow(a,(n)) ? stb__sbgrow(a,n) : 0)198#define stb__sbgrow(a,n) (*((void **)&(a)) = stb__sbgrowf((a), (n), sizeof(*(a))))199200#include <stdlib.h>201202static void * stb__sbgrowf(void *arr, int increment, int itemsize)203{204 int dbl_cur = arr ? 2*stb__sbm(arr) : 0;205 int min_needed = stb_sb_count(arr) + increment;206 int m = dbl_cur > min_needed ? dbl_cur : min_needed;207 int *p = (int *) realloc(arr ? stb__sbraw(arr) : 0, itemsize * m + sizeof(int)*2);208 if (p) {209 if (!arr)210 p[1] = 0;211 p[0] = m;212 return p+2;213 } else {214 #ifdef STRETCHY_BUFFER_OUT_OF_MEMORY215 STRETCHY_BUFFER_OUT_OF_MEMORY ;216 #endif217 return (void *) (2*sizeof(int)); // try to force a NULL pointer exception later218 }219}220#endif // STB_STRETCHY_BUFFER_H_INCLUDED221222223/*224------------------------------------------------------------------------------225This software is available under 2 licenses -- choose whichever you prefer.226------------------------------------------------------------------------------227ALTERNATIVE A - MIT License228Copyright (c) 2017 Sean Barrett229Permission is hereby granted, free of charge, to any person obtaining a copy of230this software and associated documentation files (the "Software"), to deal in231the Software without restriction, including without limitation the rights to232use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies233of the Software, and to permit persons to whom the Software is furnished to do234so, subject to the following conditions:235The above copyright notice and this permission notice shall be included in all236copies or substantial portions of the Software.237THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR238IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,239FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE240AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER241LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,242OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE243SOFTWARE.244------------------------------------------------------------------------------245ALTERNATIVE B - Public Domain (www.unlicense.org)246This is free and unencumbered software released into the public domain.247Anyone is free to copy, modify, publish, use, compile, sell, or distribute this248software, either in source code form or as a compiled binary, for any purpose,249commercial or non-commercial, and by any means.250In jurisdictions that recognize copyright laws, the author or authors of this251software dedicate any and all copyright interest in the software to the public252domain. We make this dedication for the benefit of the public at large and to253the detriment of our heirs and successors. We intend this dedication to be an254overt act of relinquishment in perpetuity of all present and future rights to255this software under copyright law.256THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR257IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,258FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE259AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN260ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION261WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.262------------------------------------------------------------------------------263*/