Ver código fonte

fix and improve length conversion error message

deltanedas 1 semana atrás
pai
commit
99d6bf614c
2 arquivos alterados com 14 adições e 12 exclusões
  1. 1 1
      Cargo.toml
  2. 13 11
      src/impls.rs

+ 1 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "orio"
-version = "0.7.3"
+version = "0.7.4"
 authors = ["deltanedas"]
 edition = "2024"
 rust-version = "1.85"

+ 13 - 11
src/impls.rs

@@ -1,6 +1,7 @@
 use crate::*;
 
 use std::{
+	any::type_name,
 	collections::HashMap,
 	hash::Hash,
 	io::{Error, Read, Result, Write},
@@ -246,8 +247,9 @@ impl<K: Hash + Io + Ord, V: Io> LenIo for HashMap<K, V> {
 	}
 
 	fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
-		let len = L::try_from(self.len() as u64)
-			.map_err(conversion)?;
+		let len = self.len() as u64;
+		let len = L::try_from(len)
+			.map_err(|_| conversion_error(len, type_name::<L>()))?;
 		len.write(w)?;
 		// sorting has some overhead though probably not much overall
 		let mut keys = self.keys().collect::<Vec<_>>();
@@ -292,7 +294,7 @@ impl LenIo for Duration {
 		let ms = u64::try_from(self.as_millis())
 			.map_err(Error::other)?;
 		L::try_from(ms)
-			.map_err(conversion)?
+			.map_err(|_| conversion_error(ms, type_name::<L>()))?
 			.write(w)
 	}
 
@@ -354,9 +356,9 @@ impl LenIo for &str {
 	}
 
 	fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
-		let len = L::try_from(self.len() as u64)
-			.map_err(conversion)
-			.map_err(Error::other)?;
+		let len = self.len() as u64;
+		let len = L::try_from(len)
+			.map_err(|_| conversion_error(len, type_name::<L>()))?;
 		len.write(w)?;
 		w.write_all(self.as_bytes())
 	}
@@ -374,8 +376,9 @@ impl<T: Io> LenIo for &[T] {
 	}
 
 	fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
-		let len = L::try_from(self.len() as u64)
-			.map_err(conversion)?;
+		let len = self.len() as u64;
+		let len = L::try_from(len)
+			.map_err(|_| conversion_error(len, type_name::<L>()))?;
 		len.write(w)?;
 		for item in *self {
 			item.write(w)?;
@@ -405,9 +408,8 @@ impl<T: Io> Io for &T {
 	}
 }
 
-// discard error and use a string
-fn conversion<T>(_: T) -> Error {
-	Error::other("failed to convert length to u64")
+fn conversion_error(len: u64, ty: &str) -> Error {
+	Error::other(format!("cannot store length {len} as {ty}"))
 }
 
 fn immutable_read() -> Error {