Skip to content

Commit

Permalink
Allow table/to-struct to take a prototype.
Browse files Browse the repository at this point in the history
Use this prototype struct in freeze.
  • Loading branch information
bakpakin committed Dec 20, 2024
1 parent 682f0f5 commit 1b49934
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
12 changes: 10 additions & 2 deletions src/boot/boot.janet
Original file line number Diff line number Diff line change
Expand Up @@ -2230,8 +2230,16 @@
(tuple/slice (map freeze x))

(or (= tx :table) (= tx :struct))
(let [sorted-kvs (array/join @[] ;(sort (map freeze (pairs x))))]
(struct/with-proto (freeze (getproto x)) ;sorted-kvs))
(let [temp-tab @{}]
# Handle multiple unique keys that freeze. Result should
# be independent of iteration order.
(eachp [k v] x
(def kk (freeze k))
(def vv (freeze v))
(def old (get temp-tab kk))
(def new (if (= nil old) vv (max vv old)))
(put temp-tab kk new))
(table/to-struct temp-tab (freeze (getproto x))))

(= tx :buffer)
(string x)
Expand Down
12 changes: 7 additions & 5 deletions src/core/table.c
Original file line number Diff line number Diff line change
Expand Up @@ -372,12 +372,14 @@ JANET_CORE_FN(cfun_table_setproto,
}

JANET_CORE_FN(cfun_table_tostruct,
"(table/to-struct tab)",
"Convert a table to a struct. Returns a new struct. This function "
"does not take into account prototype tables.") {
janet_fixarity(argc, 1);
"(table/to-struct tab &opt proto)",
"Convert a table to a struct. Returns a new struct.") {
janet_arity(argc, 1, 2);
JanetTable *t = janet_gettable(argv, 0);
return janet_wrap_struct(janet_table_to_struct(t));
JanetStruct proto = janet_optstruct(argv, argc, 1, NULL);
JanetStruct st = janet_table_to_struct(t);
janet_struct_proto(st) = proto;
return janet_wrap_struct(st);
}

JANET_CORE_FN(cfun_table_rawget,
Expand Down

0 comments on commit 1b49934

Please sign in to comment.