gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/mpackdb/msgpack.zig

33.0 KB

  1. // MessagePack codec for hl:mpackdb — byte-compatible with npm msgpackr 1.11.5
  2. // as mpackdb v1.0.7 uses it (decision D12).
  3. //
  4. // Measured msgpackr surface (probed against the real library, see
  5. // testdata/gen_corpus.mjs):
  6. // - NO record/shared-structure extensions: the standalone pack() export
  7. // serializes plain objects as ordinary MessagePack maps.
  8. // - Objects ALWAYS encode as map16 (0xde) — even empty — never fixmap/map32.
  9. // Maps with > 65535 keys throw in msgpackr; we mirror with error.MapTooLarge.
  10. // - Numbers: integer-valued f64 in [-2^31, 2^32) uses the smallest
  11. // uint/int family (fixint, cc, cd, ce / negfixint, d0, d1, d2). Everything
  12. // else (non-integers, |v| outside that range, NaN, ±Inf) is float64 (0xcb).
  13. // msgpackr never emits float32 or int64/uint64 for JS numbers.
  14. // - Strings: fixstr ≤31 bytes, str8 ≤255, str16 ≤65535, str32 beyond.
  15. // - Arrays: fixarray ≤15, array16 ≤65535, array32 beyond.
  16. // - Binary: bin8/16/32 by length.
  17. // - undefined: fixext1 type 0x00 data 0x00 (d4 00 00) — kept as a distinct
  18. // Value so re-encode is byte-exact; it surfaces as null in Hybriel.
  19. // - Date: timestamp ext -1 (d6ff / d7ff / c70cff). Kept as a raw ext Value
  20. // for byte-exact round-trips; timestampMs() interprets it.
  21. //
  22. // Decode accepts the FULL MessagePack spec (all int/str/bin/array/map families,
  23. // float32, int64/uint64, all ext forms); encode emits only the canonical
  24. // msgpackr subset above.
  25. const std = @import("std");
  26. pub const Error = error{
  27. Truncated,
  28. InvalidFormat, // 0xc1
  29. MapTooLarge,
  30. OutOfMemory,
  31. };
  32. pub const Ext = struct {
  33. type: i8,
  34. data: []const u8,
  35. };
  36. pub const Entry = struct {
  37. key: Value,
  38. value: Value,
  39. };
  40. pub const Value = union(enum) {
  41. nil,
  42. undef, // msgpackr `undefined` (fixext1 type 0)
  43. boolean: bool,
  44. number: f64,
  45. str: []const u8,
  46. bin: []const u8,
  47. array: []Value,
  48. map: []Entry,
  49. ext: Ext,
  50. /// Interpret a timestamp ext (-1) as milliseconds since epoch.
  51. pub fn timestampMs(self: Value) ?f64 {
  52. if (self != .ext or self.ext.type != -1) return null;
  53. const d = self.ext.data;
  54. switch (d.len) {
  55. 4 => {
  56. const sec = std.mem.readInt(u32, d[0..4], .big);
  57. return @as(f64, @floatFromInt(sec)) * 1000.0;
  58. },
  59. 8 => {
  60. const packed_v = std.mem.readInt(u64, d[0..8], .big);
  61. const ns: f64 = @floatFromInt(packed_v >> 34);
  62. const sec: f64 = @floatFromInt(packed_v & 0x3ffffffff);
  63. return sec * 1000.0 + ns / 1_000_000.0;
  64. },
  65. 12 => {
  66. const ns = std.mem.readInt(u32, d[0..4], .big);
  67. const sec = std.mem.readInt(i64, d[4..12], .big);
  68. return @as(f64, @floatFromInt(sec)) * 1000.0 + @as(f64, @floatFromInt(ns)) / 1_000_000.0;
  69. },
  70. else => return null,
  71. }
  72. }
  73. /// Map field lookup by string key (returns null for missing / non-map).
  74. pub fn get(self: Value, key: []const u8) ?Value {
  75. if (self != .map) return null;
  76. for (self.map) |e| {
  77. if (e.key == .str and std.mem.eql(u8, e.key.str, key)) return e.value;
  78. }
  79. return null;
  80. }
  81. };
  82. pub const Decoded = struct {
  83. value: Value,
  84. len: usize, // bytes consumed
  85. };
  86. /// Decode one MessagePack value from `bytes`. All slices in the returned Value
  87. /// reference memory allocated from `alloc` (str/bin/ext data are duplicated,
  88. /// so the Value outlives `bytes`). Use an arena and free it wholesale.
  89. pub fn decode(alloc: std.mem.Allocator, bytes: []const u8) Error!Decoded {
  90. var d = Decoder{ .alloc = alloc, .bytes = bytes, .pos = 0 };
  91. const v = try d.readValue();
  92. return .{ .value = v, .len = d.pos };
  93. }
  94. const Decoder = struct {
  95. alloc: std.mem.Allocator,
  96. bytes: []const u8,
  97. pos: usize,
  98. fn need(self: *Decoder, n: usize) Error!void {
  99. if (self.pos + n > self.bytes.len) return Error.Truncated;
  100. }
  101. fn take(self: *Decoder, n: usize) Error![]const u8 {
  102. try self.need(n);
  103. const s = self.bytes[self.pos .. self.pos + n];
  104. self.pos += n;
  105. return s;
  106. }
  107. fn readBigInt(self: *Decoder, comptime T: type) Error!T {
  108. const n = @divExact(@typeInfo(T).int.bits, 8);
  109. const s = try self.take(n);
  110. return std.mem.readInt(T, s[0..n], .big);
  111. }
  112. fn dupSlice(self: *Decoder, n: usize) Error![]const u8 {
  113. const s = try self.take(n);
  114. return self.alloc.dupe(u8, s) catch return Error.OutOfMemory;
  115. }
  116. fn readArray(self: *Decoder, n: usize) Error!Value {
  117. const items = self.alloc.alloc(Value, n) catch return Error.OutOfMemory;
  118. for (items) |*it| it.* = try self.readValue();
  119. return .{ .array = items };
  120. }
  121. fn readMap(self: *Decoder, n: usize) Error!Value {
  122. const entries = self.alloc.alloc(Entry, n) catch return Error.OutOfMemory;
  123. for (entries) |*e| {
  124. e.key = try self.readValue();
  125. e.value = try self.readValue();
  126. }
  127. return .{ .map = entries };
  128. }
  129. fn readExt(self: *Decoder, n: usize) Error!Value {
  130. try self.need(1 + n);
  131. const t: i8 = @bitCast(self.bytes[self.pos]);
  132. self.pos += 1;
  133. const data = try self.dupSlice(n);
  134. // msgpackr undefined: fixext1 type 0, data byte 0
  135. if (t == 0 and n == 1 and data[0] == 0) return .undef;
  136. return .{ .ext = .{ .type = t, .data = data } };
  137. }
  138. /// Walk one value without building it: the checks `readValue` makes (a short buffer, 0xc1).
  139. fn skipValue(self: *Decoder) Error!void {
  140. var pending: usize = 1;
  141. while (pending > 0) {
  142. pending -= 1;
  143. try self.need(1);
  144. const b = self.bytes[self.pos];
  145. self.pos += 1;
  146. switch (b) {
  147. 0x00...0x7f, 0xc0, 0xc2, 0xc3, 0xe0...0xff => {},
  148. 0x80...0x8f => pending += 2 * @as(usize, b & 0x0f),
  149. 0x90...0x9f => pending += b & 0x0f,
  150. 0xa0...0xbf => _ = try self.take(b & 0x1f),
  151. 0xc1 => return Error.InvalidFormat,
  152. 0xc4, 0xd9 => _ = try self.take(try self.readBigInt(u8)),
  153. 0xc5, 0xda => _ = try self.take(try self.readBigInt(u16)),
  154. 0xc6, 0xdb => _ = try self.take(try self.readBigInt(u32)),
  155. 0xc7 => _ = try self.take(1 + @as(usize, try self.readBigInt(u8))),
  156. 0xc8 => _ = try self.take(1 + @as(usize, try self.readBigInt(u16))),
  157. 0xc9 => _ = try self.take(1 + @as(usize, try self.readBigInt(u32))),
  158. 0xca, 0xce, 0xd2 => _ = try self.take(4),
  159. 0xcb, 0xcf, 0xd3 => _ = try self.take(8),
  160. 0xcc, 0xd0 => _ = try self.take(1),
  161. 0xcd, 0xd1 => _ = try self.take(2),
  162. 0xd4 => _ = try self.take(2),
  163. 0xd5 => _ = try self.take(3),
  164. 0xd6 => _ = try self.take(5),
  165. 0xd7 => _ = try self.take(9),
  166. 0xd8 => _ = try self.take(17),
  167. 0xdc => pending += try self.readBigInt(u16),
  168. 0xdd => pending += try self.readBigInt(u32),
  169. 0xde => pending += 2 * @as(usize, try self.readBigInt(u16)),
  170. 0xdf => pending += 2 * @as(usize, try self.readBigInt(u32)),
  171. }
  172. }
  173. }
  174. fn readValue(self: *Decoder) Error!Value {
  175. try self.need(1);
  176. const b = self.bytes[self.pos];
  177. self.pos += 1;
  178. switch (b) {
  179. 0x00...0x7f => return .{ .number = @floatFromInt(b) },
  180. 0x80...0x8f => return self.readMap(b & 0x0f),
  181. 0x90...0x9f => return self.readArray(b & 0x0f),
  182. 0xa0...0xbf => return .{ .str = try self.dupSlice(b & 0x1f) },
  183. 0xc0 => return .nil,
  184. 0xc1 => return Error.InvalidFormat,
  185. 0xc2 => return .{ .boolean = false },
  186. 0xc3 => return .{ .boolean = true },
  187. 0xc4 => return .{ .bin = try self.dupSlice(try self.readBigInt(u8)) },
  188. 0xc5 => return .{ .bin = try self.dupSlice(try self.readBigInt(u16)) },
  189. 0xc6 => return .{ .bin = try self.dupSlice(try self.readBigInt(u32)) },
  190. 0xc7 => return self.readExt(try self.readBigInt(u8)),
  191. 0xc8 => return self.readExt(try self.readBigInt(u16)),
  192. 0xc9 => return self.readExt(try self.readBigInt(u32)),
  193. 0xca => {
  194. const bits = try self.readBigInt(u32);
  195. return .{ .number = @as(f32, @bitCast(bits)) };
  196. },
  197. 0xcb => {
  198. const bits = try self.readBigInt(u64);
  199. return .{ .number = @bitCast(bits) };
  200. },
  201. 0xcc => return .{ .number = @floatFromInt(try self.readBigInt(u8)) },
  202. 0xcd => return .{ .number = @floatFromInt(try self.readBigInt(u16)) },
  203. 0xce => return .{ .number = @floatFromInt(try self.readBigInt(u32)) },
  204. 0xcf => return .{ .number = @floatFromInt(try self.readBigInt(u64)) },
  205. 0xd0 => return .{ .number = @floatFromInt(@as(i8, @bitCast(try self.readBigInt(u8)))) },
  206. 0xd1 => return .{ .number = @floatFromInt(@as(i16, @bitCast(try self.readBigInt(u16)))) },
  207. 0xd2 => return .{ .number = @floatFromInt(@as(i32, @bitCast(try self.readBigInt(u32)))) },
  208. 0xd3 => return .{ .number = @floatFromInt(@as(i64, @bitCast(try self.readBigInt(u64)))) },
  209. 0xd4 => return self.readExt(1),
  210. 0xd5 => return self.readExt(2),
  211. 0xd6 => return self.readExt(4),
  212. 0xd7 => return self.readExt(8),
  213. 0xd8 => return self.readExt(16),
  214. 0xd9 => return .{ .str = try self.dupSlice(try self.readBigInt(u8)) },
  215. 0xda => return .{ .str = try self.dupSlice(try self.readBigInt(u16)) },
  216. 0xdb => return .{ .str = try self.dupSlice(try self.readBigInt(u32)) },
  217. 0xdc => return self.readArray(try self.readBigInt(u16)),
  218. 0xdd => return self.readArray(try self.readBigInt(u32)),
  219. 0xde => return self.readMap(try self.readBigInt(u16)),
  220. 0xdf => return self.readMap(try self.readBigInt(u32)),
  221. 0xe0...0xff => return .{ .number = @floatFromInt(@as(i8, @bitCast(b))) },
  222. }
  223. }
  224. };
  225. /// MISSION 436: decode only some top-level fields of a record. `bytes` is one msgpack value;
  226. /// `out[i]` becomes the value of the FIRST entry of that map whose key is the string `names[i]`
  227. /// (what `Value.get` returns for the fully decoded record), or null when there is none or the
  228. /// value is not a map. Every other value is skipped without being built, but the whole value
  229. /// is walked: an invalid or truncated part fails exactly where `decode` fails.
  230. pub fn decodeFields(alloc: std.mem.Allocator, bytes: []const u8, names: []const []const u8, out: []?Value) Error!void {
  231. for (out) |*o| o.* = null;
  232. var d = Decoder{ .alloc = alloc, .bytes = bytes, .pos = 0 };
  233. try d.need(1);
  234. const b = bytes[0];
  235. const n: usize = switch (b) {
  236. 0x80...0x8f => b & 0x0f,
  237. 0xde => blk: {
  238. d.pos = 1;
  239. break :blk try d.readBigInt(u16);
  240. },
  241. 0xdf => blk: {
  242. d.pos = 1;
  243. break :blk try d.readBigInt(u32);
  244. },
  245. else => {
  246. try d.skipValue(); // not a map: no fields, but still a value that must decode
  247. return;
  248. },
  249. };
  250. if (b >= 0x80 and b <= 0x8f) d.pos = 1;
  251. var i: usize = 0;
  252. while (i < n) : (i += 1) {
  253. // the key: a string is compared in place, anything else is skipped
  254. try d.need(1);
  255. const kb = bytes[d.pos];
  256. const klen: ?usize = switch (kb) {
  257. 0xa0...0xbf => blk: {
  258. d.pos += 1;
  259. break :blk kb & 0x1f;
  260. },
  261. 0xd9 => blk: {
  262. d.pos += 1;
  263. break :blk try d.readBigInt(u8);
  264. },
  265. 0xda => blk: {
  266. d.pos += 1;
  267. break :blk try d.readBigInt(u16);
  268. },
  269. 0xdb => blk: {
  270. d.pos += 1;
  271. break :blk try d.readBigInt(u32);
  272. },
  273. else => null,
  274. };
  275. var hit: ?usize = null;
  276. if (klen) |kl| {
  277. const ks = try d.take(kl);
  278. for (names, 0..) |nm, j| {
  279. if (out[j] == null and std.mem.eql(u8, nm, ks)) {
  280. hit = j;
  281. break;
  282. }
  283. }
  284. } else {
  285. try d.skipValue();
  286. }
  287. if (hit) |j| {
  288. out[j] = try d.readValue();
  289. } else {
  290. try d.skipValue();
  291. }
  292. }
  293. }
  294. /// Decode a record, optionally retaining only named top-level fields. The
  295. /// caller supplies unique names; absent fields do not become null entries.
  296. pub fn decodeRecord(alloc: std.mem.Allocator, bytes: []const u8, fields: ?[]const []const u8) Error!Value {
  297. const names = fields orelse return (try decode(alloc, bytes)).value;
  298. const vals = try alloc.alloc(?Value, names.len);
  299. try decodeFields(alloc, bytes, names, vals);
  300. var entries: std.ArrayList(Entry) = .empty;
  301. for (names, vals) |name, val| {
  302. if (val) |v| try entries.append(alloc, .{ .key = .{ .str = name }, .value = v });
  303. }
  304. return .{ .map = try entries.toOwnedSlice(alloc) };
  305. }
  306. /// Encode a Value in the canonical msgpackr form (see header comment).
  307. pub fn encode(alloc: std.mem.Allocator, value: Value) Error![]u8 {
  308. var buf: std.ArrayList(u8) = .empty;
  309. errdefer buf.deinit(alloc);
  310. try encodeInto(alloc, &buf, value);
  311. return buf.toOwnedSlice(alloc) catch Error.OutOfMemory;
  312. }
  313. pub fn encodeInto(alloc: std.mem.Allocator, buf: *std.ArrayList(u8), value: Value) Error!void {
  314. const w = Writer{ .alloc = alloc, .buf = buf };
  315. try w.writeValue(value);
  316. }
  317. const Writer = struct {
  318. alloc: std.mem.Allocator,
  319. buf: *std.ArrayList(u8),
  320. fn byte(self: Writer, b: u8) Error!void {
  321. self.buf.append(self.alloc, b) catch return Error.OutOfMemory;
  322. }
  323. fn raw(self: Writer, s: []const u8) Error!void {
  324. self.buf.appendSlice(self.alloc, s) catch return Error.OutOfMemory;
  325. }
  326. fn big(self: Writer, comptime T: type, v: T) Error!void {
  327. var tmp: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined;
  328. std.mem.writeInt(T, &tmp, v, .big);
  329. try self.raw(&tmp);
  330. }
  331. fn writeNumber(self: Writer, v: f64) Error!void {
  332. // msgpackr rule (measured): integer-valued and within [-2^31, 2^32) →
  333. // smallest int family; else float64. -0 encodes as fixint 0.
  334. if (v == @floor(v) and v >= -2147483648.0 and v <= 4294967295.0) {
  335. if (v >= 0) {
  336. const u: u32 = @intFromFloat(v);
  337. if (u < 0x80) return self.byte(@intCast(u));
  338. if (u <= 0xff) {
  339. try self.byte(0xcc);
  340. return self.byte(@intCast(u));
  341. }
  342. if (u <= 0xffff) {
  343. try self.byte(0xcd);
  344. return self.big(u16, @intCast(u));
  345. }
  346. try self.byte(0xce);
  347. return self.big(u32, u);
  348. } else {
  349. const i: i32 = @intFromFloat(v);
  350. if (i >= -32) return self.byte(@bitCast(@as(i8, @intCast(i))));
  351. if (i >= -128) {
  352. try self.byte(0xd0);
  353. return self.byte(@bitCast(@as(i8, @intCast(i))));
  354. }
  355. if (i >= -32768) {
  356. try self.byte(0xd1);
  357. return self.big(u16, @bitCast(@as(i16, @intCast(i))));
  358. }
  359. try self.byte(0xd2);
  360. return self.big(u32, @bitCast(i));
  361. }
  362. }
  363. try self.byte(0xcb);
  364. return self.big(u64, @bitCast(v));
  365. }
  366. fn writeStr(self: Writer, s: []const u8) Error!void {
  367. if (s.len <= 31) {
  368. try self.byte(0xa0 | @as(u8, @intCast(s.len)));
  369. } else if (s.len <= 0xff) {
  370. try self.byte(0xd9);
  371. try self.byte(@intCast(s.len));
  372. } else if (s.len <= 0xffff) {
  373. try self.byte(0xda);
  374. try self.big(u16, @intCast(s.len));
  375. } else {
  376. try self.byte(0xdb);
  377. try self.big(u32, @intCast(s.len));
  378. }
  379. return self.raw(s);
  380. }
  381. fn writeValue(self: Writer, value: Value) Error!void {
  382. switch (value) {
  383. .nil => try self.byte(0xc0),
  384. .undef => try self.raw(&[_]u8{ 0xd4, 0x00, 0x00 }),
  385. .boolean => |b| try self.byte(if (b) 0xc3 else 0xc2),
  386. .number => |n| try self.writeNumber(n),
  387. .str => |s| try self.writeStr(s),
  388. .bin => |s| {
  389. if (s.len <= 0xff) {
  390. try self.byte(0xc4);
  391. try self.byte(@intCast(s.len));
  392. } else if (s.len <= 0xffff) {
  393. try self.byte(0xc5);
  394. try self.big(u16, @intCast(s.len));
  395. } else {
  396. try self.byte(0xc6);
  397. try self.big(u32, @intCast(s.len));
  398. }
  399. try self.raw(s);
  400. },
  401. .array => |items| {
  402. if (items.len <= 15) {
  403. try self.byte(0x90 | @as(u8, @intCast(items.len)));
  404. } else if (items.len <= 0xffff) {
  405. try self.byte(0xdc);
  406. try self.big(u16, @intCast(items.len));
  407. } else {
  408. try self.byte(0xdd);
  409. try self.big(u32, @intCast(items.len));
  410. }
  411. for (items) |it| try self.writeValue(it);
  412. },
  413. .map => |entries| {
  414. // msgpackr: objects are ALWAYS map16, >65535 keys throws.
  415. if (entries.len > 0xffff) return Error.MapTooLarge;
  416. try self.byte(0xde);
  417. try self.big(u16, @intCast(entries.len));
  418. for (entries) |e| {
  419. try self.writeValue(e.key);
  420. try self.writeValue(e.value);
  421. }
  422. },
  423. .ext => |e| {
  424. switch (e.data.len) {
  425. 1 => try self.byte(0xd4),
  426. 2 => try self.byte(0xd5),
  427. 4 => try self.byte(0xd6),
  428. 8 => try self.byte(0xd7),
  429. 16 => try self.byte(0xd8),
  430. else => {
  431. if (e.data.len <= 0xff) {
  432. try self.byte(0xc7);
  433. try self.byte(@intCast(e.data.len));
  434. } else if (e.data.len <= 0xffff) {
  435. try self.byte(0xc8);
  436. try self.big(u16, @intCast(e.data.len));
  437. } else {
  438. try self.byte(0xc9);
  439. try self.big(u32, @intCast(e.data.len));
  440. }
  441. },
  442. }
  443. try self.byte(@bitCast(e.type));
  444. try self.raw(e.data);
  445. },
  446. }
  447. }
  448. };
  449. // =========================================================================
  450. // mpackdb record framing: [4-byte LE total size incl. prefix][msgpack]
  451. // =========================================================================
  452. /// Serialize a value with mpackdb's 4-byte little-endian length prefix.
  453. pub fn serialize(alloc: std.mem.Allocator, value: Value) Error![]u8 {
  454. var buf: std.ArrayList(u8) = .empty;
  455. errdefer buf.deinit(alloc);
  456. buf.appendSlice(alloc, &[_]u8{ 0, 0, 0, 0 }) catch return Error.OutOfMemory;
  457. try encodeInto(alloc, &buf, value);
  458. const total: u32 = @intCast(buf.items.len);
  459. std.mem.writeInt(u32, buf.items[0..4], total, .little);
  460. return buf.toOwnedSlice(alloc) catch Error.OutOfMemory;
  461. }
  462. /// Read the length prefix of a framed record (total size incl. the 4 bytes).
  463. pub fn readSize(bytes: []const u8) Error!u32 {
  464. if (bytes.len < 4) return Error.Truncated;
  465. return std.mem.readInt(u32, bytes[0..4], .little);
  466. }
  467. /// Deserialize a framed record ([4-byte LE size][msgpack]).
  468. pub fn deserializeFramed(alloc: std.mem.Allocator, bytes: []const u8) Error!Value {
  469. const total = try readSize(bytes);
  470. if (total < 5 or total > bytes.len) return Error.Truncated;
  471. const d = try decode(alloc, bytes[4..total]);
  472. return d.value;
  473. }
  474. // =========================================================================
  475. // Tests
  476. // =========================================================================
  477. const testing = std.testing;
  478. /// Linux-syscall file read (plugins avoid std.Io plumbing; same pattern as
  479. /// plugins/fs/fs.zig). Returns null when the file cannot be opened.
  480. fn readFileLinux(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {
  481. const linux = std.os.linux;
  482. const path_z = alloc.dupeZ(u8, path) catch return null;
  483. defer alloc.free(path_z);
  484. const rc = linux.open(path_z, .{}, 0);
  485. const fd: i32 = @bitCast(@as(u32, @truncate(rc)));
  486. if (fd < 0) return null;
  487. defer _ = linux.close(fd);
  488. var content: std.ArrayList(u8) = .empty;
  489. var buf: [65536]u8 = undefined;
  490. while (true) {
  491. const n = linux.read(fd, &buf, buf.len);
  492. if (@as(isize, @bitCast(n)) <= 0) break;
  493. content.appendSlice(alloc, buf[0..n]) catch return null;
  494. }
  495. return content.toOwnedSlice(alloc) catch null;
  496. }
  497. test "corpus: decode + canonical re-encode is byte-identical (msgpackr 1.11.5)" {
  498. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  499. defer arena.deinit();
  500. const alloc = arena.allocator();
  501. // Corpus lives next to this file; zig build test runs with cwd native/.
  502. const candidates = [_][]const u8{
  503. "../plugins/mpackdb/testdata/corpus.json",
  504. "plugins/mpackdb/testdata/corpus.json",
  505. };
  506. var content: ?[]u8 = null;
  507. for (candidates) |p| {
  508. content = readFileLinux(alloc, p) orelse continue;
  509. break;
  510. }
  511. const json = content orelse return error.CorpusNotFound;
  512. const parsed = try std.json.parseFromSlice(std.json.Value, alloc, json, .{});
  513. const arr = parsed.value.array;
  514. try testing.expect(arr.items.len >= 70);
  515. var checked: usize = 0;
  516. for (arr.items) |item| {
  517. const obj = item.object;
  518. const hex = obj.get("hex").?.string;
  519. const framed = if (obj.get("framed")) |f| f.bool else false;
  520. const bytes = try alloc.alloc(u8, hex.len / 2);
  521. _ = try std.fmt.hexToBytes(bytes, hex);
  522. if (framed) {
  523. // Frame round-trip: parse prefix, decode, re-serialize, compare all.
  524. const total = try readSize(bytes);
  525. try testing.expectEqual(bytes.len, @as(usize, total));
  526. const v = try deserializeFramed(alloc, bytes);
  527. const re = try serialize(alloc, v);
  528. try testing.expectEqualSlices(u8, bytes, re);
  529. } else {
  530. const d = try decode(alloc, bytes);
  531. try testing.expectEqual(bytes.len, d.len);
  532. const re = try encode(alloc, d.value);
  533. try testing.expectEqualSlices(u8, bytes, re);
  534. }
  535. checked += 1;
  536. }
  537. try testing.expect(checked == arr.items.len);
  538. }
  539. test "decode spot checks" {
  540. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  541. defer arena.deinit();
  542. const alloc = arena.allocator();
  543. // {name:'Alice', age:30} as msgpackr encodes it (map16)
  544. var bytes: [19]u8 = undefined;
  545. _ = try std.fmt.hexToBytes(&bytes, "de0002a46e616d65a5416c696365a36167651e");
  546. const d = try decode(alloc, &bytes);
  547. const name = d.value.get("name").?;
  548. try testing.expectEqualStrings("Alice", name.str);
  549. try testing.expectEqual(@as(f64, 30), d.value.get("age").?.number);
  550. }
  551. test "decode non-canonical families (full spec)" {
  552. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  553. defer arena.deinit();
  554. const alloc = arena.allocator();
  555. // fixmap {a:1}
  556. var b1: [4]u8 = undefined;
  557. _ = try std.fmt.hexToBytes(&b1, "81a16101");
  558. const v1 = try decode(alloc, &b1);
  559. try testing.expectEqual(@as(f64, 1), v1.value.get("a").?.number);
  560. // map32 {a:1}
  561. var b2: [8]u8 = undefined;
  562. _ = try std.fmt.hexToBytes(&b2, "df00000001a16101");
  563. const v2 = try decode(alloc, &b2);
  564. try testing.expectEqual(@as(f64, 1), v2.value.get("a").?.number);
  565. // int64 -1 (d3 ffffffffffffffff)
  566. var b3: [9]u8 = undefined;
  567. _ = try std.fmt.hexToBytes(&b3, "d3ffffffffffffffff");
  568. const v3 = try decode(alloc, &b3);
  569. try testing.expectEqual(@as(f64, -1), v3.value.number);
  570. // uint64 2^32 (cf 0000000100000000)
  571. var b4: [9]u8 = undefined;
  572. _ = try std.fmt.hexToBytes(&b4, "cf0000000100000000");
  573. const v4 = try decode(alloc, &b4);
  574. try testing.expectEqual(@as(f64, 4294967296), v4.value.number);
  575. // float32 0.5 (ca 3f000000)
  576. var b5: [5]u8 = undefined;
  577. _ = try std.fmt.hexToBytes(&b5, "ca3f000000");
  578. const v5 = try decode(alloc, &b5);
  579. try testing.expectEqual(@as(f64, 0.5), v5.value.number);
  580. // 0xc1 is invalid
  581. const bad = [_]u8{0xc1};
  582. try testing.expectError(Error.InvalidFormat, decode(alloc, &bad));
  583. }
  584. test "undefined is distinct and byte-exact" {
  585. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  586. defer arena.deinit();
  587. const alloc = arena.allocator();
  588. const bytes = [_]u8{ 0xd4, 0x00, 0x00 };
  589. const d = try decode(alloc, &bytes);
  590. try testing.expect(d.value == .undef);
  591. const re = try encode(alloc, d.value);
  592. try testing.expectEqualSlices(u8, &bytes, re);
  593. }
  594. test "timestamp ext interpretation" {
  595. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  596. defer arena.deinit();
  597. const alloc = arena.allocator();
  598. // date whole sec: d6 ff 66a39486 → 1721996422000 ms
  599. var b: [6]u8 = undefined;
  600. _ = try std.fmt.hexToBytes(&b, "d6ff66a39486");
  601. const d = try decode(alloc, &b);
  602. try testing.expectEqual(@as(f64, 1721996422000), d.value.timestampMs().?);
  603. // date ms: d7 ff 1d53530066a39486 → 1721996422123 ms
  604. var b2: [10]u8 = undefined;
  605. _ = try std.fmt.hexToBytes(&b2, "d7ff1d53530066a39486");
  606. const d2 = try decode(alloc, &b2);
  607. try testing.expectApproxEqAbs(@as(f64, 1721996422123), d2.value.timestampMs().?, 0.001);
  608. }
  609. test "framing" {
  610. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  611. defer arena.deinit();
  612. const alloc = arena.allocator();
  613. var entries = [_]Entry{
  614. .{ .key = .{ .str = "id" }, .value = .{ .number = 1 } },
  615. };
  616. const v = Value{ .map = &entries };
  617. const framed = try serialize(alloc, v);
  618. try testing.expectEqual(@as(u32, @intCast(framed.len)), try readSize(framed));
  619. const back = try deserializeFramed(alloc, framed);
  620. try testing.expectEqual(@as(f64, 1), back.get("id").?.number);
  621. }
  622. test "encode number boundaries match msgpackr" {
  623. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  624. defer arena.deinit();
  625. const alloc = arena.allocator();
  626. const cases = [_]struct { v: f64, hex: []const u8 }{
  627. .{ .v = 0, .hex = "00" },
  628. .{ .v = 127, .hex = "7f" },
  629. .{ .v = 128, .hex = "cc80" },
  630. .{ .v = 256, .hex = "cd0100" },
  631. .{ .v = 65536, .hex = "ce00010000" },
  632. .{ .v = 2147483648, .hex = "ce80000000" },
  633. .{ .v = 4294967296, .hex = "cb41f0000000000000" },
  634. .{ .v = -1, .hex = "ff" },
  635. .{ .v = -32, .hex = "e0" },
  636. .{ .v = -33, .hex = "d0df" },
  637. .{ .v = -129, .hex = "d1ff7f" },
  638. .{ .v = -32769, .hex = "d2ffff7fff" },
  639. .{ .v = -2147483648, .hex = "d280000000" },
  640. .{ .v = -2147483649, .hex = "cbc1e0000000200000" },
  641. .{ .v = 0.5, .hex = "cb3fe0000000000000" },
  642. };
  643. for (cases) |c| {
  644. const enc = try encode(alloc, Value{ .number = c.v });
  645. const expect_bytes = try alloc.alloc(u8, c.hex.len / 2);
  646. _ = try std.fmt.hexToBytes(expect_bytes, c.hex);
  647. try testing.expectEqualSlices(u8, expect_bytes, enc);
  648. }
  649. }
  650. // =========================================================================
  651. // Mission 436: decodeFields gives what decode + Value.get give
  652. // =========================================================================
  653. fn randValue(r: std.Random, arena: std.mem.Allocator, depth: u8) error{OutOfMemory}!Value {
  654. const kinds: u8 = if (depth > 3) 6 else 9;
  655. return switch (r.uintLessThan(u8, kinds)) {
  656. 0 => .nil,
  657. 1 => .{ .boolean = r.boolean() },
  658. 2 => .{ .number = @floatFromInt(r.int(i32)) },
  659. 3 => .{ .number = @as(f64, @floatFromInt(r.int(u16))) / 7.0 },
  660. 4 => blk: {
  661. const n = r.uintLessThan(usize, 40);
  662. const b = try arena.alloc(u8, n);
  663. for (b) |*c| c.* = 'a' + r.uintLessThan(u8, 26);
  664. break :blk .{ .str = b };
  665. },
  666. 5 => .{ .bin = try arena.dupe(u8, "\x01\x02\x03") },
  667. 6 => blk: {
  668. const n = r.uintLessThan(usize, 4);
  669. const items = try arena.alloc(Value, n);
  670. for (items) |*it| it.* = try randValue(r, arena, depth + 1);
  671. break :blk .{ .array = items };
  672. },
  673. 7 => try randMap(r, arena, depth + 1),
  674. else => .{ .ext = .{ .type = -1, .data = try arena.dupe(u8, "\x00\x00\x00\x01") } },
  675. };
  676. }
  677. fn randMap(r: std.Random, arena: std.mem.Allocator, depth: u8) error{OutOfMemory}!Value {
  678. const names = [_][]const u8{ "id", "oldId", "name", "n" };
  679. const n = r.uintLessThan(usize, 6);
  680. const es = try arena.alloc(Entry, n);
  681. for (es) |*e| {
  682. e.key = if (r.uintLessThan(u8, 8) == 0) Value{ .number = 3 } else Value{ .str = names[r.uintLessThan(usize, names.len)] };
  683. e.value = try randValue(r, arena, depth);
  684. }
  685. return .{ .map = es };
  686. }
  687. fn sameValue(a: ?Value, b: ?Value) bool {
  688. if (a == null or b == null) return a == null and b == null;
  689. return std.meta.activeTag(a.?) == std.meta.activeTag(b.?) and switch (a.?) {
  690. .str => |s| std.mem.eql(u8, s, b.?.str),
  691. .number => |x| x == b.?.number or (std.math.isNan(x) and std.math.isNan(b.?.number)),
  692. .boolean => |x| x == b.?.boolean,
  693. else => true,
  694. };
  695. }
  696. test "436: decodeFields = decode + get, on random records and on damaged ones" {
  697. var prng = std.Random.DefaultPrng.init(436);
  698. const r = prng.random();
  699. var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
  700. defer arena_state.deinit();
  701. const names = [_][]const u8{ "id", "oldId", "zzz" };
  702. var round: usize = 0;
  703. while (round < 20000) : (round += 1) {
  704. _ = arena_state.reset(.retain_capacity);
  705. const arena = arena_state.allocator();
  706. const v = if (r.uintLessThan(u8, 12) == 0) try randValue(r, arena, 0) else try randMap(r, arena, 0);
  707. var bytes = try encode(arena, v);
  708. switch (r.uintLessThan(u8, 6)) {
  709. 0 => bytes = bytes[0..r.uintLessThan(usize, bytes.len + 1)],
  710. 1 => {
  711. if (bytes.len > 0) bytes[r.uintLessThan(usize, bytes.len)] = r.uintLessThan(u8, 0xc2); // no big counts: decode allocates n values up front
  712. },
  713. else => {},
  714. }
  715. var out: [3]?Value = undefined;
  716. const got = decodeFields(arena, bytes, &names, &out);
  717. const want = decode(arena, bytes);
  718. if (want) |w| {
  719. try testing.expect(got != error.Truncated and got != error.InvalidFormat);
  720. try got;
  721. for (names, 0..) |nm, i| try testing.expect(sameValue(out[i], w.value.get(nm)));
  722. } else |_| {
  723. try testing.expect(std.meta.isError(got));
  724. }
  725. }
  726. }
  727. test "600: projected records preserve values, order, absence and null" {
  728. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  729. defer arena.deinit();
  730. const a = arena.allocator();
  731. // Nested map, null, binary, timestamp and undefined from actual MessagePack families.
  732. const bytes = "\x85\xa4keep\x81\xa1x\x92\x01\xc0\xa3nil\xc0\xa3bin\xc4\x02ab\xa4date\xd6\xff\x00\x00\x00\x01\xa5undef\xd4\x00\x00";
  733. const names = [_][]const u8{ "date", "missing", "nil", "keep", "bin", "undef" };
  734. const got = try decodeRecord(a, bytes, &names);
  735. const full = (try decode(a, bytes)).value;
  736. try testing.expectEqual(@as(usize, 5), got.map.len);
  737. try testing.expectEqualStrings("date", got.map[0].key.str);
  738. try testing.expect(got.get("missing") == null);
  739. try testing.expect(got.get("nil").? == .nil);
  740. for (names) |name| {
  741. if (full.get(name)) |value| {
  742. try testing.expectEqualSlices(u8, try encode(a, value), try encode(a, got.get(name).?));
  743. }
  744. }
  745. try testing.expectEqual(@as(usize, 0), (try decodeRecord(a, bytes, &.{})).map.len);
  746. // Unselected data is still validated, including nested invalid and truncated values.
  747. try testing.expectError(Error.InvalidFormat, decodeRecord(a, "\x81\xa1x\x91\xc1", &.{}));
  748. try testing.expectError(Error.Truncated, decodeRecord(a, "\x81\xa1x\xc6\x00\x00\x01\x00", &.{}));
  749. }
  750. test "600: skipping the codec corpus allocates nothing" {
  751. const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, @embedFile("testdata/corpus.json"), .{});
  752. defer parsed.deinit();
  753. for (parsed.value.array.items) |item| {
  754. const hex = item.object.get("hex").?.string;
  755. const bytes = try testing.allocator.alloc(u8, hex.len / 2);
  756. defer testing.allocator.free(bytes);
  757. _ = try std.fmt.hexToBytes(bytes, hex);
  758. var out: [0]?Value = .{};
  759. // No requested fields: even strings, arrays, maps and extensions need no allocator.
  760. try decodeFields(std.testing.failing_allocator, bytes, &.{}, &out);
  761. }
  762. }

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre