samchon/tstl

std.hash function returns negative value

samchon opened this issue · 0 comments

Bug Report

Summary

  • TSTL Version: 2.4.5
  • Expected behavior: std.hash() always returns positive value
  • Actual behavior: sometimes be negative

When call std.hash() function with multiple or composite arguments, it sometimes returns a negative value. If the hashed value is negative and the negative value is used on hash container like std.HashMap, it may cause an out_of_range error on the hack buckets.

Therefore, change the std.hash() function to return only positive value.

Code occuring the bug

import { Pair, hash, randint } from "tstl";

const CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

function random_characters(length: number): string
{
    let ret: string = "";
    for (let i: number = 0; i < length; ++i)
    {
        let index: number = randint(9, CHARACTERS.length - 1);
        ret += CHARACTERS[index];
    }
    return ret;
}

function main(): void
{
    type Tuple = Pair<Pair<object, string>, Pair<object, string>>;
    const Tuple = Pair;

    for (let i: number = 0; i < 10; ++i)
    {
        let tuple: Tuple = new Tuple
        (
            new Pair(new Object(), random_characters(3)), 
            new Pair(new Object(), random_characters(7))
        );
        let value: number = hash(tuple);

        console.log(value);
    }
}
main();
-23409629988420516
-11329128905355596
20706793082276600
4756301873949006
-15805877427348520
864371773763365
11176494969498808
-19793194415380096
-29669317861049210
-1737578809468320