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_H
11 #define _LIBCPP_REFSTRING_H
19 #include <mach-o/dyld.h>
21 #include "atomic_support.h"
23 _LIBCPP_BEGIN_NAMESPACE_STD
25 namespace __refstring_imp { namespace {
34 inline _Rep_base* rep_from_data(const char *data_) noexcept {
35 char *data = const_cast<char *>(data_);
36 return reinterpret_cast<_Rep_base *>(data - sizeof(_Rep_base));
39 inline char * data_from_rep(_Rep_base *rep) noexcept {
40 char *data = reinterpret_cast<char *>(rep);
41 return data + sizeof(*rep);
44 #if defined(__APPLE__)
46 const char* compute_gcc_empty_string_storage() _NOEXCEPT
48 void* handle = dlopen("/usr/lib/libstdc++.6.dylib", RTLD_NOLOAD);
49 if (handle == nullptr)
51 void* sym = dlsym(handle, "_ZNSs4_Rep20_S_empty_rep_storageE");
54 return data_from_rep(reinterpret_cast<_Rep_base *>(sym));
59 get_gcc_empty_string_storage() _NOEXCEPT
61 static const char* p = compute_gcc_empty_string_storage();
66 }} // namespace __refstring_imp
68 using namespace __refstring_imp;
71 __libcpp_refstring::__libcpp_refstring(const char* msg) {
72 std::size_t len = strlen(msg);
73 _Rep_base* rep = static_cast<_Rep_base *>(::operator new(sizeof(*rep) + len + 1));
77 char *data = data_from_rep(rep);
78 std::memcpy(data, msg, len + 1);
83 __libcpp_refstring::__libcpp_refstring(const __libcpp_refstring &s) _NOEXCEPT
86 if (__uses_refcount())
87 __libcpp_atomic_add(&rep_from_data(__imp_)->count, 1);
91 __libcpp_refstring& __libcpp_refstring::operator=(__libcpp_refstring const& s) _NOEXCEPT {
92 bool adjust_old_count = __uses_refcount();
93 struct _Rep_base *old_rep = rep_from_data(__imp_);
95 if (__uses_refcount())
96 __libcpp_atomic_add(&rep_from_data(__imp_)->count, 1);
99 if (__libcpp_atomic_add(&old_rep->count, count_t(-1)) < 0)
101 ::operator delete(old_rep);
108 __libcpp_refstring::~__libcpp_refstring() {
109 if (__uses_refcount()) {
110 _Rep_base* rep = rep_from_data(__imp_);
111 if (__libcpp_atomic_add(&rep->count, count_t(-1)) < 0) {
112 ::operator delete(rep);
118 bool __libcpp_refstring::__uses_refcount() const {
120 return __imp_ != get_gcc_empty_string_storage();
126 _LIBCPP_END_NAMESPACE_STD
128 #endif //_LIBCPP_REFSTRING_H