Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hash causes panic #1

Open
dann-romm opened this issue Jul 24, 2022 · 2 comments
Open

hash causes panic #1

dann-romm opened this issue Jul 24, 2022 · 2 comments
Assignees

Comments

@dann-romm
Copy link

dann-romm commented Jul 24, 2022

i was looking for hash function implementation using maphash and found your repo

there is a hash method of Map in file maps/hash/hash.go
if you use integer type as comparable K key, you get a panic
panic: interface conversion: interface {} is int, not []uint8

it is also panics if key is any Number type, like float64 or uint16

i believe, error in the byte conversion:
bytes := any(key).([]byte)

@bdreece
Copy link
Owner

bdreece commented Jul 24, 2022

I would not recommend using this repository for anything in production at this point, many of the collections are unimplemented or untested. Regardless, I will work on fixing this particular issue in case you end up using it, and I am thinking the right approach will look something like this:

func (m *Map) hash(key K) int {
    keyString := fmt.Sprint(key)
    m.Hash.WriteString(keyString)
    return int(m.Hash.Sum64() % len(*m.Vector))
}

@bdreece bdreece self-assigned this Jul 24, 2022
@dann-romm
Copy link
Author

dann-romm commented Jul 24, 2022

thanks for reply and sorry for misunderstanding, i don't use this in production, i was looking specifically for a way to take a hash function from any type (i mean, comparable type)

fortunately i found solution working for me, in this case we can use gob encoder to get byte slice something like this:

func newHashFunc[K comparable]() func(K) uint64 {
	var h maphash.Hash
	h.SetSeed(maphash.MakeSeed())
	var buf bytes.Buffer
	encoder := gob.NewEncoder(&buf)

	return func(key K) uint64 {
		h.Reset()
		buf.Reset()
		_ = encoder.Encode(key)
		_, _ = h.Write(buf.Bytes())
		value := h.Sum64()
		return value
	}
}

or in your implementation:

func (m *Map) hash(key K) int {
	var buf bytes.Buffer
	encoder := gob.NewEncoder(&buf)
	encoder.Encode(key)
	
	h.Reset()
	m.Hash.Write(buf.Bytes())
	return int(m.Hash.Sum64() % len(*m.Vector))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

When branches are created from issues, their pull requests are automatically linked.

2 participants