David Brazdil | 136f294 | 2019-09-23 14:11:03 +0100 | [diff] [blame^] | 1 | /* |
| 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 | #pragma once |
| 18 | |
| 19 | #include <stdbool.h> |
| 20 | #include <stddef.h> |
| 21 | |
| 22 | /** |
| 23 | * Maximum length of a string including the NULL terminator. |
| 24 | * This is an arbitrary number and can be adjusted to fit use cases. |
| 25 | */ |
| 26 | #define STRING_MAX_SIZE 32 |
| 27 | |
| 28 | enum string_return_code { |
| 29 | STRING_SUCCESS, |
| 30 | STRING_ERROR_INVALID_INPUT, |
| 31 | STRING_ERROR_TOO_LONG, |
| 32 | }; |
| 33 | |
| 34 | /** |
| 35 | * Statically-allocated string data structure with input validation to ensure |
| 36 | * strings are properly NULL-terminated. |
| 37 | * |
| 38 | * This is intentionally kept as simple as possible and should not be extended |
| 39 | * to perform complex string operations without a good use case. |
| 40 | */ |
| 41 | struct string { |
| 42 | char data[STRING_MAX_SIZE]; |
| 43 | }; |
| 44 | |
| 45 | /** |
| 46 | * Macro to initialize `struct string` from a string constant. |
| 47 | * Triggers a compilation error if the string does not fit into the buffer. |
| 48 | */ |
| 49 | #define STRING_INIT(str) ((struct string){.data = str}) |
| 50 | |
| 51 | enum string_return_code string_init(struct string *str, const char *data, |
| 52 | size_t size); |
| 53 | void string_init_empty(struct string *str); |
| 54 | bool string_is_empty(const struct string *str); |
| 55 | const char *string_data(const struct string *str); |