1 /* Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file. */
8 /* String pool holds a large pile of strings. */
9 /* It is up to higher level data structures to avoid duplicates. */
10 /* It is up to higher level data structures to provide fast lookups. */
12 /* _GNU_SOURCE must be defined prior to the inclusion of string.h
13 * so that strnlen is available with glibc */
17 #include "xray/xray_priv.h"
21 struct XRayStringPoolNode
{
22 struct XRayStringPoolNode
* next
;
23 char strings
[XRAY_STRING_POOL_NODE_SIZE
];
27 struct XRayStringPool
{
28 struct XRayStringPoolNode
* head
;
29 struct XRayStringPoolNode
* current
;
34 static struct XRayStringPoolNode
* XRayStringPoolAllocNode() {
35 struct XRayStringPoolNode
* s
;
36 s
= (struct XRayStringPoolNode
*)XRayMalloc(sizeof(*s
));
42 static int XRayStringPoolCurrentNodeSpaceAvail(struct XRayStringPool
* pool
) {
44 return (XRAY_STRING_POOL_NODE_SIZE
- i
) - 1;
48 /* Append a string to the string pool. */
49 char* XRayStringPoolAppend(struct XRayStringPool
* pool
, const char* src
) {
50 /* Add +1 to STRING_POOL_NODE_SIZE to detect large strings */
51 /* Add +1 to strnlen result to account for string termination */
52 int n
= strnlen(src
, XRAY_STRING_POOL_NODE_SIZE
+ 1) + 1;
53 int a
= XRayStringPoolCurrentNodeSpaceAvail(pool
);
55 /* Don't accept strings larger than the pool node. */
56 if (n
>= (XRAY_STRING_POOL_NODE_SIZE
- 1))
58 /* If string doesn't fit, alloc a new node. */
60 pool
->current
->next
= XRayStringPoolAllocNode();
61 pool
->current
= pool
->current
->next
;
64 /* Copy string and return a pointer to copy. */
65 dst
= &pool
->current
->strings
[pool
->index
];
72 /* Create & initialize a string pool instance. */
73 struct XRayStringPool
* XRayStringPoolCreate() {
74 struct XRayStringPool
* pool
;
75 pool
= (struct XRayStringPool
*)XRayMalloc(sizeof(*pool
));
76 pool
->head
= XRayStringPoolAllocNode();
77 pool
->current
= pool
->head
;
82 /* Free a string pool. */
83 void XRayStringPoolFree(struct XRayStringPool
* pool
) {
84 struct XRayStringPoolNode
* n
= pool
->head
;
86 struct XRayStringPoolNode
* c
= n
;