www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [AA] No restrictions for toHash/opCmp

<docs href="http://www.digitalmars.com/d/arrays.html#associative">

If the KeyType is a struct type, a default mechanism is used to 
compute the hash and comparisons of it based on the binary data 
within the struct value. A custom mechanism can be used by 
providing the following functions as struct members: 

	uint toHash();
	int opCmp(KeyType* s);

</docs>

Here the restriction is missing, that the values yielded by both 
functions for a given instance of the struct are not allowed to 
change during the lifetime of the AA.

Currently even a change of the value generated by `toHash' followed 
by a `rehash' on the AA does not work as this code shows by 
throwing an assertion failure:

<code>
import std.stdio, std.string;
int hsh;
struct MyString
{
  char[] str;

  uint toHash(){
    return hsh;
  }

  int opCmp(MyString* s)
  {
    return std.string.cmp(this.str, s.str);
  }
  
}

void main(){
  int[MyString] a;

  MyString x;
  x.str="a";

  hsh= 0;
  a[ x]= a[ x];
  a.rehash;
  assert( x in a);

  hsh= 1;
  a.rehash;
  assert( x in a);
}
</code>
Apr 19 2005