Skip to content

Commit 31fc9e9

Browse files
authored
Merge pull request #8 from andrewnester/fix/empty
Fixed unpacking empty arrays
2 parents 7ad60b6 + 11b5304 commit 31fc9e9

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/unpacker.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,13 @@ impl Unpacker {
159159
}
160160
};
161161

162+
// Handle empty packed array (empty object case)
163+
if packed_array.is_empty() {
164+
let empty_obj = json!({});
165+
self.add_to_dict(&empty_obj.to_string());
166+
return Ok(empty_obj);
167+
}
168+
162169
let type_value = &packed_array[0];
163170
let type_id = match type_value.as_i64() {
164171
Some(i) => i,

tests/test_packer.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,3 +814,47 @@ fn it_doesnot_pack_very_large_nonscalars() {
814814
let unpacked: Value = unpacker.unpack(&packed).unwrap();
815815
assert_eq!(unpacked, input);
816816
}
817+
818+
#[test]
819+
fn it_packs_empty_objects() {
820+
// This test matches the exact bug report scenario
821+
let mut packer = Packer::new();
822+
let options = PackOptions::new();
823+
let packed = packer.pack(&json!({}), &options).unwrap();
824+
825+
// The packed value should be [0]
826+
assert_eq!(packed, json!([0]));
827+
828+
// This should not panic - it was panicking before the fix
829+
let mut unpacker = Unpacker::new();
830+
let unpacked: Result<Value, _> = unpacker.unpack(&packed);
831+
832+
// Verify unpacking succeeds and returns the original empty object
833+
assert!(unpacked.is_ok());
834+
assert_eq!(unpacked.unwrap(), json!({}));
835+
}
836+
837+
#[test]
838+
fn it_packs_empty_objects_inside_arrays() {
839+
let mut packer = Packer::new();
840+
let mut unpacker = Unpacker::new();
841+
842+
let options = PackOptions::new();
843+
let packed = packer.pack(&json!([{}, {}]), &options).unwrap();
844+
// The second empty object is memoized and becomes index 3
845+
assert_eq!(packed, json!([TYPE_ARRAY, [], 3, 0]));
846+
let unpacked: Value = unpacker.unpack(&packed).unwrap();
847+
assert_eq!(unpacked, json!([{}, {}]));
848+
}
849+
850+
#[test]
851+
fn it_packs_empty_objects_nested() {
852+
let mut packer = Packer::new();
853+
let mut unpacker = Unpacker::new();
854+
855+
let options = PackOptions::new();
856+
let packed = packer.pack(&json!({"foo": {}}), &options).unwrap();
857+
assert_eq!(packed, json!(["foo", [], 0]));
858+
let unpacked: Value = unpacker.unpack(&packed).unwrap();
859+
assert_eq!(unpacked, json!({"foo": {}}));
860+
}

0 commit comments

Comments
 (0)