diff --git a/src/preserves/private/encoding.nim b/src/preserves/private/encoding.nim index c26157f..5e90a89 100644 --- a/src/preserves/private/encoding.nim +++ b/src/preserves/private/encoding.nim @@ -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)