Skip to content

Commit

Permalink
some stdlib fixes and improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
p7g committed Dec 16, 2020
1 parent f07b428 commit e10bb18
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
4 changes: 4 additions & 0 deletions lib/hash.rbcvm
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,7 @@ export function fnv1a(bytes) {
export function int(n) {
return n;
}

export function char(c) {
return int(ord(c));
}
33 changes: 28 additions & 5 deletions lib/hashmap.rbcvm
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ module HashMap;
import "array.rbcvm";
import "assoclist.rbcvm";
import "hash.rbcvm";
import "iter.rbcvm";
import "string.rbcvm";

let INITIAL_CAPACITY = 2 ** 3;
let INITIAL_CAPACITY = toint(2 ** 3);
let LOAD_FACTOR = 0.7;

# hashmap
Expand All @@ -20,6 +21,8 @@ function hash_string(str) {
return Hash.fnv1a(string_bytes(str));
}

let default_hash = hash_string;

function do_hash(self, key) {
return self:hash_fn(key) & self:cap - 1;
}
Expand All @@ -31,7 +34,10 @@ function grow(self) {
self:buckets = Array.new(cap);
self:load = 0;

Array.foreach(oldbuckets, function(bucket) {
Array.foreach(old_buckets, function(bucket) {
if (!bucket) {
return;
}
Array.foreach(AssocList.entries(bucket), function(entry) {
set(self, entry[0], entry[1]);
});
Expand All @@ -44,7 +50,7 @@ export function with_capacity(capacity) {
return HashMap{
cap=capacity,
load=0,
hash_fn=hash_string,
hash_fn=default_hash,
buckets=Array.new(capacity),
};
}
Expand Down Expand Up @@ -80,7 +86,7 @@ export function set(self, key, value) {

AssocList.set(bucket, key, value);

if (self:load / self:cap < LOAD_FACTOR) {
if (self:load / self:cap > LOAD_FACTOR) {
grow(self);
}
}
Expand Down Expand Up @@ -114,5 +120,22 @@ export function make_with_hash_function(hash, init_fn) {
}

export function make(init_fn) {
return make_with_hash_function(hash_string, init_fn);
return make_with_hash_function(default_hash, init_fn);
}

export function from_entries_with_hash_function(hash, entries) {
let map = new();
set_hash_function(map, hash);
extend(map, entries);
return map;
}

export function from_entries(entries) {
return from_entries_with_hash_function(default_hash, entries);
}

export function extend(map, entries) {
Iter.foreach(entries, function(entry) {
set(map, entry[0], entry[1]);
});
}
2 changes: 1 addition & 1 deletion lib/string.rbcvm
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function parse_integer(str, base) {

Array.foreach(cs, function(char, i) {
if (Char.is_digit(char)) {
sum = sum + Char.to_digit(char) * base ** i;
sum = sum + toint(Char.to_digit(char) * base ** i);
}
});

Expand Down

0 comments on commit e10bb18

Please sign in to comment.