Skip to main content

fprint_core/
lib.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! # fprint-core
6//!
7//! The GObject-free core of an fprintd-compatible fingerprint stack: the domain model
8//! (fingers, device capabilities, prints/templates) plus the [`Backend`]/[`Device`] traits
9//! that a concrete backend implements.
10//!
11//! It contains no device drivers, USB code, or matching algorithms; those live in downstream
12//! crates:
13//!
14//! * `fprint-backend-libfprint` implements [`Backend`] by wrapping the C libfprint, and
15//! * `fprint-backend-native` implements the same trait with pure-Rust drivers + transport.
16//!
17//! The fprintd-compatible daemon (`fprintd`) depends only on these traits, so the backend
18//! can be swapped without touching the daemon.
19//!
20//! Enum *values* that cross a wire boundary (the FP3 template format, fprintd's per-finger
21//! file names) mirror libfprint's C enums exactly — see [`Finger`] — so the stack stays
22//! interoperable with existing `/var/lib/fprint` stores. The device-capability enums
23//! ([`DeviceFeature`], [`ScanType`]) mirror their libfprint counterparts too. The wire
24//! *vocabularies* themselves (the `net.reactivated.Fprint` finger-name and status strings)
25//! live at the daemon edge, not here (`ARCHITECTURE.md` principle 3).
26//!
27//! # Implementing a backend
28//!
29//! A backend is a type that hands out [`Device`]s. Both traits are native `async fn` traits with
30//! no `dyn` and no runtime: a backend is a struct and two impl blocks. The example below is
31//! compiled as a doctest, depending on nothing but `std`.
32//!
33//! ```
34//! # use std::future::Future;
35//! # use std::sync::Arc;
36//! # use std::task::{Context, Poll, Wake, Waker};
37//! # struct Noop;
38//! # impl Wake for Noop {
39//! #     fn wake(self: Arc<Self>) {}
40//! # }
41//! # /// Poll a future to completion on this thread; the futures below never pend.
42//! # fn block_on<F: Future>(future: F) -> F::Output {
43//! #     let mut future = Box::pin(future);
44//! #     let waker = Waker::from(Arc::new(Noop));
45//! #     let mut cx = Context::from_waker(&waker);
46//! #     loop {
47//! #         match future.as_mut().poll(&mut cx) {
48//! #             Poll::Ready(value) => return value,
49//! #             Poll::Pending => unreachable!("this example never pends"),
50//! #         }
51//! #     }
52//! # }
53//! use fprint_core::{
54//!     Backend, Device, DeviceFeature, DeviceId, DeviceInfo, DriverId, EnrollProgress, Error,
55//!     Finger, FingerStatus, IdentifyOutcome, Print, Result, ScanType, Template, VerifyOutcome,
56//! };
57//!
58//! /// A match-on-chip reader holding one template.
59//! struct Demo {
60//!     info: DeviceInfo,
61//!     stored: Option<Print>,
62//! }
63//!
64//! impl Device for Demo {
65//!     fn info(&self) -> &DeviceInfo {
66//!         &self.info
67//!     }
68//!
69//!     async fn enroll<F: FnMut(EnrollProgress)>(
70//!         &mut self,
71//!         mut print: Print,
72//!         mut on_progress: F,
73//!     ) -> Result<Print> {
74//!         let total_stages = self.info.enroll_stages;
75//!         for completed_stages in 1..=total_stages {
76//!             on_progress(EnrollProgress::new(completed_stages, total_stages));
77//!         }
78//!         print.template = Template::Raw(b"on-sensor handle".to_vec());
79//!         print.driver = Some(self.info.driver.clone());
80//!         print.device_stored = true;
81//!         self.stored = Some(print.clone());
82//!         Ok(print)
83//!     }
84//!
85//!     async fn verify_with_status<F: FnMut(FingerStatus)>(
86//!         &mut self,
87//!         enrolled: &Print,
88//!         mut on_status: F,
89//!     ) -> Result<VerifyOutcome> {
90//!         on_status(FingerStatus::PRESENT); // report the finger the desktop prompts for
91//!         Ok(VerifyOutcome::new(self.stored.as_ref() == Some(enrolled), None))
92//!     }
93//!
94//!     // The remaining operations are stubs here; a real backend talks to the sensor.
95//! #   async fn open(&mut self) -> Result<()> { Ok(()) }
96//! #   async fn close(&mut self) -> Result<()> { Ok(()) }
97//! #   async fn identify_with_status<F: FnMut(FingerStatus)>(&mut self, _gallery: &[Print], _on_status: F) -> Result<IdentifyOutcome> {
98//! #       Err(Error::NotSupported)
99//! #   }
100//! #   async fn list_prints(&mut self) -> Result<Vec<Print>> {
101//! #       Ok(self.stored.clone().into_iter().collect())
102//! #   }
103//! #   async fn delete_print(&mut self, _print: &Print) -> Result<()> { self.stored = None; Ok(()) }
104//! #   async fn clear_storage(&mut self) -> Result<()> { self.stored = None; Ok(()) }
105//! #   async fn suspend(&mut self) -> Result<()> { Ok(()) }
106//! #   async fn resume(&mut self) -> Result<()> { Ok(()) }
107//! }
108//!
109//! struct DemoBackend;
110//!
111//! impl Backend for DemoBackend {
112//!     type Device = Demo;
113//!
114//!     async fn enumerate(&self) -> Result<Vec<Demo>> {
115//!         Ok(vec![Demo {
116//!             info: DeviceInfo::new(
117//!                 DeviceId::new("demo-0"),
118//!                 DriverId::new("demo"),
119//!                 "Demo Reader",
120//!                 ScanType::Press,
121//!                 DeviceFeature::VERIFY | DeviceFeature::STORAGE,
122//!                 3,
123//!             ),
124//!             stored: None,
125//!         }])
126//!     }
127//!
128//!     async fn open(&self, id: &DeviceId) -> Result<Demo> {
129//!         self.enumerate()
130//!             .await?
131//!             .into_iter()
132//!             .find(|d| &d.info().id == id)
133//!             .ok_or(Error::NotFound)
134//!     }
135//! }
136//!
137//! # fn main() {
138//! block_on(async {
139//!     let mut device = DemoBackend.open(&DeviceId::new("demo-0")).await.unwrap();
140//!     device.open().await.unwrap();
141//!     assert!(device.has_feature(DeviceFeature::STORAGE));
142//!     assert!(device.info().features.is_match_on_chip());
143//!
144//!     let mut seen = Vec::new();
145//!     let print = device
146//!         .enroll(Print::new_for_enroll(Finger::RightIndex), |p| seen.push(p.completed_stages))
147//!         .await
148//!         .unwrap();
149//!
150//!     assert_eq!(seen, [1, 2, 3]);
151//!     assert_eq!(print.finger, Some(Finger::RightIndex));
152//!     assert!(print.is_compatible_with_driver(&DriverId::new("demo")));
153//!     assert!(device.verify(&print).await.unwrap().matched);
154//! });
155//! # }
156//! ```
157
158#![forbid(unsafe_code)]
159#![deny(missing_docs)]
160
161mod device;
162mod error;
163mod feature;
164mod finger;
165mod print;
166
167pub use device::{
168    Backend, Device, DeviceId, DeviceInfo, DriverId, EnrollProgress, IdentifyOutcome, VerifyOutcome,
169};
170pub use error::{Error, Result, RetryReason};
171pub use feature::{DeviceFeature, FingerStatus, ScanType, Temperature};
172pub use finger::{Finger, InvalidFinger};
173pub use print::{EnrollDate, InvalidEnrollDate, Minutia, Print, PrintBuilder, Template};
174
175/// The names a backend or client reaches for most: the traits, the model, and the result types.
176///
177/// ```
178/// use fprint_core::prelude::*;
179/// ```
180pub mod prelude {
181    pub use crate::{
182        Backend, Device, DeviceFeature, DeviceId, DeviceInfo, DriverId, EnrollProgress, Error,
183        Finger, FingerStatus, IdentifyOutcome, Minutia, Print, PrintBuilder, Result, RetryReason,
184        ScanType, Template, VerifyOutcome,
185    };
186}