[Snippet] StringIndexer

Scripts

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

Jass:

Code (jass) Select
/************************************************
*
*   StringIndexer
*   v1.0.0.2
*   By Magtheridon96
*
*   - Retrieves an index for a string below 8191
*   - Helps easy string data attachment
*
*   Optional:
*   ---------
*
*       - Table by Bribe
*
*   API:
*   ----
*
*       - function IndexString takes string s returns integer
*           - Indexes a string and returns the index
*       - function GetStringId takes string s returns integer
*           - Retrieves the index of an indexed string
*       - function GetStringById takes integer id returns string
*           - Returns the string corresponding to a certain Id
*
************************************************/
library StringIndexer requires optional Table

    globals
        private string array strings
        private integer count = 0
    endglobals
   
    static if LIBRARY_Table then
        private module Init
            private static method onInit takes nothing returns nothing
                set data = Table.create()
            endmethod
        endmodule
    endif

    private struct D extends array
        static if LIBRARY_Table then
            static Table data
           
            implement Init
        else
            static hashtable data = InitHashtable()
        endif
    endstruct
   
    function GetStringById takes integer i returns string
        return strings[i]
    endfunction
   
    function GetStringId takes string t returns integer
        static if LIBRARY_Table then
            return D.data[StringHash(t)]
        else
            return LoadInteger(D.data, StringHash(t), 0)
        endif
    endfunction
   
    function IndexString takes string t returns integer
        local integer i = StringHash(t)
       
        static if LIBRARY_Table then
            if D.data[i] == 0 then
                set count = count + 1
               
                set D.data[i] = count

                set strings[count] = t
                return count
            endif

            return D.data[i]
        else
            if LoadInteger(D.data, i, 0) == 0 then
                set count = count + 1

                call SaveInteger(D.data, i, 0, count)

                set strings[count] = t
                return count
            endif

            return LoadInteger(D.data, i, 0)
        endif
    endfunction
   
endlibrary



I think it's quite nifty.

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