85 lines
2 KiB
Rust
85 lines
2 KiB
Rust
use std::{convert::TryFrom, fmt};
|
|
|
|
use sea_orm::prelude::*;
|
|
use std::ops::{Deref, Index};
|
|
|
|
pub enum MacParseError {
|
|
BadOctet,
|
|
WrongOctetCount,
|
|
}
|
|
|
|
/// Wrapper type for validation and manipulation of MAC addresses
|
|
pub struct MacAddr(pub [u8; 6]);
|
|
|
|
impl TryFrom<String> for MacAddr {
|
|
type Error = MacParseError;
|
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
|
let v = value
|
|
.split(':')
|
|
.map(|x| u8::from_str_radix(x, 16))
|
|
.collect::<Result<Vec<u8>, _>>()
|
|
.map_err(|_| Self::Error::BadOctet)?;
|
|
let octets: [u8; 6] = v.try_into().map_err(|_| Self::Error::WrongOctetCount)?;
|
|
|
|
Ok(Self(octets))
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for MacAddr {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
write!(f, "{}", self.0.map(|x| format!("{:x}", x)).join(":"))
|
|
}
|
|
}
|
|
|
|
impl Deref for MacAddr {
|
|
type Target = [u8; 6];
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl Index<usize> for MacAddr {
|
|
type Output = u8;
|
|
fn index(&self, index: usize) -> &Self::Output {
|
|
&self.0[index]
|
|
}
|
|
}
|
|
|
|
/// Key for defaults table
|
|
#[derive(Clone, Copy, Debug, EnumIter, PartialEq, Eq, DeriveActiveEnum)]
|
|
#[sea_orm(rs_type = "String", db_type = "Text")]
|
|
pub enum DefaultKey {
|
|
#[sea_orm(string_value = "ssh_keys")]
|
|
SshKeys,
|
|
}
|
|
|
|
impl sea_orm::TryFromU64 for DefaultKey {
|
|
fn try_from_u64(_: u64) -> Result<Self, DbErr> {
|
|
// XXX: ok im being a bit lazy here. it's prolly fine
|
|
Err(DbErr::Type("?????".to_owned()))
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for DefaultKey {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::SshKeys => write!(f, "ssh_keys"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum ParseError {
|
|
InvalidKey,
|
|
}
|
|
|
|
impl TryFrom<String> for DefaultKey {
|
|
type Error = ParseError;
|
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
|
match value.as_str() {
|
|
"ssh_keys" => Ok(Self::SshKeys),
|
|
_ => Err(ParseError::InvalidKey),
|
|
}
|
|
}
|
|
}
|