1 //===------------------------ __refstring ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef _LIBCPP___REFSTRING
11 #define _LIBCPP___REFSTRING
18 #include <mach-o/dyld.h>
21 _LIBCPP_BEGIN_NAMESPACE_STD
23 class _LIBCPP_HIDDEN __libcpp_refstring
39 rep_from_data(const char *data_) _NOEXCEPT
41 char *data = const_cast<char *>(data_);
42 return reinterpret_cast<_Rep_base *>(data - sizeof(_Rep_base));
46 data_from_rep(_Rep_base *rep) _NOEXCEPT
48 char *data = reinterpret_cast<char *>(rep);
49 return data + sizeof(*rep);
55 compute_gcc_empty_string_storage() _NOEXCEPT
57 void* handle = dlopen("/usr/lib/libstdc++.6.dylib", RTLD_NOLOAD);
58 if (handle == nullptr)
60 void* sym = dlsym(handle, "_ZNSs4_Rep20_S_empty_rep_storageE");
63 return data_from_rep(reinterpret_cast<_Rep_base *>(sym));
68 get_gcc_empty_string_storage() _NOEXCEPT
70 static const char* p = compute_gcc_empty_string_storage();
77 return str_ != get_gcc_empty_string_storage();
88 explicit __libcpp_refstring(const char* msg) {
89 std::size_t len = strlen(msg);
90 _Rep_base* rep = static_cast<_Rep_base *>(::operator new(sizeof(*rep) + len + 1));
94 char *data = data_from_rep(rep);
95 std::memcpy(data, msg, len + 1);
99 __libcpp_refstring(const __libcpp_refstring& s) _NOEXCEPT : str_(s.str_)
102 __sync_add_and_fetch(&rep_from_data(str_)->count, 1);
105 __libcpp_refstring& operator=(const __libcpp_refstring& s) _NOEXCEPT
107 bool adjust_old_count = uses_refcount();
108 struct _Rep_base *old_rep = rep_from_data(str_);
111 __sync_add_and_fetch(&rep_from_data(str_)->count, 1);
112 if (adjust_old_count)
114 if (__sync_add_and_fetch(&old_rep->count, count_t(-1)) < 0)
116 ::operator delete(old_rep);
122 ~__libcpp_refstring()
126 _Rep_base* rep = rep_from_data(str_);
127 if (__sync_add_and_fetch(&rep->count, count_t(-1)) < 0)
129 ::operator delete(rep);
134 const char* c_str() const _NOEXCEPT {return str_;}
137 _LIBCPP_END_NAMESPACE_STD
139 #endif //_LIBCPP___REFSTRING