[Snippet] StringIndexer

Scripts

14 years
edited 8 years
This system generates an index for any string below 8191.

Jass:

Code (jass) Select
1
/************************************************
2
*
3
*   StringIndexer
4
*   v1.0.0.2
5
*   By Magtheridon96
6
*
7
*   - Retrieves an index for a string below 8191
8
*   - Helps easy string data attachment
9
*
10
*   Optional:
11
*   ---------
12
*
13
*       - Table by Bribe
14
*
15
*   API:
16
*   ----
17
*
18
*       - function IndexString takes string s returns integer
19
*           - Indexes a string and returns the index
20
*       - function GetStringId takes string s returns integer
21
*           - Retrieves the index of an indexed string
22
*       - function GetStringById takes integer id returns string
23
*           - Returns the string corresponding to a certain Id
24
*
25
************************************************/
26
library StringIndexer requires optional Table
27
28
    globals
29
        private string array strings
30
        private integer count = 0
31
    endglobals
32
    
33
    static if LIBRARY_Table then
34
        private module Init
35
            private static method onInit takes nothing returns nothing
36
                set data = Table.create()
37
            endmethod
38
        endmodule
39
    endif
40
41
    private struct D extends array
42
        static if LIBRARY_Table then
43
            static Table data
44
            
45
            implement Init
46
        else
47
            static hashtable data = InitHashtable()
48
        endif
49
    endstruct
50
    
51
    function GetStringById takes integer i returns string
52
        return strings[i]
53
    endfunction
54
    
55
    function GetStringId takes string t returns integer
56
        static if LIBRARY_Table then
57
            return D.data[StringHash(t)]
58
        else
59
            return LoadInteger(D.data, StringHash(t), 0)
60
        endif
61
    endfunction
62
    
63
    function IndexString takes string t returns integer
64
        local integer i = StringHash(t)
65
        
66
        static if LIBRARY_Table then
67
            if D.data[i] == 0 then
68
                set count = count + 1
69
                
70
                set D.data[i] = count
71
72
                set strings[count] = t
73
                return count
74
            endif
75
76
            return D.data[i]
77
        else
78
            if LoadInteger(D.data, i, 0) == 0 then
79
                set count = count + 1
80
81
                call SaveInteger(D.data, i, 0, count)
82
83
                set strings[count] = t
84
                return count
85
            endif
86
87
            return LoadInteger(D.data, i, 0)
88
        endif
89
    endfunction
90
    
91
endlibrary



I think it's quite nifty.

Feel free to comment.
13 years
Just in case, it's been approved by me :)