1 /* 2 * Copyright (C) 2021 The Android Open Source Project 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 17 #pragma once 18 19 #include <memory> 20 #include <string> 21 22 namespace unwindstack { 23 24 // Ref-counted read-only string. Used to avoid string allocations/copies. 25 // It is intended to be transparent std::string replacement in most cases. 26 class SharedString { 27 public: SharedString()28 SharedString() : data_() {} SharedString(std::string && s)29 SharedString(std::string&& s) : data_(std::make_shared<const std::string>(std::move(s))) {} SharedString(const std::string & s)30 SharedString(const std::string& s) : SharedString(std::string(s)) {} SharedString(const char * s)31 SharedString(const char* s) : SharedString(std::string(s)) {} 32 clear()33 void clear() { data_.reset(); } is_null()34 bool is_null() const { return data_.get() == nullptr; } empty()35 bool empty() const { return is_null() ? true : data_->empty(); } c_str()36 const char* c_str() const { return is_null() ? "" : data_->c_str(); } 37 38 operator const std::string&() const { 39 [[clang::no_destroy]] static const std::string empty; 40 return data_ ? *data_.get() : empty; 41 } 42 string_view()43 operator std::string_view() const { return static_cast<const std::string&>(*this); } 44 45 private: 46 std::shared_ptr<const std::string> data_; 47 }; 48 49 static inline bool operator==(const SharedString& a, SharedString& b) { 50 return static_cast<std::string_view>(a) == static_cast<std::string_view>(b); 51 } 52 static inline bool operator==(const SharedString& a, std::string_view b) { 53 return static_cast<std::string_view>(a) == b; 54 } 55 static inline bool operator==(std::string_view a, const SharedString& b) { 56 return a == static_cast<std::string_view>(b); 57 } 58 static inline bool operator!=(const SharedString& a, SharedString& b) { 59 return !(a == b); 60 } 61 static inline bool operator!=(const SharedString& a, std::string_view b) { 62 return !(a == b); 63 } 64 static inline bool operator!=(std::string_view a, const SharedString& b) { 65 return !(a == b); 66 } 67 static inline std::string operator+(const SharedString& a, const char* b) { 68 return static_cast<const std::string&>(a) + b; 69 } 70 static inline std::string operator+(const char* a, const SharedString& b) { 71 return a + static_cast<const std::string&>(b); 72 } 73 74 } // namespace unwindstack 75