Skip to main content

keyrill_ffi/
lib.rs

1//! C ABI over [`keyrill_core`] for native input-method adapters.
2//!
3//! Built as a static library and linked into each platform adapter. `include/keyrill.h` is the
4//! caller contract: struct layouts, ownership, threading, versioning and every status code. The
5//! exports here implement it. Native Rust adapters use the same entry points and bounded views.
6//!
7//! The boundary keeps everything Rust owns out of native reach. Events are copied into owned
8//! values before the session sees them, and plans are copied out into fixed-size `#[repr(C)]`
9//! structs whose arrays belong to the caller, so no Rust allocation, borrow or lifetime crosses
10//! the interface and the adapter frees nothing but handles. Every export that can fail runs
11//! inside [`std::panic::catch_unwind`]: a panic marks the handle poisoned, and every later call
12//! on it returns `KR_POISONED` rather than touch state the panic may have left half-updated.
13//! Rust never calls back into the adapter, so no Rust borrow is live while native code runs.
14//!
15//! ```text
16//!   adapter (C, Objective-C++, ...)         keyrill-ffi                  keyrill-core
17//!   kr_event, caller-owned     --copy-->    decode_event   --Event-->    Session::propose*
18//!   kr_plan, caller-owned      <--copy--    NativePlan     <--Plan---
19//!   kr_commit(plan_id, outcome)   ------------------------------------>  Session::acknowledge
20//! ```
21//!
22//! - Engine handles (`kr_engine_*`, `kr_plan_event`, `kr_commit`) wrap one
23//!   [`keyrill_core::session::Session`] each, copy every buffer across the boundary, catch
24//!   panics and poison the handle on one.
25//! - Configuration (`kr_set_automatic_policy`, `kr_set_keyboard`) applies while idle.
26//! - Dictionaries (`kr_dictionary_parse_utf8`, `kr_adopt_dictionaries`,
27//!   `kr_set_dictionary_utf8`, `kr_clear_dictionary`,
28//!   `kr_dictionary_skipped_lines`) publish and describe immutable snapshots; reading files
29//!   stays in the adapter.
30//! - The compatibility family (`kr_plan_compatibility_event`, `kr_commit_compatibility`) tracks
31//!   observed input for the macOS synthetic-rewrite backend, separately from verified edits.
32//! - `vocabulary_source` and `kr_vocabulary_*` read and settle dictionary files on a serial
33//!   queue for the adapter, and name Vim's default spell files under a home directory.
34//!
35//! `docs/porting.md` explains how a new platform adapter uses these calls.
36#![deny(unsafe_op_in_unsafe_fn)]
37
38pub mod vocabulary_source;
39
40pub mod vocabulary_host;
41
42mod compatibility;
43mod dictionary;
44
45pub use dictionary::{
46    Dictionary, kr_adopt_dictionaries, kr_dictionary_free, kr_dictionary_parse_utf8,
47    kr_prepare_model,
48};
49
50// Lives at the crate root because `vocabulary_source` forbids unsafe code, tests included
51#[cfg(all(test, unix))]
52fn descriptor_flags(file: &std::fs::File) -> i32 {
53    use std::os::fd::AsRawFd;
54    // SAFETY: the borrowed File keeps the descriptor live; F_GETFL takes no third argument
55    unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFL) }
56}
57
58use keyrill_core::inference::{Dictionaries, Policy};
59use keyrill_core::mapping::Keyboard;
60use keyrill_core::model::{Model, ModelError};
61use keyrill_core::session::{Action, Context, Disposition, Event, Mode, Outcome, Session};
62use keyrill_core::vocabulary::{MAX_SOURCE_BYTES, Snapshot, Vocabulary};
63use std::panic::{AssertUnwindSafe, catch_unwind};
64use std::sync::{Arc, OnceLock};
65
66// Status codes, the KR_* values of include/keyrill.h
67const OK: u32 = 0;
68const NULL: u32 = 1;
69const BOUNDS: u32 = 2;
70const BAD_TAG: u32 = 3;
71const STALE: u32 = 4;
72const STATE: u32 = 5;
73const POISONED: u32 = 6;
74const VERSION: u32 = 7;
75const MODEL_ASSET: u32 = 8;
76const DICTIONARY_DATA: u32 = 9;
77// KR_ABI_VERSION, major << 16 | minor
78const ABI: u32 = 0x0000_0003;
79
80// The plan/commit family a handle is bound to. The first successful plan selects it and reset
81// keeps it, so composition and compatibility state never meet in one session.
82#[derive(Default, PartialEq, Eq)]
83enum Backend {
84    #[default]
85    Unselected,
86    Composition,
87    Compatibility,
88}
89
90// A compatibility plan awaiting acknowledgement, with the tracker state that takes effect only
91// if it is acknowledged; the three flags mirror the `compatibility_*` fields of `Engine`
92#[derive(Clone, Copy)]
93struct CompatibilityPending {
94    id: u64,
95    rewrite: bool,
96    boundary: bool,
97    word_boundary: bool,
98    collect: bool,
99}
100
101// Before 1.0 the ABI makes no compatibility promise, so only the exact version is accepted
102fn compatible_abi(abi: u32) -> bool {
103    abi == ABI
104}
105
106// The automatic policy kr_set_automatic_policy selected
107#[derive(Default)]
108enum Automatic {
109    #[default]
110    Off,
111    Fixture,
112    Model(Model<'static>),
113}
114
115/// `kr_engine`: one word session for one input context, owned by the native adapter.
116///
117/// The handle holds no native object and no reference into the adapter. Mutable access must be
118/// serialized without aliasing; the exports take a unique borrow for the length of one call.
119pub struct Engine {
120    session: Session,
121    poisoned: bool,
122    automatic: Automatic,
123    // English and Russian Vim dictionaries; a missing one keeps the automatic policy unready
124    dictionaries: [Snapshot; 2],
125    // Learned-word lists, changed only by kr_adopt_vocabulary
126    learned: Vec<Arc<Vocabulary>>,
127    backend: Backend,
128    // The last observed input was a Space, so a word that starts next may be corrected
129    // automatically; reset clears it, since activation shows no document boundary
130    compatibility_boundary: bool,
131    // The tracked word started right after an observed Space
132    compatibility_word_boundary: bool,
133    // The next letter may start a tracked word: true after reset or a Space, false after any
134    // other observed input, so a word glued to an identifier or punctuation is never collected
135    compatibility_collect: bool,
136    compatibility_pending: Option<CompatibilityPending>,
137}
138
139/// `kr_event`: one key or command, read by value; `len` counts the UTF-16 units in use.
140#[repr(C)]
141#[derive(Clone, Copy)]
142pub struct NativeEvent {
143    role: u32,
144    mode: u32,
145    context: u32,
146    len: u32,
147    units: [u16; 8],
148}
149
150/// `kr_plan`: a proposal copied into caller-owned arrays; no Rust allocation crosses the
151/// interface.
152#[repr(C)]
153pub struct NativePlan {
154    plan_id: u64,
155    action: u32,
156    disposition: u32,
157    expected_len: u32,
158    mark_len: u32,
159    expected: [u16; 128],
160    mark: [u16; 128],
161}
162
163impl NativeEvent {
164    /// Copy a bounded wire event using the tags defined in `include/keyrill.h`.
165    ///
166    /// The engine validates tags when planning. Native key translation may represent an unmapped
167    /// layout with mode zero, which the engine refuses.
168    ///
169    /// # Errors
170    /// Returns the C ABI bounds status when the input exceeds eight UTF-16 units.
171    ///
172    /// ```
173    /// let event = keyrill_ffi::NativeEvent::new(1, 1, 0, &[b'g' as u16]);
174    /// assert!(event.is_ok());
175    /// ```
176    pub fn new(role: u32, mode: u32, context: u32, units: &[u16]) -> Result<Self, u32> {
177        if units.len() > 8 {
178            return Err(BOUNDS);
179        }
180        let mut event = Self {
181            role,
182            mode,
183            context,
184            len: units.len() as u32,
185            units: [0; 8],
186        };
187        event.units[..units.len()].copy_from_slice(units);
188        Ok(event)
189    }
190
191    /// Borrow wire fields with a bounded text buffer.
192    ///
193    /// # Errors
194    /// Returns the C ABI bounds status if a foreign caller supplied an oversized length.
195    pub fn view(&self) -> Result<NativeEventView<'_>, u32> {
196        if self.len > 8 {
197            return Err(BOUNDS);
198        }
199        Ok(NativeEventView {
200            role: self.role,
201            mode: self.mode,
202            context: self.context,
203            units: &self.units[..self.len as usize],
204        })
205    }
206}
207
208/// Read-only bounded wire event. The engine remains responsible for tag validation.
209pub struct NativeEventView<'a> {
210    /// Physical input role using the C ABI tags.
211    pub role: u32,
212    /// Observed input mode, including zero for an unmapped native layout.
213    pub mode: u32,
214    /// Native eligibility context using the C ABI tags.
215    pub context: u32,
216    /// Copied physical text in UTF-16 units.
217    pub units: &'a [u16],
218}
219
220/// Read-only view of a successfully initialized proposal.
221pub struct NativePlanView<'a> {
222    /// Latest-only acknowledgement token.
223    pub plan_id: u64,
224    /// Proposed operation, using the C ABI action tags.
225    pub action: u32,
226    /// Proposed physical-key disposition.
227    pub disposition: u32,
228    /// Exact previously verified marked text.
229    pub expected: &'a [u16],
230    /// Exact proposed marked text.
231    pub mark: &'a [u16],
232}
233
234impl NativePlan {
235    /// Borrow bounded buffers after `kr_plan_event` returned the C ABI OK status.
236    ///
237    /// Buffers belong to this copied proposal. Native adapters copy them before calling a host.
238    pub fn view(&self) -> NativePlanView<'_> {
239        NativePlanView {
240            plan_id: self.plan_id,
241            action: self.action,
242            disposition: self.disposition,
243            expected: &self.expected[..self.expected_len as usize],
244            mark: &self.mark[..self.mark_len as usize],
245        }
246    }
247}
248
249/// Best-effort committed-input proposal; submission is not document verification.
250#[repr(C)]
251pub struct CompatibilityPlan {
252    plan_id: u64,
253    operation: u32,
254    disposition: u32,
255    delete_units: u32,
256    replacement_len: u32,
257    replacement: [u16; 128],
258}
259
260// The same layouts the header's static assertions pin
261const _: () = assert!(size_of::<CompatibilityPlan>() == 280);
262
263const _: () = assert!(size_of::<NativeEvent>() == 32);
264const _: () = assert!(size_of::<NativePlan>() == 536);
265const _: () = assert!(std::mem::offset_of!(NativePlan, expected) == 24);
266// A word plus its Space fits the 128-unit plan arrays
267const _: () = assert!(keyrill_core::session::MAX_WORD < 128);
268// KR_MAX_DICTIONARY_BYTES
269const _: () = assert!(MAX_SOURCE_BYTES == 1_048_576);
270
271// Validated once per process; every engine that selects MODEL shares the result, a failure too
272fn embedded_model() -> Result<Model<'static>, ModelError> {
273    static MODEL: OnceLock<Result<Model<'static>, ModelError>> = OnceLock::new();
274    *MODEL.get_or_init(Model::embedded)
275}
276
277// The model loader is a parameter so a test can inject an asset failure
278fn set_policy(
279    engine: &mut Engine,
280    policy: u32,
281    model: impl FnOnce() -> Result<Model<'static>, ModelError>,
282) -> u32 {
283    if policy > 2 {
284        return BAD_TAG;
285    }
286    // Also the Idle check: an owned word or a pending plan refuses before anything changes
287    if let Err(error) = engine.session.set_fixtures(policy == 1) {
288        return status(error);
289    }
290    if matches!(
291        (&engine.automatic, policy),
292        (Automatic::Off, 0) | (Automatic::Fixture, 1) | (Automatic::Model(_), 2)
293    ) {
294        return OK;
295    }
296    engine.session.reset();
297    engine.compatibility_pending = None;
298    engine.compatibility_boundary = false;
299    engine.compatibility_word_boundary = false;
300    engine.compatibility_collect = true;
301    // Not redundant: a model failure returns from inside the match and must leave OFF behind
302    engine.automatic = Automatic::Off;
303    engine.automatic = match policy {
304        0 => Automatic::Off,
305        1 => Automatic::Fixture,
306        _ => match model() {
307            Ok(model) => Automatic::Model(model),
308            Err(_) => return MODEL_ASSET,
309        },
310    };
311    OK
312}
313
314fn status(error: keyrill_core::session::Error) -> u32 {
315    match error {
316        keyrill_core::session::Error::Stale => STALE,
317        keyrill_core::session::Error::Invalidated => STATE,
318    }
319}
320
321fn decode_event(event: &NativeEvent) -> Result<(Event, Mode, Context), u32> {
322    if event.len > 8 {
323        return Err(BOUNDS);
324    }
325    let mode = match event.mode {
326        1 => Mode::En,
327        2 => Mode::Ru,
328        _ => return Err(BAD_TAG),
329    };
330    let context = match event.context {
331        0 => Context::Boundary,
332        1 => Context::Ineligible,
333        _ => return Err(BAD_TAG),
334    };
335    if event.role != 1 && event.len != 0 {
336        return Err(BAD_TAG);
337    }
338    let input = match event.role {
339        1 => Event::Text(event.units[..event.len as usize].to_vec()),
340        2 => Event::Backspace,
341        3 => Event::Escape,
342        4 => Event::Manual,
343        5 => Event::Reverse,
344        6 => Event::Finish,
345        _ => return Err(BAD_TAG),
346    };
347    Ok((input, mode, context))
348}
349
350// `automatic` false asks for a manual-only proposal; otherwise the selected policy decides,
351// with the fixture flag kept inside the session
352fn propose(
353    engine: &mut Engine,
354    input: &Event,
355    mode: Mode,
356    context: Context,
357    automatic: bool,
358) -> Result<keyrill_core::session::Plan, keyrill_core::session::Error> {
359    if !automatic {
360        return engine
361            .session
362            .propose_without_automatic(input, mode, context);
363    }
364    match &engine.automatic {
365        Automatic::Model(model) => {
366            let en = engine.dictionaries[0].current();
367            let ru = engine.dictionaries[1].current();
368            engine.session.propose_with_inference(
369                input,
370                mode,
371                context,
372                model,
373                Dictionaries {
374                    en: en.as_deref(),
375                    ru: ru.as_deref(),
376                    learned: &engine.learned,
377                },
378                Policy::default(),
379            )
380        }
381        _ => engine.session.propose(input, mode, context),
382    }
383}
384
385// Callers provide live, uniquely borrowed handles. No callback is made while this borrow
386// exists; every export releases it before returning to native code. A panic in `f` poisons the
387// handle, which also drops the word, history and pending plans it held. AssertUnwindSafe is
388// acceptable because nothing relies on state a panic may have left inconsistent: the handle is
389// only reset, and every later call returns POISONED before touching it.
390unsafe fn with_engine(pointer: *mut Engine, f: impl FnOnce(&mut Engine) -> u32) -> u32 {
391    if pointer.is_null() {
392        return NULL;
393    }
394    // SAFETY: non-null was checked above; the caller contract requires a live aligned handle from
395    // kr_engine_new, not yet freed, with no other reference to it alive during this call
396    let engine = unsafe { &mut *pointer };
397    if engine.poisoned {
398        return POISONED;
399    }
400    match catch_unwind(AssertUnwindSafe(|| f(engine))) {
401        Ok(result) => result,
402        Err(_) => {
403            engine.poisoned = true;
404            engine.session.reset();
405            engine.compatibility_pending = None;
406            POISONED
407        }
408    }
409}
410
411/// Return the major/minor ABI version. No allocation or panicking work occurs.
412#[unsafe(no_mangle)]
413pub extern "C" fn kr_abi_version() -> u32 {
414    ABI
415}
416
417/// Allocate an engine in Idle with the OFF policy, the Apple keyboard and both dictionaries
418/// missing. `*out` is set to null first and receives the handle only on `KR_OK`.
419///
420/// # Safety
421/// `out` must be null, or writable and aligned for one handle pointer; it must not alias a live
422/// handle.
423#[unsafe(no_mangle)]
424pub unsafe extern "C" fn kr_engine_new(abi: u32, out: *mut *mut Engine) -> u32 {
425    if out.is_null() {
426        return NULL;
427    }
428    // SAFETY: `out` is non-null (checked above), and the caller guarantees it is aligned and
429    // writable for one pointer
430    unsafe {
431        out.write(std::ptr::null_mut());
432    }
433    if !compatible_abi(abi) {
434        return VERSION;
435    }
436    match catch_unwind(|| {
437        Box::new(Engine {
438            session: Session::default(),
439            poisoned: false,
440            automatic: Automatic::Off,
441            dictionaries: [Snapshot::default(), Snapshot::default()],
442            learned: Vec::new(),
443            backend: Backend::Unselected,
444            compatibility_boundary: false,
445            compatibility_word_boundary: false,
446            compatibility_collect: true,
447            compatibility_pending: None,
448        })
449    }) {
450        Ok(engine) => {
451            // SAFETY: same output contract; allocation is transferred exactly once
452            unsafe {
453                out.write(Box::into_raw(engine));
454            }
455            OK
456        }
457        Err(_) => POISONED,
458    }
459}
460
461/// Free once, after every call on the engine has returned and no callback can reach it. Null is
462/// a no-op.
463///
464/// # Safety
465/// A non-null pointer must be the live allocation returned by `kr_engine_new`, with no aliases.
466#[unsafe(no_mangle)]
467pub unsafe extern "C" fn kr_engine_free(pointer: *mut Engine) {
468    if !pointer.is_null() {
469        // An unwind must not cross into C; a panic while dropping is discarded
470        let _ = catch_unwind(AssertUnwindSafe(|| {
471            // SAFETY: caller transfers the original unique allocation exactly once
472            drop(unsafe { Box::from_raw(pointer) });
473        }));
474    }
475}
476
477/// Drop the word, its receipt, pending plans and history, and clear an invalidated session, as
478/// the adapter does on each generation change. Configuration and the selected backend survive;
479/// poisoning is permanent.
480///
481/// # Safety
482/// `pointer` must meet the live unique serialized handle contract, or be null.
483#[unsafe(no_mangle)]
484pub unsafe extern "C" fn kr_reset(pointer: *mut Engine) -> u32 {
485    // SAFETY: forwarded handle contract; no native callbacks occur in this closure
486    unsafe {
487        with_engine(pointer, |engine| {
488            engine.session.reset();
489            engine.compatibility_pending = None;
490            engine.compatibility_boundary = false;
491            engine.compatibility_word_boundary = false;
492            engine.compatibility_collect = true;
493            OK
494        })
495    }
496}
497
498/// Select OFF, the test FIXTURE, or the frozen MODEL policy while idle, outside input callbacks.
499///
500/// # Safety
501/// `pointer` must meet the live unique serialized handle contract, or be null.
502#[unsafe(no_mangle)]
503pub unsafe extern "C" fn kr_set_automatic_policy(pointer: *mut Engine, policy: u32) -> u32 {
504    // SAFETY: forwarded handle contract; validation performs no native callbacks
505    unsafe { with_engine(pointer, |engine| set_policy(engine, policy, embedded_model)) }
506}
507
508/// Select the APPLE or PC Russian map while idle, outside input callbacks.
509///
510/// # Safety
511/// `pointer` must meet the live unique serialized handle contract, or be null.
512#[unsafe(no_mangle)]
513pub unsafe extern "C" fn kr_set_keyboard(pointer: *mut Engine, keyboard: u32) -> u32 {
514    // SAFETY: forwarded handle contract; validation performs no native callbacks
515    unsafe {
516        with_engine(pointer, |engine| {
517            let keyboard = match keyboard {
518                0 => Keyboard::Apple,
519                1 => Keyboard::Pc,
520                _ => return BAD_TAG,
521            };
522            engine
523                .session
524                .set_keyboard(keyboard)
525                .map_or_else(status, |()| OK)
526        })
527    }
528}
529
530/// Publish a complete bounded UTF-8 protection source, retaining last-good on parse failure.
531/// Prepare accepted updates outside input callbacks; an outstanding proposal rejects publication.
532///
533/// # Safety
534/// The handle must be live and uniquely borrowed for this serialized call, or null. Non-null
535/// `bytes` with `len <= MAX_SOURCE_BYTES` must address that many readable bytes without aliasing
536/// the handle. Null and oversized arguments are checked without dereferencing the buffer; null
537/// with zero length is valid empty data. No input pointer is retained.
538#[unsafe(no_mangle)]
539pub unsafe extern "C" fn kr_set_dictionary_utf8(
540    pointer: *mut Engine,
541    language: u32,
542    bytes: *const u8,
543    len: u32,
544) -> u32 {
545    // SAFETY: forwarded handle contract; candidate bytes are borrowed only inside this closure
546    unsafe {
547        with_engine(pointer, |engine| {
548            let index = match language {
549                1 => 0,
550                2 => 1,
551                _ => return BAD_TAG,
552            };
553            if engine.session.has_pending() {
554                return STATE;
555            }
556            if len as usize > MAX_SOURCE_BYTES {
557                return BOUNDS;
558            }
559            let source = if len == 0 {
560                &[]
561            } else {
562                if bytes.is_null() {
563                    return NULL;
564                }
565                // SAFETY: `bytes` is non-null and `len` nonzero and at most MAX_SOURCE_BYTES (both
566                // checked above); the caller guarantees `len` readable bytes that do not alias the
567                // handle and stay valid for this call, and the slice does not outlive it
568                std::slice::from_raw_parts(bytes, len as usize)
569            };
570            engine.dictionaries[index]
571                .replace(source)
572                .map_or(DICTIONARY_DATA, |()| OK)
573        })
574    }
575}
576
577/// Explicitly make a protection source missing, without reviving editing authority.
578/// Apply outside input callbacks; an outstanding proposal rejects the operation.
579///
580/// # Safety
581/// `pointer` must meet the live unique serialized handle contract, or be null.
582#[unsafe(no_mangle)]
583pub unsafe extern "C" fn kr_clear_dictionary(pointer: *mut Engine, language: u32) -> u32 {
584    // SAFETY: forwarded handle contract; no native callbacks occur
585    unsafe {
586        with_engine(pointer, |engine| {
587            let index = match language {
588                1 => 0,
589                2 => 1,
590                _ => return BAD_TAG,
591            };
592            if engine.session.has_pending() {
593                return STATE;
594            }
595            engine.dictionaries[index] = Snapshot::default();
596            OK
597        })
598    }
599}
600
601/// Write the skipped-line count of a language's current source; a missing source is STATE.
602///
603/// # Safety
604/// `pointer` must meet the live unique serialized handle contract, or be null. A non-null `out`
605/// must be aligned and writable for one `u32` and must not alias the handle.
606#[unsafe(no_mangle)]
607pub unsafe extern "C" fn kr_dictionary_skipped_lines(
608    pointer: *mut Engine,
609    language: u32,
610    out: *mut u32,
611) -> u32 {
612    if out.is_null() {
613        return NULL;
614    }
615    // SAFETY: forwarded handle contract; `out` is non-null (checked above) and, by contract,
616    // aligned, writable and distinct from the handle; it is written once after validation
617    unsafe {
618        with_engine(pointer, |engine| {
619            let index = match language {
620                1 => 0,
621                2 => 1,
622                _ => return BAD_TAG,
623            };
624            let Some(source) = engine.dictionaries[index].current() else {
625                return STATE;
626            };
627            // A source of at most 1 MiB has far fewer than u32::MAX lines
628            out.write(source.skipped() as u32);
629            OK
630        })
631    }
632}
633
634/// Copy a proposal out without installing its state; it becomes the only plan
635/// [`kr_commit`] accepts, replacing an earlier unacknowledged one.
636///
637/// # Safety
638/// Handle, event and output must be live, aligned, nonaliasing C objects with their declared sizes.
639#[unsafe(no_mangle)]
640pub unsafe extern "C" fn kr_plan_event(
641    pointer: *mut Engine,
642    event: *const NativeEvent,
643    out: *mut NativePlan,
644) -> u32 {
645    if event.is_null() || out.is_null() {
646        return NULL;
647    }
648    // SAFETY: forwarded handle contract. `event` and `out` are non-null (checked above) and, by
649    // contract, aligned, valid for their whole C object and distinct from the handle. The event
650    // is borrowed only while decode_event copies it, and `out` is written once with a whole plan.
651    unsafe {
652        with_engine(pointer, |engine| {
653            let event = &*event;
654            let (input, mode, context) = match decode_event(event) {
655                Ok(decoded) => decoded,
656                Err(error) => return error,
657            };
658            if engine.backend == Backend::Compatibility {
659                return STATE;
660            }
661            let proposal = propose(engine, &input, mode, context, true);
662            let plan = match proposal {
663                Ok(plan) => plan,
664                Err(error) => return status(error),
665            };
666            // Only a successful plan binds the handle to a backend
667            engine.backend = Backend::Composition;
668            let mut copied = NativePlan {
669                plan_id: plan.id,
670                action: match plan.action {
671                    Action::Pass => 0,
672                    Action::Mark => 1,
673                    Action::Finish => 2,
674                    Action::Unavailable => 3,
675                },
676                disposition: match plan.disposition {
677                    Disposition::Pass => 0,
678                    Disposition::Consumed => 1,
679                    Disposition::Replan => 2,
680                },
681                expected_len: plan.expected.len() as u32,
682                mark_len: plan.text.len() as u32,
683                expected: [0; 128],
684                mark: [0; 128],
685            };
686            // Conversion maps unit for unit, so both texts are at most a MAX_WORD word plus Space
687            copied.expected[..plan.expected.len()].copy_from_slice(&plan.expected);
688            copied.mark[..plan.text.len()].copy_from_slice(&plan.text);
689            out.write(copied);
690            OK
691        })
692    }
693}
694
695/// Acknowledge the latest plan; refused and unknown outcomes invalidate the session until
696/// [`kr_reset`]. A stale token changes nothing.
697///
698/// # Safety
699/// `pointer` must meet the live unique serialized handle contract, or be null.
700#[unsafe(no_mangle)]
701pub unsafe extern "C" fn kr_commit(pointer: *mut Engine, token: u64, outcome: u32) -> u32 {
702    // SAFETY: forwarded handle contract
703    unsafe {
704        with_engine(pointer, |engine| {
705            let outcome = match outcome {
706                0 => Outcome::Verified,
707                1 => Outcome::Refused,
708                2 => Outcome::Unknown,
709                _ => return BAD_TAG,
710            };
711            if engine.backend == Backend::Compatibility {
712                return STATE;
713            }
714            engine
715                .session
716                .acknowledge(token, outcome)
717                .map_or_else(status, |()| OK)
718        })
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725
726    #[test]
727    fn rust_adapter_event_construction_and_borrowed_plan_match_the_abi() {
728        assert!(matches!(NativeEvent::new(1, 1, 0, &[0; 9]), Err(BOUNDS)));
729        for role in 2..=6 {
730            assert!(NativeEvent::new(role, 2, 1, &[]).is_ok());
731        }
732        let mut source = [b'g' as u16];
733        let event = NativeEvent::new(1, 1, 0, &source).unwrap();
734        source[0] = b'x' as u16;
735        assert_eq!(source, [b'x' as u16]);
736        let mut engine = std::ptr::null_mut();
737        let mut storage = std::mem::MaybeUninit::uninit();
738        // SAFETY: distinct local objects provide valid ABI storage. The unique handle drains here.
739        unsafe {
740            assert_eq!(kr_engine_new(ABI, &mut engine), OK);
741            for event in [
742                NativeEvent::new(2, 1, 0, &[1]),
743                NativeEvent::new(7, 1, 0, &[]),
744                NativeEvent::new(1, 0, 0, &[]),
745                NativeEvent::new(1, 1, 2, &[]),
746            ] {
747                let invalid = event.unwrap();
748                assert_eq!(
749                    kr_plan_event(engine, &invalid, storage.as_mut_ptr()),
750                    BAD_TAG
751                );
752            }
753            assert_eq!(kr_plan_event(engine, &event, storage.as_mut_ptr()), OK);
754            let plan = storage.assume_init();
755            let view = plan.view();
756            assert_eq!(view.action, 1);
757            assert_eq!(view.disposition, 1);
758            assert_eq!(view.expected, &[]);
759            assert_eq!(view.mark, &[b'g' as u16]);
760            assert_eq!(kr_commit(engine, view.plan_id, 0), OK);
761            kr_engine_free(engine);
762        }
763    }
764
765    // Plan one event and acknowledge it as verified, following at most one REPLAN the way an
766    // adapter does
767    pub(super) unsafe fn apply_event(engine: *mut Engine, event: &NativeEvent) -> NativePlan {
768        // SAFETY: the test retains the unique live handle and distinct local C objects
769        unsafe {
770            for attempt in 0..2 {
771                let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
772                assert_eq!(kr_plan_event(engine, event, out.as_mut_ptr()), OK);
773                let plan = out.assume_init();
774                assert_eq!(kr_commit(engine, plan.plan_id, 0), OK);
775                if plan.disposition != 2 {
776                    return plan;
777                }
778                assert_eq!((attempt, plan.action), (0, 2));
779            }
780            unreachable!("a second replan is a protocol error")
781        }
782    }
783
784    // Type each UTF-16 unit as a KR_TEXT event at a boundary and return the last plan
785    pub(super) unsafe fn type_text(engine: *mut Engine, mode: u32, text: &str) -> NativePlan {
786        // SAFETY: the handle remains live and serialized; every event is a distinct local object
787        unsafe {
788            text.encode_utf16()
789                .map(|unit| {
790                    let mut units = [0; 8];
791                    units[0] = unit;
792                    apply_event(
793                        engine,
794                        &NativeEvent {
795                            role: 1,
796                            mode,
797                            context: 0,
798                            len: 1,
799                            units,
800                        },
801                    )
802                })
803                .last()
804                .unwrap()
805        }
806    }
807
808    // Every refused call leaves the published snapshot, the pending plan and the policy as they
809    // were. Publishing a partly parsed list, keeping a pointer to the caller's buffer
810    // (overwritten below after publication) or falling back to FIXTURE after a model failure
811    // would each change what a later lookup or plan sees.
812    #[test]
813    fn dictionary_buffers_configuration_and_failed_asset_are_transactional() {
814        use keyrill_core::vocabulary::Membership;
815        use std::sync::Arc;
816
817        // SAFETY: inputs are null where allowed or backed by live distinct C objects/buffers.
818        // No call overlaps another Rust borrow; each allocated handle is freed exactly once.
819        unsafe {
820            let mut engine = std::ptr::null_mut();
821            assert_eq!(kr_abi_version(), 0x0000_0003);
822            assert_eq!(kr_engine_new(ABI, &mut engine), OK);
823            assert_eq!(kr_set_automatic_policy(std::ptr::null_mut(), 0), NULL);
824            assert_eq!(kr_clear_dictionary(std::ptr::null_mut(), 1), NULL);
825            assert_eq!(
826                kr_set_dictionary_utf8(std::ptr::null_mut(), 1, std::ptr::null(), 0),
827                NULL
828            );
829            assert_eq!(kr_set_automatic_policy(engine, 3), BAD_TAG);
830            assert_eq!(
831                kr_set_dictionary_utf8(engine, 0, std::ptr::null(), 0),
832                BAD_TAG
833            );
834            assert_eq!(kr_clear_dictionary(engine, 3), BAD_TAG);
835            assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 1), NULL);
836            assert_eq!(
837                kr_set_dictionary_utf8(engine, 1, std::ptr::null(), MAX_SOURCE_BYTES as u32 + 1),
838                BOUNDS
839            );
840            let mut source = b"cgbcjr".to_vec();
841            assert_eq!(
842                kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
843                OK
844            );
845            let old = (*engine).dictionaries[0].current().unwrap();
846            source.fill(b'x');
847            let original: Vec<_> = "cgbcjr".encode_utf16().collect();
848            assert_eq!(old.lookup(&original), Membership::Recognized);
849            for invalid in [b"a\0b".as_slice(), b"/encoding=latin1\nword"] {
850                assert_eq!(
851                    kr_set_dictionary_utf8(engine, 1, invalid.as_ptr(), invalid.len() as u32),
852                    DICTIONARY_DATA
853                );
854                assert!(Arc::ptr_eq(
855                    &old,
856                    &(*engine).dictionaries[0].current().unwrap()
857                ));
858            }
859            let event = NativeEvent {
860                role: 1,
861                mode: 1,
862                context: 0,
863                len: 1,
864                units: [97; 8],
865            };
866            let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
867            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
868            let pending = out.assume_init_read();
869            assert_eq!(
870                kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
871                STATE
872            );
873            assert_eq!(kr_clear_dictionary(engine, 1), STATE);
874            assert_eq!(kr_set_automatic_policy(engine, 2), STATE);
875            assert!(Arc::ptr_eq(
876                &old,
877                &(*engine).dictionaries[0].current().unwrap()
878            ));
879            assert_eq!(kr_commit(engine, pending.plan_id, 0), OK);
880            assert_eq!(kr_set_automatic_policy(engine, 2), STATE);
881            assert_eq!(kr_set_dictionary_utf8(engine, 1, source.as_ptr(), 0), OK);
882            assert!((*engine).dictionaries[0].current().unwrap().is_empty());
883            assert_eq!(kr_set_dictionary_utf8(engine, 2, std::ptr::null(), 0), OK);
884            assert_eq!(kr_clear_dictionary(engine, 1), OK);
885            assert!((*engine).dictionaries[0].current().is_none());
886            assert!((*engine).dictionaries[1].current().unwrap().is_empty());
887            assert_eq!(old.lookup(&original), Membership::Recognized);
888            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
889            assert_eq!(kr_commit(engine, out.assume_init_read().plan_id, 2), OK);
890            assert_eq!(kr_clear_dictionary(engine, 2), OK);
891            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), STATE);
892            assert_eq!(kr_reset(engine), OK);
893            assert_eq!(kr_set_automatic_policy(engine, 1), OK);
894            assert_eq!(
895                with_engine(engine, |engine| set_policy(engine, 2, || Err(
896                    ModelError::Magic
897                ))),
898                MODEL_ASSET
899            );
900            let plan = type_text(engine, 1, "ghbdtn ");
901            assert_eq!(
902                &plan.mark[..plan.mark_len as usize],
903                "ghbdtn ".encode_utf16().collect::<Vec<_>>()
904            );
905            assert_eq!(kr_reset(engine), OK);
906            assert_eq!(
907                with_engine(engine, |_| panic!("synthetic policy containment test")),
908                POISONED
909            );
910            assert_eq!(kr_set_automatic_policy(engine, 0), POISONED);
911            assert_eq!(
912                kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0),
913                POISONED
914            );
915            assert_eq!(kr_clear_dictionary(engine, 1), POISONED);
916            kr_engine_free(engine);
917
918            assert_eq!(kr_engine_new(0x0001_0000, &mut engine), VERSION);
919            assert!(engine.is_null());
920            assert_eq!(kr_engine_new(ABI - 1, &mut engine), VERSION);
921            assert!(engine.is_null());
922        }
923    }
924
925    // The keyboard decides only how the ё key converts, changes only while Idle and survives
926    // reset; the skipped-line count follows the current source and survives a refused
927    // publication. Escape with a receipt restores the typed word and is consumed; without one
928    // it finishes the word and passes.
929    #[test]
930    fn keyboard_selection_and_skipped_lines_follow_the_configuration_contract() {
931        let units = |s: &str| s.encode_utf16().collect::<Vec<_>>();
932        let event = |role, mode| NativeEvent {
933            role,
934            mode,
935            context: 0,
936            len: 0,
937            units: [0; 8],
938        };
939        // SAFETY: the test exclusively retains the opaque allocation; events, outputs and
940        // source buffers are live distinct locals for each serialized call and never retained
941        unsafe {
942            let mut engine = std::ptr::null_mut();
943            assert_eq!(kr_engine_new(ABI, &mut engine), OK);
944            assert_eq!(kr_set_keyboard(std::ptr::null_mut(), 0), NULL);
945            for (keyboard, converted) in [(None, "\\krf"), (Some(1), "`krf"), (Some(0), "\\krf")] {
946                if let Some(keyboard) = keyboard {
947                    assert_eq!(kr_set_keyboard(engine, keyboard), OK);
948                    assert_eq!(kr_set_keyboard(engine, keyboard), OK);
949                }
950                assert_eq!(kr_reset(engine), OK);
951                type_text(engine, 2, "ёлка");
952                assert_eq!(kr_set_keyboard(engine, 1), STATE);
953                let manual = apply_event(engine, &event(4, 2));
954                assert_eq!(&manual.mark[..manual.mark_len as usize], units(converted));
955                let reverse = apply_event(engine, &event(5, 2));
956                assert_eq!(&reverse.mark[..reverse.mark_len as usize], units("ёлка"));
957                apply_event(engine, &event(6, 2));
958            }
959            for tag in [2, u32::MAX] {
960                assert_eq!(kr_set_keyboard(engine, tag), BAD_TAG);
961            }
962
963            // Pending and owned states refuse, and reset keeps the selection
964            assert_eq!(kr_set_keyboard(engine, 1), OK);
965            let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
966            let mut letter = event(1, 2);
967            letter.len = 1;
968            letter.units[0] = 0x451;
969            assert_eq!(kr_plan_event(engine, &letter, out.as_mut_ptr()), OK);
970            let pending = out.assume_init_read();
971            assert_eq!(kr_set_keyboard(engine, 0), STATE);
972            assert_eq!(kr_commit(engine, pending.plan_id, 0), OK);
973            assert_eq!(kr_set_keyboard(engine, 0), STATE);
974            assert_eq!(kr_reset(engine), OK);
975            type_text(engine, 2, "ё");
976            let manual = apply_event(engine, &event(4, 2));
977            assert_eq!(&manual.mark[..manual.mark_len as usize], units("`"));
978            let plan = apply_event(engine, &event(3, 2));
979            assert_eq!((plan.action, plan.disposition, plan.mark_len), (2, 1, 1));
980            assert_eq!(plan.mark[0], 0x451);
981            type_text(engine, 2, "ё");
982            let plan = apply_event(engine, &event(3, 2));
983            assert_eq!((plan.action, plan.disposition, plan.mark_len), (2, 0, 1));
984
985            let mut skipped = 77;
986            assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), STATE);
987            assert_eq!(skipped, 77);
988            let mut removed = "ёж".as_bytes().to_vec();
989            removed[0] = b'#';
990            let mut source = b"keep\nbad/*\n/future\n\xff\n".to_vec();
991            source.extend_from_slice(&removed);
992            assert_eq!(
993                kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
994                OK
995            );
996            assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
997            assert_eq!(skipped, 3);
998            assert_eq!((*engine).dictionaries[0].current().unwrap().len(), 1);
999            assert_eq!(
1000                kr_dictionary_skipped_lines(engine, 1, std::ptr::null_mut()),
1001                NULL
1002            );
1003            assert_eq!(
1004                kr_dictionary_skipped_lines(std::ptr::null_mut(), 1, &mut skipped),
1005                NULL
1006            );
1007            assert_eq!(
1008                kr_dictionary_skipped_lines(engine, 3, &mut skipped),
1009                BAD_TAG
1010            );
1011            assert_eq!(kr_dictionary_skipped_lines(engine, 2, &mut skipped), STATE);
1012            assert_eq!(
1013                kr_set_dictionary_utf8(engine, 1, b"\0a".as_ptr(), 2),
1014                DICTIONARY_DATA
1015            );
1016            assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
1017            assert_eq!(skipped, 3);
1018            assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0), OK);
1019            assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
1020            assert_eq!(skipped, 0);
1021
1022            assert_eq!(
1023                with_engine(engine, |_| panic!("synthetic keyboard containment test")),
1024                POISONED
1025            );
1026            assert_eq!(kr_set_keyboard(engine, 0), POISONED);
1027            assert_eq!(
1028                kr_dictionary_skipped_lines(engine, 1, &mut skipped),
1029                POISONED
1030            );
1031            kr_engine_free(engine);
1032        }
1033    }
1034
1035    // MODEL corrects automatically only with both dictionaries but converts manually without
1036    // them. Publishing a dictionary while a boundary mark is owned keeps its receipt. Setting the
1037    // same policy again keeps the English history that protects `yfv`, and a real change clears
1038    // it, so `yfv` then becomes `нам`.
1039    #[test]
1040    fn model_policy_bridge_preserves_configuration_context_and_receipts() {
1041        // SAFETY: the test exclusively retains the opaque allocation; all text buffers and event
1042        // objects are readable/aligned for the complete serialized call and are never retained
1043        unsafe {
1044            let mut engine = std::ptr::null_mut();
1045            assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1046            assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1047            let plan = type_text(engine, 1, "cgbcjr ");
1048            assert_eq!(
1049                &plan.mark[..plan.mark_len as usize],
1050                "cgbcjr ".encode_utf16().collect::<Vec<_>>()
1051            );
1052            let manual = apply_event(
1053                engine,
1054                &NativeEvent {
1055                    role: 4,
1056                    mode: 1,
1057                    context: 0,
1058                    len: 0,
1059                    units: [0; 8],
1060                },
1061            );
1062            assert_eq!(
1063                &manual.mark[..manual.mark_len as usize],
1064                "список ".encode_utf16().collect::<Vec<_>>()
1065            );
1066            assert_eq!(kr_reset(engine), OK);
1067            assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0), OK);
1068            assert_eq!(kr_set_dictionary_utf8(engine, 2, std::ptr::null(), 0), OK);
1069            for (mode, raw, corrected) in [(1, "cgbcjr ", "список "), (2, "цщкдв ", "world ")]
1070            {
1071                assert_eq!(kr_reset(engine), OK);
1072                let plan = type_text(engine, mode, raw);
1073                assert_eq!(
1074                    &plan.mark[..plan.mark_len as usize],
1075                    corrected.encode_utf16().collect::<Vec<_>>()
1076                );
1077                let source = "cgbcjr\nцщкдв\n".as_bytes();
1078                assert_eq!(
1079                    kr_set_dictionary_utf8(engine, 1, source.as_ptr(), source.len() as u32),
1080                    OK
1081                );
1082                let reverse = apply_event(
1083                    engine,
1084                    &NativeEvent {
1085                        role: 5,
1086                        mode,
1087                        context: 0,
1088                        len: 0,
1089                        units: [0; 8],
1090                    },
1091                );
1092                assert_eq!(
1093                    &reverse.mark[..reverse.mark_len as usize],
1094                    raw.encode_utf16().collect::<Vec<_>>()
1095                );
1096                assert_eq!(kr_set_dictionary_utf8(engine, 1, std::ptr::null(), 0), OK);
1097            }
1098            assert_eq!(kr_reset(engine), OK);
1099            assert_eq!(kr_clear_dictionary(engine, 2), OK);
1100            let plan = type_text(engine, 2, "цщкдв ");
1101            assert_eq!(
1102                &plan.mark[..plan.mark_len as usize],
1103                "цщкдв ".encode_utf16().collect::<Vec<_>>()
1104            );
1105            assert_eq!(kr_reset(engine), OK);
1106            assert_eq!(kr_set_dictionary_utf8(engine, 2, std::ptr::null(), 0), OK);
1107            type_text(engine, 1, "hello world ");
1108            let event = NativeEvent {
1109                role: 1,
1110                mode: 1,
1111                context: 0,
1112                len: 1,
1113                units: [121; 8],
1114            };
1115            let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1116            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1117            let finish = out.assume_init_read();
1118            assert_eq!((finish.action, finish.disposition), (2, 2));
1119            assert_eq!(kr_commit(engine, finish.plan_id, 0), OK);
1120            assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1121            let preserved = type_text(engine, 1, "yfv ");
1122            assert_eq!(
1123                &preserved.mark[..preserved.mark_len as usize],
1124                "yfv ".encode_utf16().collect::<Vec<_>>()
1125            );
1126            assert_eq!(kr_reset(engine), OK);
1127            type_text(engine, 1, "hello world ");
1128            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1129            assert_eq!(kr_commit(engine, out.assume_init_read().plan_id, 0), OK);
1130            assert_eq!(kr_set_automatic_policy(engine, 0), OK);
1131            assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1132            let neutral = type_text(engine, 1, "yfv ");
1133            assert_eq!(
1134                &neutral.mark[..neutral.mark_len as usize],
1135                "нам ".encode_utf16().collect::<Vec<_>>()
1136            );
1137            assert_eq!(kr_reset(engine), OK);
1138            assert_eq!(kr_set_automatic_policy(engine, 0), OK);
1139            let disabled = type_text(engine, 1, "cgbcjr ");
1140            assert_eq!(
1141                &disabled.mark[..disabled.mark_len as usize],
1142                "cgbcjr ".encode_utf16().collect::<Vec<_>>()
1143            );
1144            kr_engine_free(engine);
1145        }
1146    }
1147
1148    // Reset makes an outstanding plan STALE, so a late acknowledgement cannot advance a session
1149    // the adapter has already invalidated
1150    #[test]
1151    fn abi_null_version_bounds_stale_and_poison_contracts() {
1152        // SAFETY: all non-null pointers refer to live distinct local objects; the
1153        // handle is freed once after the final call. No native callbacks occur.
1154        unsafe {
1155            let mut engine = std::ptr::null_mut();
1156            assert_eq!(kr_engine_new(ABI + 1, &mut engine), VERSION);
1157            assert!(engine.is_null());
1158            assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1159            assert_eq!(kr_reset(std::ptr::null_mut()), NULL);
1160            let mut event = NativeEvent {
1161                role: 1,
1162                mode: 1,
1163                context: 0,
1164                len: 9,
1165                units: [97; 8],
1166            };
1167            let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1168            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), BOUNDS);
1169            event.len = 1;
1170            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1171            let plan = out.assume_init();
1172            assert_eq!(plan.mark[..plan.mark_len as usize], [97]);
1173            assert_eq!(kr_reset(engine), OK);
1174            assert_eq!(kr_commit(engine, plan.plan_id, 0), STALE);
1175            assert_eq!(
1176                with_engine(engine, |_| panic!("synthetic containment test")),
1177                POISONED
1178            );
1179            assert_eq!(kr_reset(engine), POISONED);
1180            kr_engine_free(engine);
1181            kr_engine_free(std::ptr::null_mut());
1182        }
1183    }
1184
1185    // An unknown outcome on a reversal and a refusal on the Backspace that empties a word both
1186    // stop planning until reset; continuing would act on a composition the engine cannot know
1187    #[test]
1188    fn copied_plans_manual_boundary_reverse_and_unknown_effect() {
1189        // SAFETY: local C objects are live, aligned and distinct; the opaque
1190        // allocation is accessed serially and freed once after all calls
1191        unsafe {
1192            let mut engine = std::ptr::null_mut();
1193            assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1194            assert_eq!(kr_set_automatic_policy(engine, 3), BAD_TAG);
1195            assert_eq!(kr_set_automatic_policy(engine, 1), OK);
1196            let mut event = NativeEvent {
1197                role: 1,
1198                mode: 1,
1199                context: 0,
1200                len: 1,
1201                units: [0; 8],
1202            };
1203            let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1204            for unit in "ghbdtn".encode_utf16().chain([32]) {
1205                event.units[0] = unit;
1206                assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1207                let p = out.assume_init_read();
1208                assert_eq!(p.action, 1);
1209                if unit == 32 {
1210                    assert_eq!(
1211                        &p.mark[..p.mark_len as usize],
1212                        "привет ".encode_utf16().collect::<Vec<_>>()
1213                    );
1214                }
1215                assert_eq!(kr_commit(engine, p.plan_id, 0), OK);
1216            }
1217            event.role = 5;
1218            event.len = 0;
1219            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1220            let reversed = out.assume_init_read();
1221            assert_eq!(
1222                &reversed.mark[..reversed.mark_len as usize],
1223                "ghbdtn ".encode_utf16().collect::<Vec<_>>()
1224            );
1225            assert_eq!(kr_commit(engine, reversed.plan_id, 2), OK);
1226            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), STATE);
1227            assert_eq!(kr_reset(engine), OK);
1228            event.role = 1;
1229            event.len = 1;
1230            event.units[0] = 120;
1231            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1232            assert_eq!(kr_commit(engine, out.assume_init_read().plan_id, 0), OK);
1233            event.role = 2;
1234            event.len = 0;
1235            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
1236            let empty = out.assume_init_read();
1237            assert_eq!((empty.action, empty.mark_len), (1, 0));
1238            assert_eq!(kr_commit(engine, empty.plan_id, 1), OK);
1239            assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), STATE);
1240            kr_engine_free(engine);
1241        }
1242    }
1243
1244    // Every malformed field is rejected before planning, so no token exists to acknowledge
1245    #[test]
1246    fn invalid_native_tags_never_produce_a_usable_plan() {
1247        // SAFETY: all pointers are either explicitly null or live local objects;
1248        // the handle has one owner and no callback can reenter these tests
1249        unsafe {
1250            assert_eq!(kr_engine_new(ABI, std::ptr::null_mut()), NULL);
1251            let mut engine = std::ptr::null_mut();
1252            assert_eq!(kr_engine_new(ABI, &mut engine), OK);
1253            let mut out = std::mem::MaybeUninit::<NativePlan>::uninit();
1254            let mut event = NativeEvent {
1255                role: 1,
1256                mode: 1,
1257                context: 0,
1258                len: 1,
1259                units: [97; 8],
1260            };
1261            assert_eq!(
1262                kr_plan_event(engine, std::ptr::null(), out.as_mut_ptr()),
1263                NULL
1264            );
1265            assert_eq!(kr_plan_event(engine, &event, std::ptr::null_mut()), NULL);
1266            for (role, mode, context, len) in [
1267                (0, 1, 0, 0),
1268                (7, 1, 0, 0),
1269                (1, 0, 0, 1),
1270                (1, 1, 2, 1),
1271                (4, 1, 0, 1),
1272            ] {
1273                event.role = role;
1274                event.mode = mode;
1275                event.context = context;
1276                event.len = len;
1277                assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), BAD_TAG);
1278            }
1279            assert_eq!(kr_commit(engine, 1, 3), BAD_TAG);
1280            kr_engine_free(engine);
1281        }
1282    }
1283}