aboutsummaryrefslogtreecommitdiff
path: root/include/StringView.hpp
blob: c4e7ce3db98597ed8713c37dda1d00f7ffce71b6 (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
#pragma once

#include "types.hpp"
#include <cstring>
#include <cassert>

namespace dchat
{
    template <typename CharType>
    class BasicStringView
    {
    public:
        BasicStringView() : data(nullptr), size(0)
        {
            
        }

        BasicStringView(const BasicStringView<CharType> &other) : data(other.data), size(other.size)
        {

        }
        
        BasicStringView(const CharType *_data) : data(_data), size(strlen(_data))
        {
            
        }
        
        BasicStringView(const CharType *_data, usize _size) : data(_data), size(_size)
        {
            
        }
        
        BasicStringView<CharType>& operator = (const BasicStringView<CharType> &other)
        {
            data = other.data;
            size = other.size;
            return *this;
        }
        
        BasicStringView(BasicStringView<CharType> &&other)
        {
            data = other.data;
            size = other.size;
            
            other.data = nullptr;
            other.size = 0;
        }
        
        bool equals(const BasicStringView<CharType> &other) const
        {
            if(size != other.size) return false;
            return memcmp(data, other.data, size * sizeof(CharType)) == 0;
        }
        
        bool operator == (const BasicStringView<CharType> &other) const
        {
            return equals(other);
        }
        
        bool operator != (const BasicStringView<CharType> &other) const
        {
            return !equals(other);
        }
        
        CharType operator [] (usize index) const
        {
            assert(index < size);
            return data[index];
        }
        
        // Returns -1 if substr not found.
        // TODO: Make this more efficient
        usize find(const BasicStringView<CharType> &substr, usize offset = 0) const
        {
            if(substr.size == 0)
                return -1;
            
            if(offset + substr.size > size)
                return -1;
            
            for(usize i = offset; i < size - (substr.size - 1); ++i)
            {
                if(memcmp(data + i, substr.data, substr.size) == 0)
                    return i;
            }
            return -1;
        }
        
        const CharType *data;
        usize size;
    };
    
    using StringView = BasicStringView<char>;
    using StringViewUtf32 = BasicStringView<u32>;
}