1 /*
2 * Copyright © 2023 Intel Corporation.
3 * SPDX-License-Identifier: MIT
4 */
5
6 #include <gtest/gtest.h>
7 #include "util/ralloc.h"
8
TEST(LinearAlloc,Basic)9 TEST(LinearAlloc, Basic)
10 {
11 void *ctx = ralloc_context(NULL);
12 linear_ctx *lin_ctx = linear_context(ctx);
13
14 for (unsigned i = 0; i < 1024; i++) {
15 linear_alloc_child(lin_ctx, i * 4);
16 }
17
18 ralloc_free(ctx);
19 }
20
TEST(LinearAlloc,RallocParent)21 TEST(LinearAlloc, RallocParent)
22 {
23 void *ctx = ralloc_context(NULL);
24 linear_ctx *lin_ctx = linear_context(ctx);
25 EXPECT_EQ(ralloc_parent_of_linear_context(lin_ctx), ctx);
26 ralloc_free(ctx);
27 }
28
TEST(LinearAlloc,StrCat)29 TEST(LinearAlloc, StrCat)
30 {
31 void *ctx = ralloc_context(NULL);
32 linear_ctx *lin_ctx = linear_context(ctx);
33
34 char *s = linear_strdup(lin_ctx, "hello,");
35 bool ok = linear_strcat(lin_ctx, &s, " triangle");
36 EXPECT_TRUE(ok);
37 EXPECT_STREQ(s, "hello, triangle");
38
39 ralloc_free(ctx);
40 }
41
TEST(LinearAlloc,RewriteTail)42 TEST(LinearAlloc, RewriteTail)
43 {
44 void *ctx = ralloc_context(NULL);
45 linear_ctx *lin_ctx = linear_context(ctx);
46
47 char *s = linear_strdup(lin_ctx, "hello, world");
48 size_t start = 7;
49 bool ok = linear_asprintf_rewrite_tail(lin_ctx, &s, &start, "%s", "triangle");
50 EXPECT_TRUE(ok);
51 EXPECT_STREQ(s, "hello, triangle");
52 EXPECT_EQ(start, 7 + 8);
53
54 ralloc_free(ctx);
55 }
56
TEST(LinearAlloc,AvoidWasteAfterLargeAlloc)57 TEST(LinearAlloc, AvoidWasteAfterLargeAlloc)
58 {
59 void *ctx = ralloc_context(NULL);
60 linear_ctx *lin_ctx = linear_context(ctx);
61
62 char *first = (char *) linear_alloc_child(lin_ctx, 32);
63
64 /* Large allocation that would force a larger buffer. */
65 linear_alloc_child(lin_ctx, 1024 * 16);
66
67 char *second = (char *) linear_alloc_child(lin_ctx, 32);
68
69 EXPECT_EQ(second - first, 32);
70
71 ralloc_free(ctx);
72 }
73
TEST(LinearAlloc,Options)74 TEST(LinearAlloc, Options)
75 {
76 void *ctx = ralloc_context(NULL);
77
78 linear_opts opts = {};
79 opts.min_buffer_size = 8192;
80
81 linear_ctx *lin_ctx = linear_context_with_opts(ctx, &opts);
82
83 /* Assert allocations spanning the first 8192 bytes are contiguous. */
84 char *first = (char *)linear_alloc_child(lin_ctx, 1024);
85 for (int i = 1; i < 8; i++) {
86 char *ptr = (char *)linear_alloc_child(lin_ctx, 1024);
87 EXPECT_EQ(ptr - first, 1024 * i);
88 }
89
90 ralloc_free(ctx);
91 }
92