@@ -136,9 +136,26 @@ extension CBOR {
136136 res. reserveCapacity ( 1 + map. count * ( MemoryLayout < A > . size + MemoryLayout < B > . size + 2 ) )
137137 res = map. count. encode ( options: options)
138138 res [ 0 ] = res [ 0 ] | 0b101_00000
139- for (k, v) in map {
140- res. append ( contentsOf: k. encode ( options: options) )
141- res. append ( contentsOf: v. encode ( options: options) )
139+
140+ if options. shouldSortMapKeys {
141+ let sortedKeysWithEncodedKeys = map. keys. map {
142+ ( encoded: $0. encode ( options: options) , key: $0)
143+ } . sorted ( by: {
144+ $0. encoded. lexicographicallyPrecedes ( $1. encoded)
145+ } )
146+
147+ sortedKeysWithEncodedKeys. forEach { keyTuple in
148+ res. append ( contentsOf: keyTuple. encoded)
149+ guard let value = map [ keyTuple. key] else {
150+ return
151+ }
152+ res. append ( contentsOf: value. encode ( options: options) )
153+ }
154+ } else {
155+ for (k, v) in map {
156+ res. append ( contentsOf: k. encode ( options: options) )
157+ res. append ( contentsOf: v. encode ( options: options) )
158+ }
142159 }
143160 return res
144161 }
@@ -442,16 +459,24 @@ extension CBOR {
442459 if options. forbidNonStringMapKeys {
443460 try ensureStringKey ( A . self)
444461 }
445- let sortedKeysWithEncodedKeys = map. keys. map {
446- ( encoded: $0. encode ( options: options) , key: $0)
447- } . sorted ( by: {
448- $0. encoded. lexicographicallyPrecedes ( $1. encoded)
449- } )
450-
451- try sortedKeysWithEncodedKeys. forEach { keyTuple in
452- res. append ( contentsOf: keyTuple. encoded)
453- let encodedVal = try encodeAny ( map [ keyTuple. key] !, options: options)
454- res. append ( contentsOf: encodedVal)
462+ if options. shouldSortMapKeys {
463+ let sortedKeysWithEncodedKeys = map. keys. map {
464+ ( encoded: $0. encode ( options: options) , key: $0)
465+ } . sorted ( by: {
466+ $0. encoded. lexicographicallyPrecedes ( $1. encoded)
467+ } )
468+
469+ try sortedKeysWithEncodedKeys. forEach { keyTuple in
470+ res. append ( contentsOf: keyTuple. encoded)
471+ let encodedVal = try encodeAny ( map [ keyTuple. key] !, options: options)
472+ res. append ( contentsOf: encodedVal)
473+ }
474+ } else {
475+ for (k, v) in map {
476+ res. append ( contentsOf: k. encode ( options: options) )
477+ let encodedVal = try encodeAny ( v, options: options)
478+ res. append ( contentsOf: encodedVal)
479+ }
455480 }
456481 }
457482}
0 commit comments