summaryrefslogtreecommitdiff
path: root/src/include/rc_string.hpp
blob: 914228c643ac6f0ea6a1f5176d3ba3febe7aa0b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * include/rc_string.hpp
 * - Reference-counted string (used for spans)
 */
#pragma once

#include <cstring>
#include <ostream>

class RcString
{
    unsigned int*   m_ptr;
    unsigned int    m_len;
public:
    RcString():
        m_ptr(nullptr),
        m_len(0)
    {}
    RcString(const char* s, unsigned int len);
    RcString(const char* s):
        RcString(s, ::std::strlen(s))
    {
    }
    RcString(const ::std::string& s):
        RcString(s.data(), s.size())
    {
    }

    RcString(const RcString& x);
    RcString(RcString&& x):
        m_ptr(x.m_ptr),
        m_len(x.m_len)
    {
        x.m_ptr = nullptr;
        x.m_len = 0;
    }

    ~RcString();

    RcString& operator=(const RcString& x)
    {
        if( !(&x != this) ) throw "";

        this->~RcString();
        new (this) RcString(x);

        return *this;
    }
    RcString& operator=(RcString&& x)
    {
        if( !(&x != this) ) throw "";

        this->~RcString();
        new (this) RcString( ::std::move(x) );
        return *this;
    }


    const char* c_str() const {
        if( m_len > 0 ) {
            return reinterpret_cast<const char*>(m_ptr + 1);
        }
        else {
            return "";
        }
    }
    bool operator==(const RcString& s) const { return *this == s.c_str(); }
    bool operator==(const char* s) const;
    friend ::std::ostream& operator<<(::std::ostream& os, const RcString& x) {
        return os << x.c_str();
    }
};