selinux/new_policy/
traits.rs1use super::NewPolicy;
6use super::error::{ParseError, SerializeError, ValidateError};
7use super::parser::PolicyCursor;
8
9pub trait Parse: Sized {
11 fn parse(cursor: &mut PolicyCursor<'_>) -> Result<Self, ParseError>;
12}
13
14pub trait Serialize {
16 fn serialize(&self, writer: &mut Vec<u8>) -> Result<(), SerializeError>;
17}
18
19pub trait Validate {
21 fn validate(&self, policy: &NewPolicy) -> Result<(), ValidateError>;
22}
23
24pub trait PolicyId: Copy + Clone + std::fmt::Debug + Eq + std::hash::Hash + PartialEq {
30 fn as_u32(&self) -> u32;
32
33 fn from_u32(value: u32) -> Option<Self>;
36}
37
38impl<T> Parse for T
40where
41 T: PolicyId,
42{
43 fn parse(cursor: &mut PolicyCursor<'_>) -> Result<Self, ParseError> {
44 let value = u32::parse(cursor)?;
45 T::from_u32(value).ok_or(ParseError::InvalidId { value })
46 }
47}
48
49impl<T> Serialize for T
50where
51 T: PolicyId,
52{
53 fn serialize(&self, writer: &mut Vec<u8>) -> Result<(), SerializeError> {
54 self.as_u32().serialize(writer)
55 }
56}
57
58pub trait HasName {
60 fn name(&self) -> &[u8];
61}
62
63pub trait HasPolicyId {
65 type Id: PolicyId;
66 fn id(&self) -> Self::Id;
67}
68
69impl Validate for Box<[u8]> {
70 fn validate(&self, _policy: &NewPolicy) -> Result<(), ValidateError> {
71 Ok(())
72 }
73}
74
75impl<T: Validate> Validate for Box<T> {
76 fn validate(&self, policy: &NewPolicy) -> Result<(), ValidateError> {
77 (**self).validate(policy)
78 }
79}
80
81impl Validate for bool {
82 fn validate(&self, _policy: &NewPolicy) -> Result<(), ValidateError> {
83 Ok(())
84 }
85}
86
87impl<T: Validate> Validate for Option<T> {
88 fn validate(&self, policy: &NewPolicy) -> Result<(), ValidateError> {
89 if let Some(value) = self {
90 value.validate(policy)?;
91 }
92 Ok(())
93 }
94}