blob: bb05a8d3e9deaf3b12ea14874ead21de44e70bd2 [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#pragma once
10
David Brazdil136f2942019-09-23 14:11:03 +010011#include <stddef.h>
12
David Brazdilb856be62020-03-25 10:14:55 +000013#include "hf/memiter.h"
14
David Brazdil136f2942019-09-23 14:11:03 +010015/**
16 * Maximum length of a string including the NULL terminator.
17 * This is an arbitrary number and can be adjusted to fit use cases.
18 */
19#define STRING_MAX_SIZE 32
20
21enum string_return_code {
22 STRING_SUCCESS,
23 STRING_ERROR_INVALID_INPUT,
24 STRING_ERROR_TOO_LONG,
25};
26
27/**
28 * Statically-allocated string data structure with input validation to ensure
29 * strings are properly NULL-terminated.
30 *
31 * This is intentionally kept as simple as possible and should not be extended
32 * to perform complex string operations without a good use case.
33 */
34struct string {
35 char data[STRING_MAX_SIZE];
36};
37
38/**
39 * Macro to initialize `struct string` from a string constant.
40 * Triggers a compilation error if the string does not fit into the buffer.
41 */
Karl Meakin2ad6b662024-07-29 20:45:40 +010042#define STRING_INIT(str) ((struct string){.data = (str)})
David Brazdil136f2942019-09-23 14:11:03 +010043
David Brazdilb856be62020-03-25 10:14:55 +000044enum string_return_code string_init(struct string *str,
45 const struct memiter *data);
David Brazdil136f2942019-09-23 14:11:03 +010046void string_init_empty(struct string *str);
47bool string_is_empty(const struct string *str);
48const char *string_data(const struct string *str);
David Brazdilb856be62020-03-25 10:14:55 +000049bool string_eq(const struct string *str, const struct memiter *data);