1/**
2 * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved.
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 * http://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 * \author Jiliang.ljl
17 * \date Mar 2021
18 * \brief StringView interface
19 */
20
21#ifndef __AILEGO_STRING_STRING_VIEW_H__
22#define __AILEGO_STRING_STRING_VIEW_H__
23
24#include <string>
25
26namespace ailego {
27
28//! StringView provides a lightweight view into the string data provided by
29//! a `std::string`, double-quoted string literal, character array, or even
30//! another `StringView`.
31//!
32//! A `StringView` does *not* own the string to which it
33//! points, and that data cannot be modified through the view.
34class StringView {
35 public:
36 //! Default constructor
37 StringView() = default;
38
39 //! Construct from c-string
40 StringView(const char *str)
41 : data_(str), size_(str != nullptr ? strlen(str) : 0) {}
42
43 //! Construct from [str, str+s)
44 StringView(const char *str, size_t len) : data_(str), size_(len) {}
45
46 //! Construct from std::string
47 StringView(const std::string &str) : data_(str.data()), size_(str.size()) {}
48
49 //! Retrieve data of string
50 const char *data() const {
51 return data_;
52 }
53
54 //! Retrieve size of string
55 size_t size() const {
56 return size_;
57 }
58
59 //! Retrieve non-zero if it is empty
60 bool empty() const {
61 return size_ == 0;
62 }
63
64 private:
65 const char *data_{nullptr};
66 size_t size_{0};
67};
68
69} // namespace ailego
70
71#endif // __AILEGO_STRING_STRING_VIEW_H__
72