Skip to main content

fprint_core/
feature.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Device capabilities and status — mirrors libfprint's `FpDeviceFeature`, `FpScanType`,
6//! `FpFingerStatusFlags`, and `FpTemperature`.
7
8/// Capability bit-flags, matching libfprint's `FpDeviceFeature` (`fp-device.h`).
9///
10/// The bit positions are load-bearing: `IDENTIFY = 1<<1` and `VERIFY = 1<<2` (note the
11/// order is *not* alphabetical in libfprint). `STORAGE` distinguishes match-on-chip (MOC)
12/// devices — which keep templates on the sensor — from host-side-storage devices.
13///
14/// Hand-rolled (no `bitflags` dependency) to keep `fprint-core` allocation- and dependency-free.
15#[derive(Clone, Copy, PartialEq, Eq, Default)]
16pub struct DeviceFeature(u16);
17
18impl DeviceFeature {
19    /// The empty set (`FP_DEVICE_FEATURE_NONE`). Every set contains it.
20    pub const NONE: DeviceFeature = DeviceFeature(0);
21    /// `FP_DEVICE_FEATURE_CAPTURE`: the device can return a raw image (`fp_device_capture`).
22    /// Image sensors have it; match-on-chip sensors normally do not.
23    pub const CAPTURE: DeviceFeature = DeviceFeature(1 << 0);
24    /// `FP_DEVICE_FEATURE_IDENTIFY`: the device can match one scan against a gallery
25    /// ([`Device::identify`](crate::Device::identify)).
26    pub const IDENTIFY: DeviceFeature = DeviceFeature(1 << 1);
27    /// `FP_DEVICE_FEATURE_VERIFY`: the device can match one scan against one print
28    /// ([`Device::verify`](crate::Device::verify)).
29    pub const VERIFY: DeviceFeature = DeviceFeature(1 << 2);
30    /// `FP_DEVICE_FEATURE_STORAGE`: the device keeps templates on the sensor, which marks it
31    /// match-on-chip — see [`DeviceFeature::is_match_on_chip`].
32    pub const STORAGE: DeviceFeature = DeviceFeature(1 << 3);
33    /// `FP_DEVICE_FEATURE_STORAGE_LIST`: on-sensor storage can be enumerated
34    /// ([`Device::list_prints`](crate::Device::list_prints)).
35    pub const STORAGE_LIST: DeviceFeature = DeviceFeature(1 << 4);
36    /// `FP_DEVICE_FEATURE_STORAGE_DELETE`: a single template can be removed from on-sensor
37    /// storage ([`Device::delete_print`](crate::Device::delete_print)).
38    pub const STORAGE_DELETE: DeviceFeature = DeviceFeature(1 << 5);
39    /// `FP_DEVICE_FEATURE_STORAGE_CLEAR`: on-sensor storage can be erased wholesale
40    /// ([`Device::clear_storage`](crate::Device::clear_storage)).
41    pub const STORAGE_CLEAR: DeviceFeature = DeviceFeature(1 << 6);
42    /// `FP_DEVICE_FEATURE_DUPLICATES_CHECK`: the device rejects enrolling a finger it already
43    /// holds, reporting [`Error::DataDuplicate`](crate::Error::DataDuplicate).
44    pub const DUPLICATES_CHECK: DeviceFeature = DeviceFeature(1 << 7);
45    /// `FP_DEVICE_FEATURE_ALWAYS_ON`: the sensor runs continuously rather than being powered up
46    /// per operation.
47    pub const ALWAYS_ON: DeviceFeature = DeviceFeature(1 << 8);
48    /// `FP_DEVICE_FEATURE_UPDATE_PRINT`: enrolling can extend an existing template with new scans
49    /// instead of replacing it.
50    pub const UPDATE_PRINT: DeviceFeature = DeviceFeature(1 << 9);
51
52    /// Raw bitmask (as returned by `fp_device_get_features`).
53    #[must_use]
54    pub const fn bits(self) -> u16 {
55        self.0
56    }
57
58    /// Build from a raw bitmask, keeping only defined bits.
59    ///
60    /// Takes a `u32` (libfprint's `FpDeviceFeature` is a 32-bit flags type) and masks to the
61    /// defined `0..=9` bits here, so callers never narrow before masking.
62    #[must_use]
63    pub const fn from_bits_truncate(bits: u32) -> DeviceFeature {
64        // 0..=9 are defined; mask off unknown/high bits.
65        DeviceFeature((bits & 0x03FF) as u16)
66    }
67
68    /// `fp_device_has_feature`: true iff every bit in `other` is set in `self`.
69    #[must_use]
70    pub const fn contains(self, other: DeviceFeature) -> bool {
71        self.0 & other.0 == other.0
72    }
73
74    /// Whether no flag is set (equal to [`DeviceFeature::NONE`]).
75    #[must_use]
76    pub const fn is_empty(self) -> bool {
77        self.0 == 0
78    }
79
80    /// Whether `self` and `other` share any flag.
81    #[must_use]
82    pub const fn intersects(self, other: DeviceFeature) -> bool {
83        self.0 & other.0 != 0
84    }
85
86    /// Whether this looks like a match-on-chip device (persistent on-sensor storage).
87    #[must_use]
88    pub const fn is_match_on_chip(self) -> bool {
89        self.contains(DeviceFeature::STORAGE)
90    }
91}
92
93/// Every defined flag with its libfprint name — the one registry the [`Debug`] rendering and the
94/// [`DeviceFeature::from_bits_truncate`] mask are both derived from, and the one list the tests
95/// across this crate quantify over.
96pub(crate) const FLAGS: [(DeviceFeature, &str); 10] = [
97    (DeviceFeature::CAPTURE, "CAPTURE"),
98    (DeviceFeature::IDENTIFY, "IDENTIFY"),
99    (DeviceFeature::VERIFY, "VERIFY"),
100    (DeviceFeature::STORAGE, "STORAGE"),
101    (DeviceFeature::STORAGE_LIST, "STORAGE_LIST"),
102    (DeviceFeature::STORAGE_DELETE, "STORAGE_DELETE"),
103    (DeviceFeature::STORAGE_CLEAR, "STORAGE_CLEAR"),
104    (DeviceFeature::DUPLICATES_CHECK, "DUPLICATES_CHECK"),
105    (DeviceFeature::ALWAYS_ON, "ALWAYS_ON"),
106    (DeviceFeature::UPDATE_PRINT, "UPDATE_PRINT"),
107];
108
109/// The union of every flag in [`FLAGS`].
110const fn defined_bits() -> u16 {
111    let mut acc = 0u16;
112    let mut i = 0;
113    while i < FLAGS.len() {
114        acc |= FLAGS[i].0.bits();
115        i += 1;
116    }
117    acc
118}
119
120/// **The truncation mask is exactly the defined flags.** An eleventh flag registered in [`FLAGS`]
121/// without widening the `0x03FF` literal in [`DeviceFeature::from_bits_truncate`] fails to compile
122/// here, rather than being silently masked off at runtime.
123const _: () = assert!(DeviceFeature::from_bits_truncate(u32::MAX).bits() == defined_bits());
124
125impl core::ops::BitOr for DeviceFeature {
126    type Output = DeviceFeature;
127    fn bitor(self, rhs: DeviceFeature) -> DeviceFeature {
128        DeviceFeature(self.0 | rhs.0)
129    }
130}
131
132impl core::ops::BitOrAssign for DeviceFeature {
133    fn bitor_assign(&mut self, rhs: DeviceFeature) {
134        self.0 |= rhs.0;
135    }
136}
137
138impl core::ops::BitAnd for DeviceFeature {
139    type Output = DeviceFeature;
140    /// Set intersection: the flags in both sets.
141    fn bitand(self, rhs: DeviceFeature) -> DeviceFeature {
142        DeviceFeature(self.0 & rhs.0)
143    }
144}
145
146impl core::ops::BitAndAssign for DeviceFeature {
147    fn bitand_assign(&mut self, rhs: DeviceFeature) {
148        self.0 &= rhs.0;
149    }
150}
151
152impl core::ops::Sub for DeviceFeature {
153    type Output = DeviceFeature;
154    /// Set difference: the flags in `self` that are not in `rhs` (`self & !rhs`).
155    fn sub(self, rhs: DeviceFeature) -> DeviceFeature {
156        DeviceFeature(self.0 & !rhs.0)
157    }
158}
159
160impl core::ops::SubAssign for DeviceFeature {
161    fn sub_assign(&mut self, rhs: DeviceFeature) {
162        self.0 &= !rhs.0;
163    }
164}
165
166impl core::ops::Not for DeviceFeature {
167    type Output = DeviceFeature;
168    /// Set complement **within the defined flags** — unknown/high bits never appear, so
169    /// `!!x == x` for every representable set.
170    fn not(self) -> DeviceFeature {
171        DeviceFeature(defined_bits() & !self.0)
172    }
173}
174
175impl core::fmt::Debug for DeviceFeature {
176    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
177        if self.0 == 0 {
178            return f.write_str("NONE");
179        }
180        let mut first = true;
181        for (flag, name) in FLAGS {
182            if self.contains(flag) {
183                if !first {
184                    f.write_str(" | ")?;
185                }
186                first = false;
187                f.write_str(name)?;
188            }
189        }
190        Ok(())
191    }
192}
193
194/// How a finger is presented to the sensor (`FpScanType`).
195///
196/// The `net.reactivated.Fprint` `scan-type` property string (`"swipe"`/`"press"`) is interop
197/// wire vocabulary and lives at the daemon edge, not here (`ARCHITECTURE.md` principle 3).
198///
199/// Deliberately exhaustive, unlike the other external-vocabulary mirrors in this module: the
200/// `scan-type` wire contract defines exactly these two values, the shim collapses any other
201/// `FpScanType` to `Swipe`, and the daemon maps the enum totally onto the wire string — so a
202/// `#[non_exhaustive]` here would only force a lossy fallback arm at that edge with nothing to carry.
203#[derive(Clone, Copy, PartialEq, Eq, Debug)]
204pub enum ScanType {
205    /// Finger is swiped across a line sensor.
206    Swipe,
207    /// Finger is pressed onto an area sensor.
208    Press,
209}
210
211/// Live finger-presence status (`FpFingerStatusFlags`), used to drive UI prompts.
212#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
213pub struct FingerStatus(u8);
214
215impl FingerStatus {
216    /// `FP_FINGER_STATUS_NONE`: no status information available. Every set contains it.
217    pub const NONE: FingerStatus = FingerStatus(0);
218    /// `FP_FINGER_STATUS_NEEDED`: the device is waiting for a finger on the sensor — the cue to
219    /// prompt the user.
220    pub const NEEDED: FingerStatus = FingerStatus(1 << 0);
221    /// `FP_FINGER_STATUS_PRESENT`: the device reports a finger on the sensor.
222    pub const PRESENT: FingerStatus = FingerStatus(1 << 1);
223
224    /// Raw bitmask (as carried by libfprint's `finger-status` property).
225    #[must_use]
226    pub const fn bits(self) -> u8 {
227        self.0
228    }
229
230    /// The defined flags, `NEEDED | PRESENT` — the mask the complement stays within.
231    const DEFINED_BITS: u8 = FingerStatus::NEEDED.0 | FingerStatus::PRESENT.0;
232
233    /// Build from a raw bitmask, keeping only the defined `NEEDED`/`PRESENT` bits.
234    #[must_use]
235    pub const fn from_bits_truncate(bits: u8) -> FingerStatus {
236        FingerStatus(bits & FingerStatus::DEFINED_BITS)
237    }
238
239    /// True iff every bit in `other` is set in `self`.
240    #[must_use]
241    pub const fn contains(self, other: FingerStatus) -> bool {
242        self.0 & other.0 == other.0
243    }
244
245    /// Whether no flag is set (equal to [`FingerStatus::NONE`]).
246    #[must_use]
247    pub const fn is_empty(self) -> bool {
248        self.0 == 0
249    }
250
251    /// Whether `self` and `other` share any flag.
252    #[must_use]
253    pub const fn intersects(self, other: FingerStatus) -> bool {
254        self.0 & other.0 != 0
255    }
256}
257
258impl core::ops::BitOr for FingerStatus {
259    type Output = FingerStatus;
260    fn bitor(self, rhs: FingerStatus) -> FingerStatus {
261        FingerStatus(self.0 | rhs.0)
262    }
263}
264
265impl core::ops::BitOrAssign for FingerStatus {
266    fn bitor_assign(&mut self, rhs: FingerStatus) {
267        self.0 |= rhs.0;
268    }
269}
270
271impl core::ops::BitAnd for FingerStatus {
272    type Output = FingerStatus;
273    /// Set intersection: the flags in both sets.
274    fn bitand(self, rhs: FingerStatus) -> FingerStatus {
275        FingerStatus(self.0 & rhs.0)
276    }
277}
278
279impl core::ops::BitAndAssign for FingerStatus {
280    fn bitand_assign(&mut self, rhs: FingerStatus) {
281        self.0 &= rhs.0;
282    }
283}
284
285impl core::ops::Sub for FingerStatus {
286    type Output = FingerStatus;
287    /// Set difference: the flags in `self` that are not in `rhs` (`self & !rhs`).
288    fn sub(self, rhs: FingerStatus) -> FingerStatus {
289        FingerStatus(self.0 & !rhs.0)
290    }
291}
292
293impl core::ops::SubAssign for FingerStatus {
294    fn sub_assign(&mut self, rhs: FingerStatus) {
295        self.0 &= !rhs.0;
296    }
297}
298
299impl core::ops::Not for FingerStatus {
300    type Output = FingerStatus;
301    /// Set complement **within the defined flags** (`NEEDED`/`PRESENT`), so `!!x == x`.
302    fn not(self) -> FingerStatus {
303        FingerStatus(FingerStatus::DEFINED_BITS & !self.0)
304    }
305}
306
307/// Sensor thermal state (`FpTemperature`); some sensors throttle when warm/hot.
308///
309/// `#[non_exhaustive]`: `FpTemperature` is an external vocabulary that could grow.
310#[derive(Clone, Copy, PartialEq, Eq, Debug)]
311#[non_exhaustive]
312pub enum Temperature {
313    /// `FP_TEMPERATURE_COLD`: the device can run indefinitely.
314    Cold,
315    /// `FP_TEMPERATURE_WARM`: the device can run for a limited time before it must cool.
316    Warm,
317    /// `FP_TEMPERATURE_HOT`: the device must cool down; operations are throttled or refused.
318    Hot,
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn feature_bits_match_libfprint() {
327        assert_eq!(DeviceFeature::CAPTURE.bits(), 1 << 0);
328        assert_eq!(DeviceFeature::IDENTIFY.bits(), 1 << 1);
329        assert_eq!(DeviceFeature::VERIFY.bits(), 1 << 2);
330        assert_eq!(DeviceFeature::UPDATE_PRINT.bits(), 1 << 9);
331    }
332
333    #[test]
334    fn contains_and_moc_detection() {
335        let moc = DeviceFeature::VERIFY
336            | DeviceFeature::IDENTIFY
337            | DeviceFeature::STORAGE
338            | DeviceFeature::STORAGE_LIST;
339        assert!(moc.contains(DeviceFeature::STORAGE));
340        assert!(moc.is_match_on_chip());
341        assert!(!DeviceFeature::CAPTURE.is_match_on_chip());
342    }
343
344    /// The defined flags, taken from the [`FLAGS`] registry rather than relisted: an eleventh flag
345    /// is quantified over by the properties below the moment it is registered.
346    const DEFINED: [DeviceFeature; FLAGS.len()] = {
347        let mut out = [DeviceFeature::NONE; FLAGS.len()];
348        let mut i = 0;
349        while i < FLAGS.len() {
350            out[i] = FLAGS[i].0;
351            i += 1;
352        }
353        out
354    };
355
356    /// **The mask keeps the defined bits and drops every other one**, checked over every `u16`
357    /// input plus the high halfword the `u32` parameter admits. Expected values come from
358    /// [`defined_bits`], not from a relisted `0x03FF`, so this pins truncation to the registry
359    /// rather than to the literal it is implemented with.
360    #[test]
361    fn from_bits_truncate_keeps_exactly_the_defined_bits() {
362        for b in 0..=u32::from(u16::MAX) {
363            let kept = DeviceFeature::from_bits_truncate(b).bits();
364            assert_eq!(
365                kept,
366                b as u16 & defined_bits(),
367                "from_bits_truncate({b:#06x})"
368            );
369        }
370        // Bits above the u16 the type stores must not wrap into it.
371        assert_eq!(DeviceFeature::from_bits_truncate(0x1_0000).bits(), 0);
372        assert_eq!(
373            DeviceFeature::from_bits_truncate(u32::MAX).bits(),
374            defined_bits()
375        );
376    }
377
378    /// `BitOr` is a set union: associative, commutative, with [`DeviceFeature::NONE`] as identity.
379    /// Checked over all 100 ordered pairs of the ten flags.
380    #[test]
381    fn bitor_is_associative_commutative_with_none_identity() {
382        for a in DEFINED {
383            assert_eq!(a | DeviceFeature::NONE, a, "identity for {a:?}");
384            for b in DEFINED {
385                assert_eq!(a | b, b | a, "commutativity for {a:?}, {b:?}");
386                for c in DEFINED {
387                    assert_eq!(
388                        (a | b) | c,
389                        a | (b | c),
390                        "associativity for {a:?}, {b:?}, {c:?}"
391                    );
392                }
393            }
394        }
395    }
396
397    /// Over every one of the 1024 representable sets: **`NONE` is contained in all of them**, a set
398    /// contains each flag it was built from, and `is_match_on_chip` is exactly `contains(STORAGE)`.
399    #[test]
400    fn contains_none_always_and_moc_is_exactly_storage() {
401        for bits in 0..=u32::from(defined_bits()) {
402            let set = DeviceFeature::from_bits_truncate(bits);
403            assert!(
404                set.contains(DeviceFeature::NONE),
405                "{set:?} must contain NONE"
406            );
407            assert!(set.contains(set), "{set:?} must contain itself");
408            assert_eq!(
409                set.is_match_on_chip(),
410                set.contains(DeviceFeature::STORAGE),
411                "{set:?}"
412            );
413            for flag in DEFINED {
414                assert_eq!(
415                    set.contains(flag),
416                    bits & u32::from(flag.bits()) != 0,
417                    "{set:?}.contains({flag:?})"
418                );
419                assert!(
420                    (set | flag).contains(flag),
421                    "{set:?} | {flag:?} must contain {flag:?}"
422                );
423            }
424        }
425    }
426
427    /// The intersection / difference / complement operators obey the set laws, over every one of
428    /// the 1024 representable `DeviceFeature` sets (and, for the binary ops, all pairs).
429    #[test]
430    fn bitand_sub_not_obey_the_set_laws() {
431        let all = DeviceFeature::from_bits_truncate(u32::from(defined_bits()));
432        for a_bits in 0..=defined_bits() {
433            let a = DeviceFeature::from_bits_truncate(u32::from(a_bits));
434
435            // Complement stays within the defined flags and is an involution.
436            assert!((a & !a).is_empty(), "a & !a must be empty for {a:?}");
437            assert_eq!(a | !a, all, "a | !a must be every defined flag for {a:?}");
438            assert_eq!(!!a, a, "double complement is identity for {a:?}");
439            assert_eq!(a.is_empty(), a == DeviceFeature::NONE, "is_empty for {a:?}");
440
441            for b_bits in 0..=defined_bits() {
442                let b = DeviceFeature::from_bits_truncate(u32::from(b_bits));
443
444                assert_eq!(a & b, b & a, "intersection commutes for {a:?}, {b:?}");
445                assert_eq!(
446                    a.intersects(b),
447                    !(a & b).is_empty(),
448                    "intersects agrees with & for {a:?}, {b:?}"
449                );
450                // Difference clears exactly b's bits from a, and with the intersection partitions a.
451                let diff = a - b;
452                assert!(!diff.intersects(b), "a - b keeps no b bit for {a:?}, {b:?}");
453                assert_eq!(diff, a & !b, "a - b == a & !b for {a:?}, {b:?}");
454                assert_eq!(diff | (a & b), a, "difference and intersection partition a");
455
456                // The assigning forms agree with the operators.
457                let mut and_acc = a;
458                and_acc &= b;
459                assert_eq!(and_acc, a & b, "&= agrees for {a:?}, {b:?}");
460                let mut sub_acc = a;
461                sub_acc -= b;
462                assert_eq!(sub_acc, a - b, "-= agrees for {a:?}, {b:?}");
463            }
464        }
465    }
466
467    /// `BitOrAssign` agrees with `BitOr` over all 100 pairs — the two must not drift apart.
468    #[test]
469    fn bitor_assign_agrees_with_bitor() {
470        for a in DEFINED {
471            for b in DEFINED {
472                let mut acc = a;
473                acc |= b;
474                assert_eq!(acc, a | b, "{a:?} |= {b:?}");
475            }
476        }
477    }
478
479    /// [`FingerStatus`] gets the same treatment over its three values.
480    #[test]
481    fn finger_status_bitor_is_associative_commutative_with_none_identity() {
482        const THREE: [FingerStatus; 3] = [
483            FingerStatus::NONE,
484            FingerStatus::NEEDED,
485            FingerStatus::PRESENT,
486        ];
487        for a in THREE {
488            assert_eq!(a | FingerStatus::NONE, a, "identity for {a:?}");
489            assert!(a.contains(FingerStatus::NONE), "{a:?} must contain NONE");
490            for b in THREE {
491                assert_eq!(a | b, b | a, "commutativity for {a:?}, {b:?}");
492                assert!(
493                    (a | b).contains(a) && (a | b).contains(b),
494                    "union for {a:?}, {b:?}"
495                );
496                for c in THREE {
497                    assert_eq!(
498                        (a | b) | c,
499                        a | (b | c),
500                        "associativity for {a:?}, {b:?}, {c:?}"
501                    );
502                }
503            }
504        }
505        // The two flags are distinct bits, so a finger can be both needed and present.
506        let both = FingerStatus::NEEDED | FingerStatus::PRESENT;
507        assert_eq!(both.bits(), 0b11);
508        assert!(!FingerStatus::NEEDED.contains(FingerStatus::PRESENT));
509    }
510
511    /// [`FingerStatus`]'s intersection / difference / complement obey the same set laws.
512    #[test]
513    fn finger_status_bitand_sub_not_obey_the_set_laws() {
514        const THREE: [FingerStatus; 4] = [
515            FingerStatus::NONE,
516            FingerStatus::NEEDED,
517            FingerStatus::PRESENT,
518            FingerStatus(0b11),
519        ];
520        let all = FingerStatus::NEEDED | FingerStatus::PRESENT;
521        // Truncation keeps the defined bits and drops the rest, and round-trips every defined set.
522        assert_eq!(FingerStatus::from_bits_truncate(0xFF), all);
523        assert_eq!(FingerStatus::from_bits_truncate(0b100), FingerStatus::NONE);
524        for a in THREE {
525            assert_eq!(
526                FingerStatus::from_bits_truncate(a.bits()),
527                a,
528                "round-trip {a:?}"
529            );
530            assert!((a & !a).is_empty(), "a & !a must be empty for {a:?}");
531            assert_eq!(a | !a, all, "a | !a must be every defined flag for {a:?}");
532            assert_eq!(!!a, a, "double complement is identity for {a:?}");
533            assert_eq!(a.is_empty(), a == FingerStatus::NONE, "is_empty for {a:?}");
534            for b in THREE {
535                assert_eq!(a & b, b & a, "intersection commutes for {a:?}, {b:?}");
536                assert_eq!(
537                    a.intersects(b),
538                    !(a & b).is_empty(),
539                    "intersects for {a:?}, {b:?}"
540                );
541                assert_eq!(a - b, a & !b, "a - b == a & !b for {a:?}, {b:?}");
542                let mut acc = a;
543                acc &= b;
544                assert_eq!(acc, a & b, "&= agrees for {a:?}, {b:?}");
545                acc = a;
546                acc -= b;
547                assert_eq!(acc, a - b, "-= agrees for {a:?}, {b:?}");
548            }
549        }
550    }
551}