xref: /aosp_15_r20/external/tensorflow/tensorflow/cc/experimental/libtf/impl/string.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #ifndef TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_STRING_H_
16 #define TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_STRING_H_
17 
18 #include <iosfwd>
19 #include <string>
20 
21 namespace tf {
22 namespace libtf {
23 namespace impl {
24 
25 /** A string value.
26  *  This class wraps an interned, immutable string value. Currently, interned
27  *  values are never deleted, so memory usage increases without bound as new
28  *  strings are created.
29  */
30 class String final {
31  public:
32   /** Interning constructor.
33    * Interns the given string value.
34    */
35   explicit String(const char* s);
36 
String()37   String() : String("") {}
String(const String & s)38   String(const String& s) : value_(s.value_) {}
39 
40   // This is the same as the default equality operator, which works because
41   // we're interning all strings. It is specified here so we are explicit about
42   // it. We're not saying "= default;" because we can't use C++20 features yet.
43   bool operator==(const String& other) const { return value_ == other.value_; }
44 
str()45   const std::string& str() const { return *value_; }
46 
47   /** Absl hash function. */
48   template <typename H>
AbslHashValue(H h,const String & s)49   friend H AbslHashValue(H h, const String& s) {
50     return H::combine(std::move(h), *s.value_);
51   }
52 
53  private:
54   //! The interned string value. This is never null.
55   const std::string* value_;
56 };
57 
58 // This is defined in the `iostream.cc` file in this directory. It is not
59 // defined inline here because the `iosfwd` header does not provide enough
60 // functionality (in Windows), and we don't want to include `iostream` to avoid
61 // increasing the binary size.
62 std::ostream& operator<<(std::ostream& o, const String& str);
63 
64 }  // namespace impl
65 }  // namespace libtf
66 }  // namespace tf
67 
68 #endif  // TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_STRING_H_
69