how hash_t toHash() works?

gedaiu szabobogdan at yahoo.com
Sun Apr 28 04:00:07 PDT 2013


hi,

I have a class which I want to use as key in an assoc array like
this:

string["KeyString"] myArray;

What i want is to preserve the order in the array. I want always
to have "1" before "2" if the string is a numeric value.

Can anyone help me to understand how const hash_t toHash() should
work?

Here is the KeyString class:

struct KeyString {
	string str;
	
	KeyString opAssign(string val) {
		str = val;
		return this;
	}
	
	const hash_t toHash() {
		try {
			return to!long(str);
		} catch(Exception e) {
			hash_t hash; foreach (char c; str) hash = (hash * 9) + c;
			return hash;
		}
	}
	
	const int opCmp(ref const KeyString s) {
		//return std.string.cmp(this.str, s.str);
		
		try {
			auto val1 = to!long(this.str);
			auto val2 = to!long(s.str);
			
			if(val1 < val2) {
				return -1;
			}
			
			if(val1 == val2) {
				return 0;
			}
			
		} catch(Exception e) {
			return std.string.cmp(str, s.str);
		}
		
		return 1;
	}
}


Thanks,
Bogdan


More information about the Digitalmars-d-learn mailing list