encoding: sort dictionaries by encoded keys

This commit is contained in:
Emery Hemingway 2024-05-22 19:49:07 +03:00
parent 4ebca473df
commit cd6812ae07
1 changed files with 16 additions and 4 deletions

View File

@ -1,7 +1,7 @@
# SPDX-FileCopyrightText: ☭ Emery Hemingway
# SPDX-License-Identifier: Unlicense
import std/[assertions, endians, streams]
import std/[algorithm, assertions, endians, streams]
import bigints
import ./values
@ -96,10 +96,22 @@ proc write*(str: Stream; pr: Value) =
str.write(val)
str.write(0x84'u8)
of pkDictionary:
var
keyIndices = newSeqOfCap[(string, int)](pr.dict.len)
keyBuffer = newStringStream()
for i in 0..pr.dict.high:
keyBuffer.write(pr.dict[i][0])
keyIndices.add((keyBuffer.data.move, i))
keyBuffer.setPosition(0)
# add each encoded key and its index to the seq
sort(keyIndices) do (a, b: (string, int)) -> int:
cmp(a[0], b[0])
# sort the seq by encoded keys
str.write(0xb7'u8)
for (key, value) in pr.dict.items:
str.write(key)
str.write(value)
for (keyBytes, i) in keyIndices:
str.write(keyBytes)
str.write(pr.dict[i][1])
# encode the values in sorted key order
str.write(0x84'u8)
of pkEmbedded:
# str.write(0x86'u8)