blob: f6822d13feaa73bc6ee96f09abeb3032623e337a [file] [log] [blame]
David Brazdil136f2942019-09-23 14:11:03 +01001/*
2 * Copyright 2019 The Hafnium Authors.
3 *
Andrew Walbrane959ec12020-06-17 15:01:09 +01004 * Use of this source code is governed by a BSD-style
5 * license that can be found in the LICENSE file or at
6 * https://opensource.org/licenses/BSD-3-Clause.
David Brazdil136f2942019-09-23 14:11:03 +01007 */
8
9#include "hf/string.h"
10
11#include "hf/static_assert.h"
12#include "hf/std.h"
13
14void string_init_empty(struct string *str)
15{
16 static_assert(sizeof(str->data) >= 1, "String buffer too small");
17 str->data[0] = '\0';
18}
19
20/**
21 * Caller must guarantee that `data` points to a NULL-terminated string.
22 * The constructor checks that it fits into the internal buffer and copies
23 * the string there.
24 */
David Brazdilb856be62020-03-25 10:14:55 +000025enum string_return_code string_init(struct string *str,
26 const struct memiter *data)
David Brazdil136f2942019-09-23 14:11:03 +010027{
David Brazdilb856be62020-03-25 10:14:55 +000028 const char *base = memiter_base(data);
29 size_t size = memiter_size(data);
30
David Brazdil136f2942019-09-23 14:11:03 +010031 /*
32 * Require that the value contains exactly one NULL character and that
33 * it is the last byte.
34 */
David Brazdilb856be62020-03-25 10:14:55 +000035 if (size < 1 || memchr(base, '\0', size) != &base[size - 1]) {
David Brazdil136f2942019-09-23 14:11:03 +010036 return STRING_ERROR_INVALID_INPUT;
37 }
38
39 if (size > sizeof(str->data)) {
40 return STRING_ERROR_TOO_LONG;
41 }
42
David Brazdilb856be62020-03-25 10:14:55 +000043 memcpy_s(str->data, sizeof(str->data), base, size);
David Brazdil136f2942019-09-23 14:11:03 +010044 return STRING_SUCCESS;
45}
46
47bool string_is_empty(const struct string *str)
48{
49 return str->data[0] == '\0';
50}
51
52const char *string_data(const struct string *str)
53{
54 return str->data;
55}
David Brazdilb856be62020-03-25 10:14:55 +000056
57/**
58 * Returns true if the iterator `data` contains string `str`.
59 * Only characters until the first null terminator are compared.
60 */
61bool string_eq(const struct string *str, const struct memiter *data)
62{
63 const char *base = memiter_base(data);
64 size_t len = memiter_size(data);
65
66 return (len <= sizeof(str->data)) &&
67 (strncmp(str->data, base, len) == 0);
68}