Skip to content

Instantly share code, notes, and snippets.

@martandrMC
Last active June 2, 2024 11:55
Show Gist options
  • Save martandrMC/ab888dbeb265b340b5ab1285ed1dd972 to your computer and use it in GitHub Desktop.
Save martandrMC/ab888dbeb265b340b5ab1285ed1dd972 to your computer and use it in GitHub Desktop.
Pearson Hash S-Box Finder (Useful for making minimal hash maps for keyword identification in lexers)
/*
The MIT License (MIT)
Copyright (c) 2024 Martin Andronikos
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
This is a dirty randomised swaps algorithm I wrote one day when I was
bored at university to generate the keywords hashmap for my compiler project.
(https://github.com/martandrMC/compiler) This does not scale well at all.
The experimentally determined limit is about 30 keywords. If you are in need of
more, try to improve the search algorithmn and maybe let me know! I hope you have
found Pearson Hashing interesting. (https://en.wikipedia.org/wiki/Pearson_hashing)
*/
public class Keywords {
private int[] sbox;
private int hash;
private final int maximum;
public Keywords(int maximum) {
hash = 0;
sbox = new int[256];
for(int i=0; i<256; i++)
sbox[i] = i;
double tmp = Math.log(maximum) / Math.log(2.0);
this.maximum = 1 << ((int) Math.ceil(tmp));
}
public void addChar(char c) {
int tmp = ((int) c) & 0xFF;
hash = sbox[tmp ^ hash];
}
public void addString(String str) {
for(char c : str.toCharArray())
addChar(c);
}
public int getHash() {
int ret = hash;
hash = 0;
return ret & (maximum - 1);
}
public int getMaximum() {
return maximum;
}
public void adjustSBox() {
int r1 = (int) Math.floor(Math.random() * 256);
int r2 = (int) Math.floor(Math.random() * 256);
int tmp = sbox[r1];
sbox[r1] = sbox[r2];
sbox[r2] = tmp;
}
public void printSBox() {
System.out.print("\t");
for(int i=0; i<256; i+=16) {
for(int j=0; j<16; j++) {
String val = Integer.toHexString(sbox[i + j]);
if(val.length() < 2) val = "0" + val;
System.out.print("0x" + val);
if(i < 240 || j < 15) System.out.print(",");
if(j < 15) System.out.print(" ");
}
if(i < 240) System.out.print("\n\t");
}
}
private static String[] key_set = {
"do", "end", "return", "var",
"if", "else", "while",
"nat", "int", "bool",
"nil", "true", "false",
"and", "or", "not"
};
private static String[] value_set = {
"TOK_KW_DO", "TOK_KW_END", "TOK_KW_RETURN", "TOK_KW_VAR",
"TOK_KW_IF", "TOK_KW_ELSE", "TOK_KW_WHILE",
"TOK_TYPE_NAT", "TOK_TYPE_INT", "TOK_TYPE_BOOL",
"TOK_KW_NIL", "TOK_KW_TRUE", "TOK_KW_FALSE",
"TOK_KW_AND", "TOK_KW_OR", "TOK_KW_NOT"
};
private static String[] hash_table;
public static void main(String[] args) {
Keywords hash = new Keywords(key_set.length);
hash_table = new String[hash.getMaximum()];
int tries = 1;
for(;; tries++) {
boolean colision = false;
for(String key : key_set) {
hash.addString(key);
int idx = hash.getHash();
colision = (hash_table[idx] != null);
if(colision) break;
hash_table[idx] = key;
}
if(!colision) break;
for(int i=0; i<hash_table.length; i++)
hash_table[i] = null;
hash.adjustSBox();
}
System.out.println("// S-Box for perfect hashing found after " + tries + " tries.");
System.out.println("#define MAP_SIZE " + hash_table.length + "\n");
System.out.println("static const uint8_t map_sbox[256] = {");
hash.printSBox();
System.out.println("\n};\n");
System.out.print("static const char *map_keys[MAP_SIZE] = {\n\t");
for(int i=0; i<hash_table.length;) {
System.out.print("\"" + (hash_table[i] == null ? "" : hash_table[i]) + "\"");
if(i != hash_table.length - 1) System.out.print(",");
if((++i) % 8 == 0) {
System.out.print("\n");
if(i != hash_table.length)
System.out.print("\t");
} else System.out.print(" ");
}
System.out.println("};\n");
System.out.print("static const token_type_t map_vals[MAP_SIZE] = {\n\t");
for(int i=0; i<hash_table.length;) {
String value = hash_table[i];
if(value == null) System.out.print("TOK_IDENT");
else for(int j=0; j<hash_table.length; j++) {
if(key_set[j].equals(value)) {
System.out.print(value_set[j]);
break;
}
}
if(i != hash_table.length - 1) System.out.print(",");
if((++i) % 4 == 0) {
System.out.print("\n");
if(i != hash_table.length)
System.out.print("\t");
} else System.out.print(" ");
}
System.out.println("};");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment