forked from NIVANorge/Mobius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_string.h
83 lines (68 loc) · 1.97 KB
/
token_string.h
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
//NOTE: This is a length-based string that does not have ownership of its data. Good for making substrings without having to reallocate.
struct token_string
{
token_string() : Data(nullptr), Length(0) {};
token_string(const char *);
const char *Data;
size_t Length;
bool Equals(const char *) const;
token_string Copy(bucket_allocator *Allocator = nullptr) const;
};
token_string::token_string(const char *DataIn)
{
Length = strlen(DataIn);
Data = DataIn;
}
std::ostream& operator<<(std::ostream& Os, const token_string& Str)
{
Os.write(Str.Data, Str.Length);
return Os;
}
bool operator==(const token_string &StrA, const token_string &StrB)
{
if(StrA.Length != StrB.Length) return false;
for(size_t At = 0; At < StrA.Length; ++At)
{
if(StrA.Data[At] != StrB.Data[At]) return false;
}
return true;
}
bool token_string::Equals(const char *Str) const
{
for(size_t At = 0; At < Length; ++At)
{
if(Str[At] == 0) return false;
if(Str[At] != Data[At]) return false;
}
if(Str[Length] != 0) return false;
return true;
}
token_string token_string::Copy(bucket_allocator *Allocator) const
{
token_string Result;
char *NewData;
if(Allocator)
NewData = Allocator->Allocate<char>(Length + 1);
else
NewData = (char *)malloc(Length + 1);
Result.Data = NewData;
Result.Length = Length;
NewData[Length] = '\0'; //NOTE: In case people want a 0-terminated string. This is sometimes used in the current code, but it is not that clean...
memcpy(NewData, Data, Length);
return Result;
}
//TODO: Borrowed hash function from https://stackoverflow.com/questions/20649864/c-unordered-map-with-char-as-key . We should look into it more..
struct token_string_hash_function
{
//BKDR Hash algorithm
int operator()(const token_string &Str) const
{
int Seed = 131;//31 131 1313 13131131313 etc//
int Hash = 0;
for(size_t At = 0; At < Str.Length; ++At)
{
Hash = (Hash * Seed) + Str.Data[At];
}
return Hash & (0x7FFFFFFF);
}
};