blob: 4876a3f0f51aaafac1fc13f8c6a6c59a655337af [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 */
33enum string_return_code string_init(struct string *str, const char *data,
34 size_t size)
35{
36 /*
37 * Require that the value contains exactly one NULL character and that
38 * it is the last byte.
39 */
40 if (size < 1 || memchr(data, '\0', size) != &data[size - 1]) {
41 return STRING_ERROR_INVALID_INPUT;
42 }
43
44 if (size > sizeof(str->data)) {
45 return STRING_ERROR_TOO_LONG;
46 }
47
48 memcpy_s(str->data, sizeof(str->data), data, size);
49 return STRING_SUCCESS;
50}
51
52bool string_is_empty(const struct string *str)
53{
54 return str->data[0] == '\0';
55}
56
57const char *string_data(const struct string *str)
58{
59 return str->data;
60}