fprint-core 0.1.0

Modern, GObject-free Rust core for fingerprint readers: device/print domain model and backend traits, shared by a libfprint (FFI) shim backend and native Rust drivers.
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
// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! The core seam: [`Backend`] and [`Device`] traits.
//!
//! ## Dispatch model
//!
//! These traits use **native `async fn` in trait** and **static dispatch**. `fprint-core`
//! introduces neither `dyn` nor an enum of backends: either would make the core depend on
//! its implementors and invert the dependency arrows. Runtime backend heterogeneity (e.g.
//! one device served by native Rust, another by the libfprint shim) is expressed *above*
//! the core by a `CompositeBackend` whose `Device` associated type is an enum over the
//! concrete backends — the only crate allowed to know all of them. See `ARCHITECTURE.md`.
//!
//! Cancellation is Rust-native: **dropping the returned future cancels the operation**.
//! Backends release the sensor in their own `Drop`; there is no `GCancellable`-style token.
//!
//! Every operation takes `&mut self`, so the borrow checker forbids concurrent
//! enroll/verify on one device — libfprint's single-in-flight-operation contract enforced
//! by the type system rather than runtime checks.
//!
//! The pair of doctests below is the proof, and **only the pair proves anything**: a lone
//! `compile_fail` passes for any reason at all, including a typo. These two differ in exactly one
//! thing — whether the two futures are alive at once — so the failure is attributable to the
//! overlap. Both are generic over `D: Device`, so the borrow checker rejects at the trait bound
//! and no implementor is needed.
//!
//! The `E0499` on the negative states the intended cause; stable rustdoc does not verify it, so
//! attribution rests on the control, not on the code.
//!
//! The positive control — the two operations in sequence compile:
//! ```
//! async fn sequential<D: fprint_core::Device>(dev: &mut D, p: &fprint_core::Print) {
//!     let _ = dev.enroll(p.clone(), |_| {}).await;
//!     let _ = dev.verify(p).await;
//! }
//! ```
//!
//! The negative — the same two operations overlapping do not:
//! ```compile_fail,E0499
//! fn concurrent<D: fprint_core::Device>(dev: &mut D, p: &fprint_core::Print) {
//!     let enrolling = dev.enroll(p.clone(), |_| {});
//!     let verifying = dev.verify(p);
//!     let _ = (enrolling, verifying);
//! }
//! ```

use crate::error::RetryReason;
use crate::{DeviceFeature, Error, FingerStatus, Print, Result, ScanType, Temperature};

/// Stable identifier for a physical reader (opaque; assigned by the backend).
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct DeviceId(String);

impl DeviceId {
    /// Wrap a backend-assigned identifier.
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// The identifier as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl core::fmt::Display for DeviceId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<&str> for DeviceId {
    fn from(id: &str) -> Self {
        Self::new(id)
    }
}

impl From<String> for DeviceId {
    fn from(id: String) -> Self {
        Self::new(id)
    }
}

/// Identifier of the driver a template is bound to (e.g. `"goodixmoc"`). Templates are
/// driver-specific, so this is its own type rather than a bare `String`.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct DriverId(String);

impl DriverId {
    /// Wrap a driver identifier.
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// The identifier as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl core::fmt::Display for DriverId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<&str> for DriverId {
    fn from(id: &str) -> Self {
        Self::new(id)
    }
}

impl From<String> for DriverId {
    fn from(id: String) -> Self {
        Self::new(id)
    }
}

/// Static description of a device, known once it is discovered.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct DeviceInfo {
    /// Backend-assigned identity of this reader.
    pub id: DeviceId,
    /// Driver id, which templates are bound to.
    pub driver: DriverId,
    /// Human-readable model name.
    pub name: String,
    /// How the finger is presented to this sensor.
    pub scan_type: ScanType,
    /// Everything this device advertises it can do; query it via [`Device::has_feature`].
    pub features: DeviceFeature,
    /// Number of finger presentations a full enrollment needs.
    pub enroll_stages: u32,
}

impl DeviceInfo {
    /// Describe a device from its discovered static metadata.
    ///
    /// The sensor's *thermal* state is deliberately not here: it changes as the device runs, so it
    /// is a live reading via [`Device::temperature`], not a field frozen into this static shape.
    #[must_use]
    pub fn new(
        id: DeviceId,
        driver: DriverId,
        name: impl Into<String>,
        scan_type: ScanType,
        features: DeviceFeature,
        enroll_stages: u32,
    ) -> Self {
        DeviceInfo {
            id,
            driver,
            name: name.into(),
            scan_type,
            features,
            enroll_stages,
        }
    }
}

/// Progress report delivered during [`Device::enroll`], once per capture attempt.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct EnrollProgress {
    /// Stages completed so far (`0..=total_stages`).
    pub completed_stages: u32,
    /// Stages a full enrollment needs, mirroring [`DeviceInfo::enroll_stages`].
    pub total_stages: u32,
    /// `Some` when this capture failed and the user should present the finger again;
    /// the stage count did not advance.
    pub retry: Option<RetryReason>,
    /// Live finger-presence status accompanying this report ([`FingerStatus::NONE`] when the
    /// backend reports none).
    pub finger_status: FingerStatus,
}

impl EnrollProgress {
    /// A report of `completed_stages` of `total_stages`, with no retry and no finger status.
    #[must_use]
    pub fn new(completed_stages: u32, total_stages: u32) -> Self {
        EnrollProgress {
            completed_stages,
            total_stages,
            retry: None,
            finger_status: FingerStatus::NONE,
        }
    }

    /// Mark this report as a retry with reason `r`.
    #[must_use]
    pub fn with_retry(mut self, r: RetryReason) -> Self {
        self.retry = Some(r);
        self
    }

    /// Attach the live finger-presence status.
    #[must_use]
    pub fn with_finger_status(mut self, s: FingerStatus) -> Self {
        self.finger_status = s;
        self
    }
}

/// Result of a 1:1 [`Device::verify`].
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct VerifyOutcome {
    /// Whether the scan matched the enrolled print.
    pub matched: bool,
    /// The freshly scanned print, when the backend surfaces it (host-side sensors do; many
    /// match-on-chip sensors do not).
    pub scanned: Option<Print>,
}

impl VerifyOutcome {
    /// A verify result: `matched` and the optional freshly `scanned` print.
    #[must_use]
    pub fn new(matched: bool, scanned: Option<Print>) -> Self {
        VerifyOutcome { matched, scanned }
    }
}

/// Result of a 1:N [`Device::identify`].
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct IdentifyOutcome {
    /// Index into the gallery passed to `identify`, or `None` for no match.
    pub match_index: Option<usize>,
    /// The freshly scanned print, on the same terms as [`VerifyOutcome::scanned`].
    pub scanned: Option<Print>,
}

impl IdentifyOutcome {
    /// An identify result: the gallery `match_index` (or `None`) and the optional freshly
    /// `scanned` print.
    #[must_use]
    pub fn new(match_index: Option<usize>, scanned: Option<Print>) -> Self {
        IdentifyOutcome {
            match_index,
            scanned,
        }
    }
}

/// A physical fingerprint reader.
///
/// Implemented by each backend (the libfprint shim, native Rust drivers). Consumers hold
/// a concrete `Device` (static dispatch); the fprintd-compatible daemon is generic over
/// its [`Backend`].
///
/// `async fn` in a public trait is intentional (see the module docs), so the
/// `async_fn_in_trait` lint — which warns that callers cannot add `+ Send` bounds — is
/// expected here and only here.
#[expect(async_fn_in_trait)]
pub trait Device {
    /// Static metadata (available before and after `open`).
    fn info(&self) -> &DeviceInfo;

    /// Convenience: does this device advertise `feature`?
    fn has_feature(&self, feature: DeviceFeature) -> bool {
        self.info().features.contains(feature)
    }

    /// The sensor's current thermal state, or `None` when the device does not report one.
    ///
    /// Unlike [`info`](Device::info), this is a **live** reading: a sensor warms as it runs and
    /// cools when idle, so a caller driving a long capture loop re-reads it rather than caching a
    /// value. The default is `None`; a backend whose hardware reports temperature overrides it.
    fn temperature(&self) -> Option<Temperature> {
        None
    }

    /// Open the device for use. Must be called before any operation below.
    async fn open(&mut self) -> Result<()>;

    /// Close the device, releasing the sensor.
    async fn close(&mut self) -> Result<()>;

    /// Enroll a finger into `print` (a blank [`Print::new_for_enroll`] tagged with the target
    /// finger), reporting each capture via `on_progress`. Returns the completed print.
    ///
    /// `on_progress` is a generic `FnMut`, not a trait object: progress is pushed to the
    /// caller, and static dispatch keeps the core free of `dyn`.
    async fn enroll<F: FnMut(EnrollProgress)>(
        &mut self,
        print: Print,
        on_progress: F,
    ) -> Result<Print>;

    /// Verify a single scan against one `enrolled` print (1:1), reporting live finger-presence
    /// through `on_status` as the sensor sees a finger arrive and leave.
    ///
    /// `on_status` is the verify-side counterpart of [`enroll`](Device::enroll)'s progress callback:
    /// static dispatch, pushed to the caller, so the core stays `dyn`-free. A backend with no live
    /// finger reporting simply never calls it.
    async fn verify_with_status<F: FnMut(FingerStatus)>(
        &mut self,
        enrolled: &Print,
        on_status: F,
    ) -> Result<VerifyOutcome>;

    /// Verify a single scan against one `enrolled` print (1:1).
    ///
    /// The status-free convenience form of [`verify_with_status`](Device::verify_with_status), for
    /// callers that do not drive finger-presence UI prompts.
    async fn verify(&mut self, enrolled: &Print) -> Result<VerifyOutcome> {
        self.verify_with_status(enrolled, |_| {}).await
    }

    /// Identify a single scan against a `gallery` of prints (1:N), reporting live finger-presence
    /// through `on_status`.
    async fn identify_with_status<F: FnMut(FingerStatus)>(
        &mut self,
        gallery: &[Print],
        on_status: F,
    ) -> Result<IdentifyOutcome>;

    /// Identify a single scan against a `gallery` of prints (1:N).
    ///
    /// The status-free convenience form of [`identify_with_status`](Device::identify_with_status).
    async fn identify(&mut self, gallery: &[Print]) -> Result<IdentifyOutcome> {
        self.identify_with_status(gallery, |_| {}).await
    }

    /// List prints stored on the device (match-on-chip devices with `STORAGE`).
    ///
    /// A device that keeps no on-sensor storage (a host-image sensor) inherits the default, which
    /// reports [`Error::NotSupported`] — the absence of storage is spoken by *not* overriding this,
    /// its presence by advertising [`DeviceFeature::STORAGE`] and overriding it.
    async fn list_prints(&mut self) -> Result<Vec<Print>> {
        Err(Error::NotSupported)
    }

    /// Delete one print from on-device storage.
    ///
    /// Defaults to [`Error::NotSupported`] for a device without on-sensor storage; see
    /// [`list_prints`](Device::list_prints).
    async fn delete_print(&mut self, print: &Print) -> Result<()> {
        let _ = print;
        Err(Error::NotSupported)
    }

    /// Erase all templates from on-device storage.
    ///
    /// Defaults to [`Error::NotSupported`] for a device without on-sensor storage; see
    /// [`list_prints`](Device::list_prints).
    async fn clear_storage(&mut self) -> Result<()> {
        Err(Error::NotSupported)
    }

    /// Prepare for system suspend (the sensor may need to stop an active wait).
    async fn suspend(&mut self) -> Result<()>;

    /// Resume after system suspend.
    async fn resume(&mut self) -> Result<()>;
}

/// A source of [`Device`]s — the entry point, analogous to libfprint's `FpContext`.
///
/// The associated `Device` type keeps this on static dispatch.
#[expect(async_fn_in_trait)]
pub trait Backend {
    /// The concrete reader type this backend hands out.
    type Device: Device;

    /// Enumerate the readers currently attached.
    async fn enumerate(&self) -> Result<Vec<Self::Device>>;

    /// Open a specific reader by id (convenience over `enumerate` + find).
    async fn open(&self, id: &DeviceId) -> Result<Self::Device>;
}

#[cfg(test)]
mod tests {
    use super::{Device, DeviceId, DeviceInfo, DriverId, EnrollProgress, IdentifyOutcome};
    use crate::feature::FLAGS;
    use crate::{DeviceFeature, FingerStatus, Print, Result, ScanType, VerifyOutcome};

    /// Carries a [`DeviceInfo`] and nothing else. Only `info` is ever called: [`Device::has_feature`]
    /// is a default method over it, so the sensor operations need no bodies to test it.
    struct InfoOnly(DeviceInfo);

    impl Device for InfoOnly {
        fn info(&self) -> &DeviceInfo {
            &self.0
        }

        async fn open(&mut self) -> Result<()> {
            todo!("has_feature never opens the device")
        }
        async fn close(&mut self) -> Result<()> {
            todo!("has_feature never opens the device")
        }
        async fn enroll<F: FnMut(EnrollProgress)>(&mut self, _: Print, _: F) -> Result<Print> {
            todo!("has_feature never scans")
        }
        async fn verify_with_status<F: FnMut(FingerStatus)>(
            &mut self,
            _: &Print,
            _: F,
        ) -> Result<VerifyOutcome> {
            todo!("has_feature never scans")
        }
        async fn identify_with_status<F: FnMut(FingerStatus)>(
            &mut self,
            _: &[Print],
            _: F,
        ) -> Result<IdentifyOutcome> {
            todo!("has_feature never scans")
        }
        async fn suspend(&mut self) -> Result<()> {
            todo!("has_feature never suspends")
        }
        async fn resume(&mut self) -> Result<()> {
            todo!("has_feature never suspends")
        }
    }

    fn device_with(features: DeviceFeature) -> InfoOnly {
        InfoOnly(DeviceInfo::new(
            DeviceId::new("test-0"),
            DriverId::new("test"),
            "Test Reader",
            ScanType::Press,
            features,
            1,
        ))
    }

    /// **`has_feature` is `info().features.contains`, for every representable set and every defined
    /// flag** — the default body must not develop a rule of its own.
    ///
    /// The sets and the flags both come from [`crate::feature::FLAGS`], so an eleventh flag widens
    /// this test on its own rather than escaping it.
    #[test]
    fn has_feature_agrees_with_the_advertised_set() {
        let defined = DeviceFeature::from_bits_truncate(u32::MAX).bits();
        for bits in 0..=u32::from(defined) {
            let advertised = DeviceFeature::from_bits_truncate(bits);
            let device = device_with(advertised);
            for flag in
                core::iter::once(DeviceFeature::NONE).chain(FLAGS.into_iter().map(|(f, _)| f))
            {
                assert_eq!(
                    device.has_feature(flag),
                    advertised.contains(flag),
                    "{advertised:?}.has_feature({flag:?})"
                );
            }
        }
    }
}