daegun 1.1.0

Your all-in-one text engine. Rust, no_std, zero dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
// SAFETY, once for the file. Every entry point null-checks its pointers and answers
// `Status::Null` before dereferencing anything, so the `unsafe` blocks below rest on a check
// immediately above them. Where a call takes a raw buffer, its length is the caller's promise
// from `daegun.h` and is not checkable here.

use alloc::borrow::ToOwned;
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::ffi::{CStr, c_char, c_void};

use crate::{Font, bytes, format};

use crate::ffi::handle::{Bytes, OwnedStr, Status, Str, borrow, deliver, release};
use crate::ffi::list::{Axis, Blob, F64List, GlyphValue, GlyphValueList, StrList, U16List, UsizeList, axes_of};
use crate::ffi::pen::{Pen, PenBridge};
use crate::ffi::set_error;

unsafe fn tag_of<'a>(s: *const c_char) -> Option<&'a str> {
    if s.is_null() {
        return None;
    }
    unsafe { CStr::from_ptr(s) }.to_str().ok()
}

unsafe fn slice_of<'a>(data: *const u8, len: usize) -> &'a [u8] {
    if data.is_null() || len == 0 {
        return &[];
    }
    unsafe { core::slice::from_raw_parts(data, len) }
}

#[inline]
unsafe fn put<T>(out: *mut T, value: T) -> Status {
    if out.is_null() {
        return Status::Null;
    }
    unsafe { *out = value };
    Status::Ok
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_font_table(
    font: *const Font,
    tag: *const c_char,
    out: *mut Bytes,
) -> Status {
    let Some(font) = (unsafe { borrow(font) }) else { return Status::Null };
    let Some(tag) = (unsafe { tag_of(tag) }) else { return Status::Null };
    match font.table(tag) {
        Some(data) => unsafe { put(out, Bytes::of(data)) },
        None => {
            if out.is_null() {
                return Status::Null;
            }
            // Cleared so a caller who ignores the status reads an empty run rather than whatever
            // was in the variable.
            unsafe { *out = Bytes::EMPTY };
            Status::Absent
        }
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_font_table_tags(
    font: *const Font,
    out: *mut *mut StrList,
) -> Status {
    let Some(font) = (unsafe { borrow(font) }) else { return Status::Null };
    let tags = font.table_tags().into_iter().map(str::to_owned);
    unsafe { deliver(out, StrList::new(tags)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_font_has_table(
    font: *const Font,
    tag: *const c_char,
    out: *mut i32,
) -> Status {
    let Some(font) = (unsafe { borrow(font) }) else { return Status::Null };
    let Some(tag) = (unsafe { tag_of(tag) }) else { return Status::Null };
    unsafe { put(out, i32::from(font.has_table(tag))) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_font_instance_tables(
    font: *const Font,
    axes: *const Axis,
    axis_count: usize,
    out: *mut *mut TableMap,
) -> Status {
    let Some(font) = (unsafe { borrow(font) }) else { return Status::Null };
    let axes = unsafe { axes_of(axes, axis_count) };
    let Some(tables) = font.instance_tables(&axes) else { return Status::Absent };
    let owned = tables.into_iter().map(|(tag, data)| (tag, data.into_owned())).collect();
    unsafe { deliver(out, TableMap::from_map(owned)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_font_instance_table(
    font: *const Font,
    axes: *const Axis,
    axis_count: usize,
    tag: *const c_char,
    out: *mut *mut Blob,
) -> Status {
    let Some(font) = (unsafe { borrow(font) }) else { return Status::Null };
    let Some(tag) = (unsafe { tag_of(tag) }) else { return Status::Null };
    let axes = unsafe { axes_of(axes, axis_count) };
    let Some(tables) = font.instance_tables(&axes) else { return Status::Absent };
    let Some(data) = tables.get(tag) else { return Status::Absent };
    unsafe { deliver(out, Blob(data.to_vec())) }
}

pub struct TableMap {
    tables: BTreeMap<String, Vec<u8>>,
    tags: Vec<OwnedStr>,
}

impl TableMap {
    fn from_map(tables: BTreeMap<String, Vec<u8>>) -> TableMap {
        let tags = tables.keys().map(|t| OwnedStr::new(t)).collect();
        TableMap { tables, tags }
    }

    fn resync(&mut self) {
        self.tags = self.tables.keys().map(|t| OwnedStr::new(t)).collect();
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn daegun_table_map_new() -> *mut TableMap {
    alloc::boxed::Box::into_raw(alloc::boxed::Box::new(TableMap::from_map(BTreeMap::new())))
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_count(map: *const TableMap, out: *mut usize) -> Status {
    let Some(map) = (unsafe { borrow(map) }) else { return Status::Null };
    unsafe { put(out, map.tables.len()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_tag_at(
    map: *const TableMap,
    index: usize,
    out: *mut Str,
) -> Status {
    let Some(map) = (unsafe { borrow(map) }) else { return Status::Null };
    let Some(tag) = map.tags.get(index) else { return Status::Range };
    unsafe { put(out, tag.as_str()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_bytes_at(
    map: *const TableMap,
    index: usize,
    out: *mut Bytes,
) -> Status {
    let Some(map) = (unsafe { borrow(map) }) else { return Status::Null };
    let Some((_, data)) = map.tables.iter().nth(index) else { return Status::Range };
    unsafe { put(out, Bytes::of(data)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_get(
    map: *const TableMap,
    tag: *const c_char,
    out: *mut Bytes,
) -> Status {
    let Some(map) = (unsafe { borrow(map) }) else { return Status::Null };
    let Some(tag) = (unsafe { tag_of(tag) }) else { return Status::Null };
    match map.tables.get(tag) {
        Some(data) => unsafe { put(out, Bytes::of(data)) },
        None => Status::Absent,
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_set(
    map: *mut TableMap,
    tag: *const c_char,
    data: *const u8,
    len: usize,
) -> Status {
    if map.is_null() {
        return Status::Null;
    }
    let Some(tag) = (unsafe { tag_of(tag) }) else { return Status::Null };
    let map = unsafe { &mut *map };
    map.tables.insert(tag.to_string(), unsafe { slice_of(data, len) }.to_vec());
    map.resync();
    Status::Ok
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_remove(
    map: *mut TableMap,
    tag: *const c_char,
) -> Status {
    if map.is_null() {
        return Status::Null;
    }
    let Some(tag) = (unsafe { tag_of(tag) }) else { return Status::Null };
    let map = unsafe { &mut *map };
    if map.tables.remove(tag).is_none() {
        return Status::Absent;
    }
    map.resync();
    Status::Ok
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_build(
    map: *const TableMap,
    out: *mut *mut Blob,
) -> Status {
    let Some(map) = (unsafe { borrow(map) }) else { return Status::Null };
    if map.tables.is_empty() {
        set_error("cannot build a font from an empty table map");
        return Status::Range;
    }
    unsafe { deliver(out, Blob(crate::build_font(&map.tables))) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_table_map_free(map: *mut TableMap) {
    unsafe { release(map) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_parse_loca(
    loca: *const u8,
    len: usize,
    format: i16,
    num_glyphs: usize,
    out: *mut *mut UsizeList,
) -> Status {
    let loca = unsafe { slice_of(loca, len) };
    unsafe { deliver(out, UsizeList(crate::parse_loca(loca, format, num_glyphs))) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_outline_glyf_bytes(
    glyf: *const u8,
    glyf_len: usize,
    loca: *const usize,
    loca_len: usize,
    glyph: u16,
    pen: *const Pen,
) -> Status {
    let Some(pen) = (unsafe { borrow(pen) }) else { return Status::Null };
    let glyf = unsafe { slice_of(glyf, glyf_len) };
    let loca = if loca.is_null() || loca_len == 0 {
        &[][..]
    } else {
        unsafe { core::slice::from_raw_parts(loca, loca_len) }
    };
    let mut bridge = PenBridge(*pen);
    match crate::outline_glyf_bytes(glyf, loca, glyph, &mut bridge) {
        Ok(()) => Status::Ok,
        Err(e) => {
            set_error(&e);
            Status::Parse
        }
    }
}

macro_rules! reader {
    ($name:ident, $call:path, $ty:ty) => {
        #[unsafe(no_mangle)]
        pub unsafe extern "C" fn $name(
            data: *const u8,
            len: usize,
            off: usize,
            out: *mut $ty,
        ) -> Status {
            let data = unsafe { slice_of(data, len) };
            match $call(data, off) {
                Some(v) => unsafe { put(out, v) },
                None => Status::Range,
            }
        }
    };
}

reader!(daegun_read_u16_be, bytes::read_u16_be, u16);
reader!(daegun_read_i16_be, bytes::read_i16_be, i16);
reader!(daegun_read_u24_be, bytes::read_u24_be, u32);
reader!(daegun_read_u32_be, bytes::read_u32_be, u32);
reader!(daegun_read_offset24, bytes::read_offset24, usize);

macro_rules! writer {
    ($name:ident, $call:path, $ty:ty, $width:expr) => {
        #[unsafe(no_mangle)]
        pub unsafe extern "C" fn $name(
            data: *mut u8,
            len: usize,
            off: usize,
            value: $ty,
        ) -> Status {
            if data.is_null() {
                return Status::Null;
            }
            if off.checked_add($width).is_none_or(|end| end > len) {
                return Status::Range;
            }
            let data = unsafe { core::slice::from_raw_parts_mut(data, len) };
            $call(data, off, value);
            Status::Ok
        }
    };
}

writer!(daegun_write_u16_be, bytes::write_u16_be, u16, 2);
writer!(daegun_write_i16_be, bytes::write_i16_be, i16, 2);
writer!(daegun_write_u32_be, bytes::write_u32_be, u32, 4);
writer!(daegun_write_offset24, bytes::write_offset24, usize, 3);

#[unsafe(no_mangle)]
pub extern "C" fn daegun_records_fit(
    start: usize,
    count: usize,
    stride: usize,
    len: usize,
) -> i32 {
    i32::from(bytes::records_fit(start, count, stride, len))
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_bytes_window(
    data: *const u8,
    len: usize,
    off: usize,
    n: usize,
) -> *const u8 {
    let slice = unsafe { slice_of(data, len) };
    match off.checked_add(n) {
        Some(end) if end <= slice.len() => slice[off..end].as_ptr(),
        _ => core::ptr::null(),
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_search_records(
    count: usize,
    target: u32,
    key_at: Option<extern "C" fn(usize, *mut c_void, *mut u32) -> i32>,
    user: *mut c_void,
    out_index: *mut usize,
    out_found: *mut i32,
) -> Status {
    let Some(key_at) = key_at else { return Status::Null };
    if out_index.is_null() || out_found.is_null() {
        return Status::Null;
    }
    let found = bytes::search_records(count, target, |i| {
        let mut key = 0u32;
        (key_at(i, user, &mut key) != 0).then_some(key)
    });
    let Some(result) = found else { return Status::Absent };
    let (index, hit) = match result {
        Ok(i) => (i, 1),
        Err(i) => (i, 0),
    };
    unsafe {
        *out_index = index;
        *out_found = hit;
    }
    Status::Ok
}

#[unsafe(no_mangle)]
pub extern "C" fn daegun_ot_round(value: f64) -> i32 {
    format::ot_round(value)
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_coverage_index(
    data: *const u8,
    len: usize,
    glyph: u16,
    out: *mut u16,
) -> Status {
    let data = unsafe { slice_of(data, len) };
    match format::coverage_index(data, glyph) {
        Some(i) => unsafe { put(out, i) },
        None => Status::Absent,
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_coverage_glyphs(
    buf: *const u8,
    len: usize,
    off: usize,
    out: *mut *mut U16List,
) -> Status {
    let buf = unsafe { slice_of(buf, len) };
    match format::coverage_glyphs(buf, off) {
        Ok(glyphs) => unsafe { deliver(out, U16List(glyphs)) },
        Err(e) => {
            set_error(&e);
            Status::Parse
        }
    }
}

pub struct AatLookup {
    data: Vec<u8>,
    num_glyphs: u16,
}

impl AatLookup {
    fn view(&self) -> Option<format::Lookup<'_>> {
        format::Lookup::parse(&self.data, self.num_glyphs)
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_lookup_open(
    data: *const u8,
    len: usize,
    num_glyphs: u16,
    out: *mut *mut AatLookup,
) -> Status {
    let data = unsafe { slice_of(data, len) };
    if format::Lookup::parse(data, num_glyphs).is_none() {
        set_error("aat lookup did not parse");
        return Status::Parse;
    }
    unsafe { deliver(out, AatLookup { data: data.to_vec(), num_glyphs }) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_lookup_value(
    lookup: *const AatLookup,
    glyph: u16,
    out: *mut u16,
) -> Status {
    let Some(lookup) = (unsafe { borrow(lookup) }) else { return Status::Null };
    let Some(view) = lookup.view() else { return Status::Parse };
    match view.value(glyph) {
        Some(v) => unsafe { put(out, v) },
        None => Status::Absent,
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_lookup_entries(
    lookup: *const AatLookup,
    out: *mut *mut GlyphValueList,
) -> Status {
    let Some(lookup) = (unsafe { borrow(lookup) }) else { return Status::Null };
    let Some(view) = lookup.view() else { return Status::Parse };
    let entries =
        view.entries().into_iter().map(|(glyph, value)| GlyphValue { glyph, value }).collect();
    unsafe { deliver(out, GlyphValueList(entries)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_lookup_free(lookup: *mut AatLookup) {
    unsafe { release(lookup) }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct AatEntry {
    pub new_state: u16,
    pub flags: u16,
    pub word1: u16,
    pub word2: u16,
}

const _: () = assert!(size_of::<AatEntry>() == 8);
const _: () = assert!(align_of::<AatEntry>() == 2);

pub struct AatStateTable {
    data: Vec<u8>,
    extra_words: usize,
    num_glyphs: u16,
}

impl AatStateTable {
    fn view(&self) -> Option<format::StateTable<'_>> {
        format::StateTable::parse(&self.data, self.extra_words, self.num_glyphs)
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_state_table_open(
    data: *const u8,
    len: usize,
    extra_words: usize,
    num_glyphs: u16,
    out: *mut *mut AatStateTable,
) -> Status {
    let data = unsafe { slice_of(data, len) };
    if format::StateTable::parse(data, extra_words, num_glyphs).is_none() {
        set_error("aat state table did not parse");
        return Status::Parse;
    }
    unsafe { deliver(out, AatStateTable { data: data.to_vec(), extra_words, num_glyphs }) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_state_table_class(
    table: *const AatStateTable,
    glyph: u16,
    out: *mut u16,
) -> Status {
    let Some(table) = (unsafe { borrow(table) }) else { return Status::Null };
    let Some(view) = table.view() else { return Status::Parse };
    unsafe { put(out, view.class(glyph)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_state_table_entry(
    table: *const AatStateTable,
    state: u16,
    class: u16,
    out: *mut AatEntry,
) -> Status {
    let Some(table) = (unsafe { borrow(table) }) else { return Status::Null };
    let Some(view) = table.view() else { return Status::Parse };
    let Some(entry) = view.entry(state, class) else { return Status::Range };
    unsafe {
        put(
            out,
            AatEntry {
                new_state: entry.new_state,
                flags: entry.flags,
                word1: entry.word1,
                word2: entry.word2,
            },
        )
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_aat_state_table_free(table: *mut AatStateTable) {
    unsafe { release(table) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ankr_version(
    data: *const u8,
    len: usize,
    out: *mut u16,
) -> Status {
    let data = unsafe { slice_of(data, len) };
    match format::ankr_version(data) {
        Some(v) => unsafe { put(out, v) },
        None => Status::Range,
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ankr_control_point(
    data: *const u8,
    len: usize,
    at: usize,
    out_x: *mut i16,
    out_y: *mut i16,
) -> Status {
    let data = unsafe { slice_of(data, len) };
    let Some((x, y)) = format::control_point(data, at) else { return Status::Range };
    if out_x.is_null() || out_y.is_null() {
        return Status::Null;
    }
    unsafe {
        *out_x = x;
        *out_y = y;
    }
    Status::Ok
}

pub struct Ankr {
    data: Vec<u8>,
    num_glyphs: u16,
}

impl Ankr {
    fn view(&self) -> Option<format::Ankr<'_>> {
        format::Ankr::parse(&self.data, self.num_glyphs)
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ankr_open(
    data: *const u8,
    len: usize,
    num_glyphs: u16,
    out: *mut *mut Ankr,
) -> Status {
    let data = unsafe { slice_of(data, len) };
    if format::Ankr::parse(data, num_glyphs).is_none() {
        set_error("ankr table did not parse");
        return Status::Parse;
    }
    unsafe { deliver(out, Ankr { data: data.to_vec(), num_glyphs }) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ankr_point_count(
    ankr: *const Ankr,
    glyph: u16,
    out: *mut u32,
) -> Status {
    let Some(ankr) = (unsafe { borrow(ankr) }) else { return Status::Null };
    let Some(view) = ankr.view() else { return Status::Parse };
    unsafe { put(out, view.point_count(glyph)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ankr_anchor_point(
    ankr: *const Ankr,
    glyph: u16,
    index: u16,
    out_x: *mut i16,
    out_y: *mut i16,
) -> Status {
    let Some(ankr) = (unsafe { borrow(ankr) }) else { return Status::Null };
    let Some(view) = ankr.view() else { return Status::Parse };
    let Some((x, y)) = view.anchor_point(glyph, index) else { return Status::Absent };
    if out_x.is_null() || out_y.is_null() {
        return Status::Null;
    }
    unsafe {
        *out_x = x;
        *out_y = y;
    }
    Status::Ok
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ankr_free(ankr: *mut Ankr) {
    unsafe { release(ankr) }
}

pub struct FeatureVariations {
    layout: Vec<u8>,
    at: Option<usize>,
}

impl FeatureVariations {
    fn view(&self) -> Option<format::FeatureVariations<'_>> {
        match self.at {
            Some(at) => Some(format::FeatureVariations::at(&self.layout, at)),
            None => format::FeatureVariations::parse(&self.layout),
        }
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_feature_variations_open(
    layout: *const u8,
    len: usize,
    out: *mut *mut FeatureVariations,
) -> Status {
    let layout = unsafe { slice_of(layout, len) };
    if format::FeatureVariations::parse(layout).is_none() {
        return Status::Absent;
    }
    unsafe { deliver(out, FeatureVariations { layout: layout.to_vec(), at: None }) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_feature_variations_at(
    layout: *const u8,
    len: usize,
    at: usize,
    out: *mut *mut FeatureVariations,
) -> Status {
    let layout = unsafe { slice_of(layout, len) };
    unsafe { deliver(out, FeatureVariations { layout: layout.to_vec(), at: Some(at) }) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_feature_variations_find(
    vars: *const FeatureVariations,
    coords: *const i32,
    coord_count: usize,
    out: *mut u16,
) -> Status {
    let Some(vars) = (unsafe { borrow(vars) }) else { return Status::Null };
    let Some(view) = vars.view() else { return Status::Absent };
    let coords = if coords.is_null() || coord_count == 0 {
        &[][..]
    } else {
        unsafe { core::slice::from_raw_parts(coords, coord_count) }
    };
    match view.find(coords) {
        Some(v) => unsafe { put(out, v) },
        None => Status::Absent,
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_feature_variations_substitute(
    vars: *const FeatureVariations,
    variation: u16,
    feature: u16,
    out: *mut usize,
) -> Status {
    let Some(vars) = (unsafe { borrow(vars) }) else { return Status::Null };
    let Some(view) = vars.view() else { return Status::Absent };
    match view.substitute(variation, feature) {
        Some(off) => unsafe { put(out, off) },
        None => Status::Absent,
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_feature_variations_free(vars: *mut FeatureVariations) {
    unsafe { release(vars) }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct RegionAxis {
    pub start: f64,
    pub peak: f64,
    pub end: f64,
}

const _: () = assert!(size_of::<RegionAxis>() == 24);
const _: () = assert!(align_of::<RegionAxis>() == 8);

pub struct Ivs(crate::format::ItemVariationStore);

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_parse(
    buf: *const u8,
    len: usize,
    base: usize,
    out: *mut *mut Ivs,
) -> Status {
    let buf = unsafe { slice_of(buf, len) };
    match format::parse_item_variation_store(buf, base) {
        Ok(store) => unsafe { deliver(out, Ivs(store)) },
        Err(e) => {
            set_error(&e);
            Status::Parse
        }
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_axis_count(ivs: *const Ivs, out: *mut usize) -> Status {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return Status::Null };
    unsafe { put(out, ivs.0.axis_count) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_region_count(ivs: *const Ivs, out: *mut usize) -> Status {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return Status::Null };
    unsafe { put(out, ivs.0.regions.len()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_region_axis(
    ivs: *const Ivs,
    region: usize,
    axis: usize,
    out: *mut RegionAxis,
) -> Status {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return Status::Null };
    let Some(a) = ivs.0.regions.get(region).and_then(|r| r.get(axis)) else {
        return Status::Range;
    };
    unsafe { put(out, RegionAxis { start: a.start, peak: a.peak, end: a.end }) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_ivd_count(ivs: *const Ivs, out: *mut usize) -> Status {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return Status::Null };
    unsafe { put(out, ivs.0.ivd_data.len()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_ivd_rows(
    ivs: *const Ivs,
    ivd: usize,
    out: *mut usize,
) -> Status {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return Status::Null };
    let Some(data) = ivs.0.ivd_data.get(ivd) else { return Status::Range };
    unsafe { put(out, data.rows()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_ivd_region_indices(
    ivs: *const Ivs,
    ivd: usize,
    out_count: *mut usize,
) -> *const usize {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return core::ptr::null() };
    if out_count.is_null() {
        return core::ptr::null();
    }
    let Some(data) = ivs.0.ivd_data.get(ivd) else { return core::ptr::null() };
    unsafe { *out_count = data.region_indices.len() };
    data.region_indices.as_ptr()
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_ivd_row(
    ivs: *const Ivs,
    ivd: usize,
    inner: usize,
    out_count: *mut usize,
) -> *const i32 {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return core::ptr::null() };
    if out_count.is_null() {
        return core::ptr::null();
    }
    let Some(row) = ivs.0.ivd_data.get(ivd).and_then(|d| d.row(inner)) else {
        return core::ptr::null();
    };
    unsafe { *out_count = row.len() };
    row.as_ptr()
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_region_scalars(
    ivs: *const Ivs,
    location: *const f64,
    axis_count: usize,
    out: *mut *mut F64List,
) -> Status {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return Status::Null };
    let location = if location.is_null() || axis_count == 0 {
        &[][..]
    } else {
        unsafe { core::slice::from_raw_parts(location, axis_count) }
    };
    unsafe { deliver(out, F64List(format::precompute_region_scalars(&ivs.0, location))) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_delta(
    ivs: *const Ivs,
    outer: usize,
    inner: usize,
    scalars: *const f64,
    scalar_count: usize,
    out: *mut f64,
) -> Status {
    let Some(ivs) = (unsafe { borrow(ivs) }) else { return Status::Null };
    let scalars = if scalars.is_null() || scalar_count == 0 {
        &[][..]
    } else {
        unsafe { core::slice::from_raw_parts(scalars, scalar_count) }
    };
    unsafe { put(out, format::compute_ivs_delta_f64(&ivs.0, outer, inner, scalars)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_ivs_free(ivs: *mut Ivs) {
    unsafe { release(ivs) }
}

pub struct DeltaSetIndexMap(Vec<(u32, u32)>);

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_delta_set_index_map_parse(
    buf: *const u8,
    len: usize,
    base: usize,
    out: *mut *mut DeltaSetIndexMap,
) -> Status {
    let buf = unsafe { slice_of(buf, len) };
    match format::parse_delta_set_index_map(buf, base) {
        Ok(map) => unsafe { deliver(out, DeltaSetIndexMap(map)) },
        Err(e) => {
            set_error(&e);
            Status::Parse
        }
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_delta_set_index_map_count(
    map: *const DeltaSetIndexMap,
    out: *mut usize,
) -> Status {
    let Some(map) = (unsafe { borrow(map) }) else { return Status::Null };
    unsafe { put(out, map.0.len()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_delta_set_index_map_lookup(
    map: *const DeltaSetIndexMap,
    index: usize,
    out_outer: *mut usize,
    out_inner: *mut usize,
) -> Status {
    let Some(map) = (unsafe { borrow(map) }) else { return Status::Null };
    if out_outer.is_null() || out_inner.is_null() {
        return Status::Null;
    }
    let (outer, inner) = format::delta_set_index_map_lookup(&map.0, index);
    unsafe {
        *out_outer = outer;
        *out_inner = inner;
    }
    Status::Ok
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn daegun_delta_set_index_map_free(map: *mut DeltaSetIndexMap) {
    unsafe { release(map) }
}