-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJSString.h
More file actions
67 lines (53 loc) · 1.66 KB
/
JSString.h
File metadata and controls
67 lines (53 loc) · 1.66 KB
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
#ifndef JS_STRING_H
#define JS_STRING_H
#include "GCObject.h"
struct JSString:
public GCObject {
char *buf;
int size;
int hashCode;
int getHashCode() {
if (hashCode == 0) hashCode = hashOf(buf, buf + size);
return hashCode;
}
void attach(const char *str) { buf = (char*)str; size = (int)strlen(str); hashCode = 0; }
void detach(){ buf = NULL; size = 0; hashCode = 0;}
~JSString() { free(buf); }
private:
JSString(const char *str): GCObject(GCT_String), hashCode(0) {
size = (int)strlen(str);
buf = (char*)malloc(size + 1);
strcpy(buf, str);
GCObjectManager::instance()->link(this);
}
JSString(): GCObject(GCT_String), buf(NULL), size(0), hashCode(0){}
private:
friend class JSStringManager;
};
struct JSStringContentHash {
int operator () (JSString* str) const {
return str->getHashCode();
}
};
struct JSStringContentEqual {
bool operator () (JSString* left, JSString *right) const {
if (left->size != right->size) return false;
return memcmp(left->buf, right->buf, left->size) == 0;
}
};
class JSStringManager {
public:
JSString* get(const char *str);
void notifyValidGCObjects(GCObject *obj);
static void createInstance() { s_ins = new JSStringManager(); }
static void destroyInstance() { delete s_ins; }
static JSStringManager* instance() { return s_ins; }
private:
unordered_set<JSString*, JSStringContentHash, JSStringContentEqual> m_strs;
private:
JSStringManager(){}
JSStringManager& operator = (const JSStringManager&);
JSStringManager(const JSStringManager&);
static JSStringManager *s_ins;
};
#endif