chiark / gitweb /
Convert bundles::Index to a newtype
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Sun, 2 May 2021 20:50:09 +0000 (21:50 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Sun, 2 May 2021 20:50:29 +0000 (21:50 +0100)
Mostly for string formatting.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
src/bin/otter.rs
src/bundles.rs

index ce57ceaba38e3b9f0b5200176240f604453c1ddd..5e378878382ffbcf18a7ab9ed599ac6fc509d070 100644 (file)
@@ -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, &note);
+      println!("{} {:?}", bundles::Index::try_from(index).unwrap(), &note);
     }
   }
 
index 70f3006143cd9a3d98949df1e9228f61a106d73b..948aca7e1af264a5feec9fc54a6ebc5ba2dd41bb 100644 (file)
@@ -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<Index> for usize {
+  fn from(i: Index) -> usize { i.0.into() }
+}
+impl TryFrom<usize> 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<S>(instance: &InstanceName, index: Index, suffix: S) -> String
 where S: Display + Debug
 {
-  format!("{}/{:05}.{}",
+  format!("{}/{}.{}",
           savefilename(instance, "b-", ""),
           index, suffix)
 }