blob: f64d87c6ff5c2a5c49b2a4137be2970beb5c68e9 [file] [log] [blame]
David Brazdil136f2942019-09-23 14:11:03 +01001/*
2 * Copyright 2019 The Hafnium Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "hf/string.h"
18
19#include "hf/static_assert.h"
20#include "hf/std.h"
21
22void string_init_empty(struct string *str)
23{
24 static_assert(sizeof(str->data) >= 1, "String buffer too small");
25 str->data[0] = '\0';
26}
27
28/**
29 * Caller must guarantee that `data` points to a NULL-terminated string.
30 * The constructor checks that it fits into the internal buffer and copies
31 * the string there.
32 */
David Brazdilb856be62020-03-25 10:14:55 +000033enum string_return_code string_init(struct string *str,
34 const struct memiter *data)
David Brazdil136f2942019-09-23 14:11:03 +010035{
David Brazdilb856be62020-03-25 10:14:55 +000036 const char *base = memiter_base(data);
37 size_t size = memiter_size(data);
38
David Brazdil136f2942019-09-23 14:11:03 +010039 /*
40 * Require that the value contains exactly one NULL character and that
41 * it is the last byte.
42 */
David Brazdilb856be62020-03-25 10:14:55 +000043 if (size < 1 || memchr(base, '\0', size) != &base[size - 1]) {
David Brazdil136f2942019-09-23 14:11:03 +010044 return STRING_ERROR_INVALID_INPUT;
45 }
46
47 if (size > sizeof(str->data)) {
48 return STRING_ERROR_TOO_LONG;
49 }
50
David Brazdilb856be62020-03-25 10:14:55 +000051 memcpy_s(str->data, sizeof(str->data), base, size);
David Brazdil136f2942019-09-23 14:11:03 +010052 return STRING_SUCCESS;
53}
54
55bool string_is_empty(const struct string *str)
56{
57 return str->data[0] == '\0';
58}
59
60const char *string_data(const struct string *str)
61{
62 return str->data;
63}
David Brazdilb856be62020-03-25 10:14:55 +000064
65/**
66 * Returns true if the iterator `data` contains string `str`.
67 * Only characters until the first null terminator are compared.
68 */
69bool string_eq(const struct string *str, const struct memiter *data)
70{
71 const char *base = memiter_base(data);
72 size_t len = memiter_size(data);
73
74 return (len <= sizeof(str->data)) &&
75 (strncmp(str->data, base, len) == 0);
76}