summaryrefslogtreecommitdiff
path: root/AK/StringImpl.h
blob: babca34e10415b50ccdcbf308feef5c0a54bd9d9 (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
#pragma once

#include "RetainPtr.h"
#include "Retainable.h"
#include "Types.h"

namespace AK {

enum ShouldChomp {
    NoChomp,
    Chomp
};

class StringImpl : public Retainable<StringImpl> {
public:
    static Retained<StringImpl> create_uninitialized(ssize_t length, char*& buffer);
    static RetainPtr<StringImpl> create(const char* cstring, ShouldChomp = NoChomp);
    static RetainPtr<StringImpl> create(const char* cstring, ssize_t length, ShouldChomp = NoChomp);
    Retained<StringImpl> to_lowercase() const;
    Retained<StringImpl> to_uppercase() const;

    static StringImpl& the_empty_stringimpl();

    ~StringImpl();

    ssize_t length() const { return m_length; }
    const char* characters() const { return m_characters; }
    char operator[](ssize_t i) const
    {
        ASSERT(i >= 0 && i < m_length);
        return m_characters[i];
    }

    unsigned hash() const
    {
        if (!m_hasHash)
            compute_hash();
        return m_hash;
    }

private:
    enum ConstructTheEmptyStringImplTag {
        ConstructTheEmptyStringImpl
    };
    explicit StringImpl(ConstructTheEmptyStringImplTag)
        : m_characters("")
    {
    }

    enum ConstructWithInlineBufferTag {
        ConstructWithInlineBuffer
    };
    StringImpl(ConstructWithInlineBufferTag, ssize_t length);

    void compute_hash() const;

    ssize_t m_length { 0 };
    mutable bool m_hasHash { false };
    const char* m_characters { nullptr };
    mutable unsigned m_hash { 0 };
    char m_inline_buffer[0];
};

inline dword string_hash(const char* characters, int length)
{
    dword hash = 0;
    for (int i = 0; i < length; ++i) {
        hash += (dword)characters[i];
        hash += (hash << 10);
        hash ^= (hash >> 6);
    }
    hash += hash << 3;
    hash ^= hash >> 11;
    hash += hash << 15;
    return hash;
}

}

using AK::Chomp;
using AK::string_hash;
using AK::StringImpl;