summaryrefslogtreecommitdiff
path: root/AK/String.h
blob: bb18494986211ac356baf198b7b0219478fd1a8a (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
89
90
91
92
93
94
95
96
97
98
99
#pragma once

#include "ByteBuffer.h"
#include "RetainPtr.h"
#include "StringImpl.h"
#include "Traits.h"
#include "Vector.h"
#include <cstdio>

namespace AK {

class String {
public:
    ~String() { }

    String() { }
    String(const String& other)
        : m_impl(const_cast<String&>(other).m_impl.copyRef())
    {
    }

    String(String&& other)
        : m_impl(std::move(other.m_impl))
    {
    }

    String(const char* cstring)
        : m_impl(StringImpl::create(cstring))
    {
    }

    String(const char* cstring, size_t length)
        : m_impl(StringImpl::create(cstring, length))
    {
    }

    String(const StringImpl& impl)
        : m_impl(const_cast<StringImpl&>(impl))
    {
    }

    String(RetainPtr<StringImpl>&& impl)
        : m_impl(std::move(impl))
    {
    }

    String toLowercase() const
    {
        if (!m_impl)
            return String();
        return m_impl->toLowercase();
    }

    String toUppercase() const
    {
        if (!m_impl)
            return String();
        return m_impl->toUppercase();
    }

    Vector<String> split(char separator) const;
    String substring(size_t start, size_t length) const;

    bool isEmpty() const { return length() == 0; }
    unsigned length() const { return m_impl ? m_impl->length() : 0; }
    const char* characters() const { return m_impl ? m_impl->characters() : nullptr; }
    char operator[](unsigned i) const { ASSERT(m_impl); return (*m_impl)[i]; }

    bool operator==(const String&) const;
    bool operator!=(const String& other) const { return !(*this == other); }

    static String empty();

    StringImpl* impl() { return m_impl.ptr(); }
    const StringImpl* impl() const { return m_impl.ptr(); }

    String& operator=(String&& other)
    {
        if (this != &other) {
            m_impl = std::move(other.m_impl);
        }
        return *this;
    }

    ByteBuffer toByteBuffer() const;

private:
    RetainPtr<StringImpl> m_impl;
};

template<>
struct Traits<String> {
    static unsigned hash(const String& s) { return s.impl() ? s.impl()->hash() : 0; }
    static void dump(const String& s) { printf("%s", s.characters()); }
};

}

using AK::String;