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