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
19 #include <mach-o/dyld.h>
22 _LIBCPP_BEGIN_NAMESPACE_STD
24 namespace __refstring_imp { namespace {
33 inline _Rep_base* rep_from_data(const char *data_) noexcept {
34 char *data = const_cast<char *>(data_);
35 return reinterpret_cast<_Rep_base *>(data - sizeof(_Rep_base));
38 inline char * data_from_rep(_Rep_base *rep) noexcept {
39 char *data = reinterpret_cast<char *>(rep);
40 return data + sizeof(*rep);
43 #if defined(__APPLE__)
45 const char* compute_gcc_empty_string_storage() _NOEXCEPT
47 void* handle = dlopen("/usr/lib/libstdc++.6.dylib", RTLD_NOLOAD);
48 if (handle == nullptr)
50 void* sym = dlsym(handle, "_ZNSs4_Rep20_S_empty_rep_storageE");
53 return data_from_rep(reinterpret_cast<_Rep_base *>(sym));
58 get_gcc_empty_string_storage() _NOEXCEPT
60 static const char* p = compute_gcc_empty_string_storage();
65 }} // namespace __refstring_imp
67 using namespace __refstring_imp;
70 __libcpp_refstring::__libcpp_refstring(const char* msg) {
71 std::size_t len = strlen(msg);
72 _Rep_base* rep = static_cast<_Rep_base *>(::operator new(sizeof(*rep) + len + 1));
76 char *data = data_from_rep(rep);
77 std::memcpy(data, msg, len + 1);
82 __libcpp_refstring::__libcpp_refstring(const __libcpp_refstring &s) _NOEXCEPT
85 if (__uses_refcount())
86 __sync_add_and_fetch(&rep_from_data(__imp_)->count, 1);
90 __libcpp_refstring& __libcpp_refstring::operator=(__libcpp_refstring const& s) _NOEXCEPT {
91 bool adjust_old_count = __uses_refcount();
92 struct _Rep_base *old_rep = rep_from_data(__imp_);
94 if (__uses_refcount())
95 __sync_add_and_fetch(&rep_from_data(__imp_)->count, 1);
98 if (__sync_add_and_fetch(&old_rep->count, count_t(-1)) < 0)
100 ::operator delete(old_rep);
107 __libcpp_refstring::~__libcpp_refstring() {
108 if (__uses_refcount()) {
109 _Rep_base* rep = rep_from_data(__imp_);
110 if (__sync_add_and_fetch(&rep->count, count_t(-1)) < 0) {
111 ::operator delete(rep);
117 bool __libcpp_refstring::__uses_refcount() const {
119 return __imp_ != get_gcc_empty_string_storage();
125 _LIBCPP_END_NAMESPACE_STD
127 #endif //_LIBCPP___REFSTRING