From: Ian Jackson Date: Sun, 2 May 2021 20:50:09 +0000 (+0100) Subject: Convert bundles::Index to a newtype X-Git-Tag: otter-0.6.0~470 X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?a=commitdiff_plain;h=6222746e3f55be7be6d1418aeebfff78f157e58b;p=otter.git Convert bundles::Index to a newtype Mostly for string formatting. Signed-off-by: Ian Jackson --- diff --git a/src/bin/otter.rs b/src/bin/otter.rs index ce57ceab..5e378878 100644 --- a/src/bin/otter.rs +++ b/src/bin/otter.rs @@ -1392,7 +1392,7 @@ mod list_bundles { else throw!(anyhow!("unexpected {:?}", &resp)) }; for (index, note) in bundles.into_iter().enumerate() { if_let!{ Some(note) = note; else continue; } - println!("{:05} {:?}", index, ¬e); + println!("{} {:?}", bundles::Index::try_from(index).unwrap(), ¬e); } } diff --git a/src/bundles.rs b/src/bundles.rs index 70f30061..948aca7e 100644 --- a/src/bundles.rs +++ b/src/bundles.rs @@ -19,8 +19,31 @@ pub enum Kind { } impl Kind { pub fn only() -> Self { Kind::Zip } } -pub type Index = u16; -const BUNDLES_MAX: Index = 64; +#[derive(Copy,Clone,Debug,Hash,PartialEq,Eq,Ord,PartialOrd)] +#[derive(Serialize,Deserialize)] +#[serde(transparent)] +pub struct Index(u16); +impl From for usize { + fn from(i: Index) -> usize { i.0.into() } +} +impl TryFrom for Index { + type Error = TryFromIntError; + #[throws(Self::Error)] + fn try_from(i: usize) -> Index { Index(i.try_into()?) } +} +impl Display for Index { + #[throws(fmt::Error)] + fn fmt(&self, f: &mut Formatter) { + write!(f, "{:05}", self.0)?; + } +} +impl FromStr for Index { + type Err = std::num::ParseIntError; + #[throws(Self::Err)] + fn from_str(s: &str) -> Index { Index(u16::from_str(s)?) } +} + +const BUNDLES_MAX: Index = Index(64); #[derive(Copy,Clone,Debug,Hash,PartialEq,Eq,Ord,PartialOrd)] #[derive(Serialize,Deserialize)] @@ -60,7 +83,7 @@ pub fn b_dir(instance: &InstanceName) -> String { fn b_file(instance: &InstanceName, index: Index, suffix: S) -> String where S: Display + Debug { - format!("{}/{:05}.{}", + format!("{}/{}.{}", savefilename(instance, "b-", ""), index, suffix) }