Unexpected behaviour in associative array

Arredondo arm.plus at gmail.com
Fri Apr 19 12:37:10 UTC 2019


On Friday, 19 April 2019 at 11:32:17 UTC, Andre Pany wrote:
> Could you please post the coding, otherwise it is quite hard to 
> help you.
>

Here's a reasonably-sized code fragment that demonstrates the 
issue. I hope the comments along the way are descriptive enough

Thanks,
Arredondo
----------

// this is a thin wrapper around a 2D byte matrix
// that uses an ndslice internally
struct State {
     import std.digest.murmurhash;
	import mir.ndslice;

     this(byte rows, byte cols) inout @safe pure nothrow {
         payload = slice!byte([rows, cols], 0);
     }

     size_t toHash() pure nothrow {
         byte[] data = payload.field();
         immutable digest = digest!(MurmurHash3!(128, 64))(data);
         immutable hash = *cast(size_t*) &digest[0];
         return hash;
     }

     bool opEquals(ref inout State q) inout @safe pure nothrow {
         return payload == q;
     }

     Slice!(Contiguous, [2], byte*) payload;
     alias payload this;
}

void main(string[] args) {
	import std.stdio;

	// create a key
	auto key1 = State(2, 2);
	key1[0, 0] = cast(byte) 1;

	// insert it in an assoc. array
	int[State] map;
	map[key1] = 101;

	// create the exact same key
	auto key2 = State(2, 2);
	key2[0, 0] = cast(byte) 1;

	// it is an identical key as far as the aa is concerned
	assert(key1.opEquals(key2));
	assert(key2.opEquals(key1));
	assert(key1.toHash == key2.toHash);

	// yet it is not in the map
	writeln(key1 in map); // prints some memory address
	writeln(key2 in map); // prints null <-- unexpected behaviour!!!!
}



More information about the Digitalmars-d-learn mailing list