1 /*=========================================================================
3 Program: Visualization Toolkit
4 Module: vtkParseString.c
6 Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
8 See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
10 This software is distributed WITHOUT ANY WARRANTY; without even
11 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12 PURPOSE. See the above copyright notice for more information.
14 =========================================================================*/
15 /*-------------------------------------------------------------------------
16 Copyright (c) 2012 David Gobbi.
18 Contributed to the VisualizationToolkit by the author in April 2012
19 under the terms of the Visualization Toolkit 2008 copyright.
20 -------------------------------------------------------------------------*/
22 #include "vtkParseString.h"
26 /*----------------------------------------------------------------
27 * String utility methods
29 * Strings are centrally allocated and are const. They should not
30 * be freed until the parse is complete and all the data structures
31 * generated by the parse have been freed.
34 /* allocate a string of n+1 bytes */
35 void vtkParse_InitStringCache(StringCache *cache)
37 cache->NumberOfChunks = 0;
43 /* allocate a string of n+1 bytes */
44 char *vtkParse_NewString(StringCache *cache, size_t n)
49 if (cache->ChunkSize == 0)
51 cache->ChunkSize = 8176;
54 // align next start position on an 8-byte boundary
55 nextPosition = (((cache->Position + n + 8) | 7 ) - 7);
57 if (cache->NumberOfChunks == 0 || nextPosition > cache->ChunkSize)
59 if (n + 1 > cache->ChunkSize)
61 cache->ChunkSize = n + 1;
63 cp = (char *)malloc(cache->ChunkSize);
65 /* if empty, alloc for the first time */
66 if (cache->NumberOfChunks == 0)
68 cache->Chunks = (char **)malloc(sizeof(char *));
70 /* if count is power of two, reallocate with double size */
71 else if ((cache->NumberOfChunks & (cache->NumberOfChunks-1)) == 0)
73 cache->Chunks = (char **)realloc(
74 cache->Chunks, (2*cache->NumberOfChunks)*sizeof(char *));
77 cache->Chunks[cache->NumberOfChunks++] = cp;
80 nextPosition = (((n + 8) | 7) - 7);
83 cp = &cache->Chunks[cache->NumberOfChunks-1][cache->Position];
86 cache->Position = nextPosition;
91 /* free all allocated strings */
92 void vtkParse_FreeStringCache(StringCache *cache)
96 for (i = 0; i < cache->NumberOfChunks; i++)
98 free(cache->Chunks[i]);
105 cache->Chunks = NULL;
106 cache->NumberOfChunks = 0;
109 /* duplicate the first n bytes of a string and terminate it */
110 const char *vtkParse_CacheString(StringCache *cache, const char *in, size_t n)
114 res = vtkParse_NewString(cache, n);