From ca6e4d141484331a25cfa67cf370000b74d7725f Mon Sep 17 00:00:00 2001 From: SoniEx2 Date: Sun, 9 Jun 2024 13:02:25 -0300 Subject: Add hashmap implementation --- test/bucketmap-tests.cratera | 35 +++++++++++++++++++++++++++++++++++ test/defaultbucket.cratera | 22 ++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 test/bucketmap-tests.cratera create mode 100644 test/defaultbucket.cratera (limited to 'test') diff --git a/test/bucketmap-tests.cratera b/test/bucketmap-tests.cratera new file mode 100644 index 0000000..b2e0aaa --- /dev/null +++ b/test/bucketmap-tests.cratera @@ -0,0 +1,35 @@ +local bucketlib = require "cratera.lib.bucket" + +local Bucketable = bucketlib.Bucketable +local Bucket = bucketlib.Bucket +local Struct = Struct + +local Point = mkstruct(function(_struct, x, y) + return {x, y} +end, { + __eq = function(a, b) + return a[Struct] == b[Struct] and a[1] == b[1] and a[2] == b[2] + end +}) + +Point[Bucketable] = {} +-- FIXME we really need that 'function Point:[Bucketable].bucket(bucket)' syntax... +local pointbucket = Point[Bucketable] + +function pointbucket:bucket(bucket) + bucket:[Bucket].put_number(self[1]) + bucket:[Bucket].put_number(self[2]) +end + +local map = bucketlib.BucketingMap() + +map:put(Point(0, 1), "hello") +map:put(Point(2, 3), "cratera") +map:put(Point(4, 5), "world") + +assert(map._buckets[2]) +assert(map._buckets[3]) +assert(map._buckets[4]) +assert(map:get(Point(0, 1)) == "hello") +assert(map:get(Point(2, 3)) == "cratera") +assert(map:get(Point(4, 5)) == "world") diff --git a/test/defaultbucket.cratera b/test/defaultbucket.cratera new file mode 100644 index 0000000..fd7281e --- /dev/null +++ b/test/defaultbucket.cratera @@ -0,0 +1,22 @@ +local bucketlib = require "cratera.lib.bucket" + +local Bucket = bucketlib.Bucket +local DefaultBucket = bucketlib.DefaultBucket + +local function hash_n(n) + local bucket = DefaultBucket() + bucket:[Bucket].put_number(n) + return bucket:[Bucket].finish() +end + +local function hash_s(n) + local bucket = DefaultBucket() + bucket:[Bucket].put_string(n) + return bucket:[Bucket].finish() +end + +assert(hash_n(1) == 1) +assert(hash_n(2) == 2) +assert(hash_n(-1) == 1) +assert(hash_s("") == 0) +assert(hash_s("h") == string.byte("h")+31) -- cgit 1.4.1