1#ifndef AWS_COMMON_STRING_INL
2#define AWS_COMMON_STRING_INL
3/*
4 * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License").
7 * You may not use this file except in compliance with the License.
8 * A copy of the License is located at
9 *
10 * http://aws.amazon.com/apache2.0
11 *
12 * or in the "license" file accompanying this file. This file is distributed
13 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
14 * express or implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 */
17
18#include <aws/common/string.h>
19
20AWS_EXTERN_C_BEGIN
21/**
22 * Equivalent to str->bytes.
23 */
24AWS_STATIC_IMPL
25const uint8_t *aws_string_bytes(const struct aws_string *str) {
26 AWS_PRECONDITION(aws_string_is_valid(str));
27 return str->bytes;
28}
29
30/**
31 * Equivalent to `(const char *)str->bytes`.
32 */
33AWS_STATIC_IMPL
34const char *aws_string_c_str(const struct aws_string *str) {
35 AWS_PRECONDITION(aws_string_is_valid(str));
36 return (const char *)str->bytes;
37}
38
39/**
40 * Evaluates the set of properties that define the shape of all valid aws_string structures.
41 * It is also a cheap check, in the sense it run in constant time (i.e., no loops or recursion).
42 */
43AWS_STATIC_IMPL
44bool aws_string_is_valid(const struct aws_string *str) {
45 return str && AWS_MEM_IS_READABLE(&str->bytes[0], str->len + 1) && str->bytes[str->len] == 0;
46}
47
48/**
49 * Best-effort checks aws_string invariants, when the str->len is unknown
50 */
51AWS_STATIC_IMPL
52bool aws_c_string_is_valid(const char *str) {
53 /* Knowing the actual length to check would require strlen(), which is
54 * a) linear time in the length of the string
55 * b) could already cause a memory violation for a non-zero-terminated string.
56 * But we know that a c-string must have at least one character, to store the null terminator
57 */
58 return str && AWS_MEM_IS_READABLE(str, 1);
59}
60AWS_EXTERN_C_END
61#endif /* AWS_COMMON_STRING_INL */
62