canon-yaml: Factor key comparaison function into separate file

This is function that user most likely will want to customize, so
let's make it easier to do so. Especially, since it requires no
sacrifices for me.
This commit is contained in:
Dmitry Bogatov 2024-05-20 23:11:02 -04:00
parent 4b1fbf05bb
commit 00fb05922f

View File

@ -1,3 +1,4 @@
const custom = @import("./customize.zig");
const std = @import("std");
const w = @cImport({
@cInclude("words.h");
@ -9,34 +10,6 @@ const yaml = @cImport({
const mmap = @import("./mmap.zig");
fn word_less_then(v1: []const u8, v2: []const u8) bool {
var k1 = w.in_word_set(v1.ptr, v1.len);
var k2 = w.in_word_set(v2.ptr, v2.len);
// I need to be perfectly compatible with following Haskell snippet:
//
// compareBy (\s -> (Down $ HashMap.lookup s keywordsMap, s))
//
// which is not exactly logical, unfortunately.
if (k1) |k1p| {
if (k2) |k2p| {
return k1p.*.index > k2p.*.index;
} else {
return true;
}
}
if (k2) |k2p| {
if (k1) |k1p| {
return k1p.*.index > k2p.*.index;
} else {
return false;
}
}
return std.mem.order(u8, v1, v2) == std.math.Order.lt;
}
// Tagged pointers are likely more memory-efficient than tagged unions, and, what is
// more important, they are C ABI-compatible, unlike native tagged unions, which enables
// nice tricks with re-interpreting memory.
@ -100,7 +73,7 @@ fn event_text(event: *yaml.yaml_event_t) []u8 {
}
fn event_less(e1: *yaml.yaml_event_t, e2: *yaml.yaml_event_t) bool {
return word_less_then(event_text(e1), event_text(e2));
return custom.key_less({}, event_text(e1), event_text(e2));
}
// The tree structure of the YAML document, reusing raw libyaml "yaml_event_t" objects