diff src/items.rs @ 59:3f4a77aa88be

Fix string copyting and improve error situation. This change is too big and includes several things: - Fix copying strings from PAM by fixing const and mut on pam funcs. - Improve error enums by simplifying conversions and removing unnecessary and ambiguous "success" variants. - Make a bunch of casts nicer. - Assorted other cleanup.
author Paul Fisher <paul@pfish.zone>
date Wed, 21 May 2025 00:27:18 -0400
parents daa2cde64601
children 05cc2c27334f
line wrap: on
line diff
--- a/src/items.rs	Mon May 05 00:16:04 2025 -0400
+++ b/src/items.rs	Wed May 21 00:27:18 2025 -0400
@@ -1,12 +1,12 @@
-use num_derive::{FromPrimitive, ToPrimitive};
-use num_traits::{FromPrimitive, ToPrimitive};
+use crate::constants::InvalidEnum;
+use num_derive::FromPrimitive;
+use num_traits::FromPrimitive;
 use std::ffi::{c_int, CStr};
 
-#[derive(FromPrimitive, ToPrimitive)]
+#[derive(FromPrimitive)]
 #[repr(i32)]
+#[non_exhaustive] // because C could give us anything!
 pub enum ItemType {
-    /// Unset. This should never be used.
-    Unset = 0,
     /// The service name
     Service = 1,
     /// The user name
@@ -35,19 +35,20 @@
     AuthTokType = 13,
 }
 
-impl From<c_int> for ItemType {
-    fn from(value: c_int) -> Self {
-        Self::from_i32(value).unwrap_or(Self::Unset)
+impl TryFrom<c_int> for ItemType {
+    type Error = InvalidEnum<Self>;
+    fn try_from(value: c_int) -> Result<Self, Self::Error> {
+        Self::from_i32(value).ok_or(value.into())
     }
 }
 
 impl From<ItemType> for c_int {
     fn from(val: ItemType) -> Self {
-        val.to_i32().unwrap_or(0)
+        val as Self
     }
 }
 
-// A type that can be requested by `pam::Handle::get_item`.
+/// A type that can be requested by [crate::Handle::get_item].
 pub trait Item {
     /// The `repr(C)` type that is returned (by pointer) by the underlying `pam_get_item` function.
     type Raw;
@@ -101,7 +102,7 @@
 cstr_item!(User);
 cstr_item!(Tty);
 cstr_item!(RemoteHost);
-// Conv
+// Conversation is not included here since it's special.
 cstr_item!(AuthTok);
 cstr_item!(OldAuthTok);
 cstr_item!(RemoteUser);