summaryrefslogtreecommitdiff
path: root/src/include/rc_string.hpp
blob: eec47d802dc02f3f1f154a0c43af751e37f4e41f (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
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
 * 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):
        m_ptr(x.m_ptr),
        m_len(x.m_len)
    {
        if( m_ptr ) *m_ptr += 1;
    }
    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 )
        {
            this->~RcString();
            m_ptr = x.m_ptr;
            m_len = x.m_len;
            if( m_ptr ) *m_ptr += 1;
        }
        return *this;
    }
    RcString& operator=(RcString&& x)
    {
        if( &x != this )
        {
            this->~RcString();
            m_ptr = x.m_ptr;
            m_len = x.m_len;
            x.m_ptr = nullptr;
            x.m_len = 0;
        }
        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();
    }
};