|
| 1 | +use std::{error::Error, fmt::Display}; |
| 2 | + |
1 | 3 | use mac_address::{get_mac_address, MacAddress, MacAddressError}; |
2 | 4 |
|
3 | 5 | use crate::{id::Flake, seq::SeqGen}; |
@@ -35,7 +37,11 @@ impl FlakeGen { |
35 | 37 | /// let id: Flake = gen.next().expect("No ID was generated"); |
36 | 38 | /// ``` |
37 | 39 | pub fn with_mac_addr() -> Result<FlakeGen, FlakeGenErr> { |
38 | | - let mac_addr: MacAddress = get_mac_address()?.ok_or(FlakeGenErr::NoMacAddr)?; |
| 40 | + let mac_addr: MacAddress = match get_mac_address() { |
| 41 | + Ok(Some(addr)) => addr, |
| 42 | + Ok(None) => return Err(FlakeGenErr::NoMacAddr(None)), |
| 43 | + Err(err) => return Err(FlakeGenErr::NoMacAddr(Some(err))), |
| 44 | + }; |
39 | 45 | let mac_addr: u64 = |
40 | 46 | mac_addr.bytes().iter().fold(0u64, |acc, value| (acc << 8) + (*value as u64)); |
41 | 47 |
|
@@ -82,15 +88,34 @@ impl Iterator for FlakeGen { |
82 | 88 | pub enum FlakeGenErr { |
83 | 89 | /// No MAC address could be found on the host device, which makes it impossible to generate |
84 | 90 | /// flake ids that are globally unique. |
85 | | - NoMacAddr, |
| 91 | + NoMacAddr(Option<MacAddressError>), |
| 92 | +} |
| 93 | + |
| 94 | +impl Display for FlakeGenErr { |
| 95 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 96 | + f.write_str("unable to acquire MAC address") |
| 97 | + } |
86 | 98 | } |
87 | 99 |
|
88 | | -impl From<MacAddressError> for FlakeGenErr { |
89 | | - fn from(_: MacAddressError) -> Self { |
90 | | - FlakeGenErr::NoMacAddr |
| 100 | +impl Error for FlakeGenErr { |
| 101 | + fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 102 | + match self { |
| 103 | + FlakeGenErr::NoMacAddr(Some(err)) => Some(err), |
| 104 | + FlakeGenErr::NoMacAddr(None) => None, |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + fn cause(&self) -> Option<&dyn Error> { |
| 109 | + self.source() |
91 | 110 | } |
92 | 111 | } |
93 | 112 |
|
| 113 | +// impl From<MacAddressError> for FlakeGenErr { |
| 114 | +// fn from(err: MacAddressError) -> Self { |
| 115 | +// FlakeGenErr::NoMacAddr(Some(err)) |
| 116 | +// } |
| 117 | +// } |
| 118 | + |
94 | 119 | /// A FlakeErr is an error that could happen when we try to generate an _identifier_ (`Flake`) |
95 | 120 | #[derive(Debug)] |
96 | 121 | pub enum FlakeErr { |
|
0 commit comments