Browse Source

add result/str/slice/ref impls and feature-gated char impl

deltanedas 2 years ago
parent
commit
a760726d86
4 changed files with 199 additions and 36 deletions
  1. 5 3
      Cargo.toml
  2. 115 17
      src/impls.rs
  3. 2 2
      src/io.rs
  4. 77 14
      src/tests.rs

+ 5 - 3
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "orio"
-version = "0.5.3"
+version = "0.6.0"
 authors = ["deltanedas"]
 edition = "2021"
 readme = "README.md"
@@ -16,8 +16,10 @@ arrayvec = "0.7"
 byteorder = "1"
 orio-derive = {path = "orio-derive", version = "0.5.1", optional = true}
 paste = "1"
+utf8-chars = {version = "3", optional = true}
 
 [features]
-default = ["derive", "usize"]
-derive = ["orio-derive"]
+default = ["char", "derive", "usize"]
+char = ["dep:utf8-chars"]
+derive = ["dep:orio-derive"]
 usize = []

+ 115 - 17
src/impls.rs

@@ -102,6 +102,27 @@ impl Io for bool {
 	}
 }
 
+/// UTF-8 encoded unicode codepoint.
+#[cfg(feature = "char")]
+impl Io for char {
+	fn read(r: &mut Reader) -> Result<Self> {
+		use utf8_chars::BufReadCharsExt;
+		r.read_char()?
+			.ok_or_else(|| other("unexpected EOF"))
+	}
+
+	fn write(&self, w: &mut Writer) -> Result<()> {
+		let mut buf = [0; 4];
+		w.write_all(self.encode_utf8(&mut buf).as_bytes())
+	}
+
+	fn size(&self) -> usize {
+		// bit wasteful but eh
+		let mut buf = [0; 4];
+		self.encode_utf8(&mut buf).len()
+	}
+}
+
 /// Treat usize as u64 on all platforms to allow for better compatibility.
 #[cfg(feature = "usize")]
 impl Io for usize {
@@ -151,6 +172,32 @@ impl<T: Io> Io for Option<T> {
 	}
 }
 
+/// Result Io implementation
+impl<T: Io, E: Io> Io for std::result::Result<T, E> {
+	fn read(r: &mut Reader) -> Result<Self> {
+		if bool::read(r)? {
+			T::read(r).map(Ok)
+		} else {
+			E::read(r).map(Err)
+		}
+	}
+
+	fn write(&self, w: &mut Writer) -> Result<()> {
+		self.is_ok().write(w)?;
+		match self {
+			Ok(inner) => inner.write(w),
+			Err(e) => e.write(w)
+		}
+	}
+
+	fn size(&self) -> usize {
+		1 + match self {
+			Ok(inner) => inner.size(),
+			Err(e) => e.size()
+		}
+	}
+}
+
 /// String LenIo implementation
 impl LenIo for String {
 	fn read<L: Len>(r: &mut Reader) -> Result<Self> {
@@ -162,15 +209,11 @@ impl LenIo for String {
 	}
 
 	fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
-		let len = L::try_from(self.len() as u64)
-			.map_err(|_| "conversion to u64 failed")
-			.map_err(other)?;
-		len.write(w)?;
-		w.write_all(self.as_bytes())
+		self.as_str().write::<L>(w)
 	}
 
 	fn size<L: Len>(&self) -> usize {
-		size_of::<L>() + self.len()
+		self.as_str().size::<L>()
 	}
 }
 
@@ -184,18 +227,11 @@ impl<T: Io> LenIo for Vec<T> {
 	}
 
 	fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
-		let len = L::try_from(self.len() as u64)
-			.map_err(conversion)?;
-		len.write(w)?;
-		for item in self {
-			item.write(w)?;
-		}
-
-		Ok(())
+		(self as &[T]).write::<L>(w)
 	}
 
 	fn size<L: Len>(&self) -> usize {
-		size_of::<L>() + self.iter().map(Io::size).sum::<usize>()
+		(self as &[T]).size::<L>()
 	}
 }
 
@@ -302,8 +338,7 @@ impl<T: Io, const N: usize> Io for [T; N] {
 
 	fn write(&self, w: &mut Writer) -> Result<()> {
 		self.iter()
-			.map(|item| item.write(w))
-			.collect()
+			.try_for_each(|item| item.write(w))
 	}
 
 	fn size(&self) -> usize {
@@ -311,6 +346,65 @@ impl<T: Io, const N: usize> Io for [T; N] {
 	}
 }
 
+/// Write-only `str` LenIo implementation.
+/// Errors at runtime if you try to read it.
+impl LenIo for &str {
+	fn read<L: Len>(_: &mut Reader) -> Result<Self> {
+		Err(immutable_read())
+	}
+
+	fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
+		let len = L::try_from(self.len() as u64)
+			.map_err(conversion)
+			.map_err(other)?;
+		len.write(w)?;
+		w.write_all(self.as_bytes())
+	}
+
+	fn size<L: Len>(&self) -> usize {
+		size_of::<L>() + self.len()
+	}
+}
+
+/// Write-only unbounded slice LenIo implementation.
+/// Errors at runtime if you try to read it.
+impl<T: Io> LenIo for &[T] {
+	fn read<L: Len>(_: &mut Reader) -> Result<Self> {
+		Err(immutable_read())
+	}
+
+	fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
+		let len = L::try_from(self.len() as u64)
+			.map_err(conversion)?;
+		len.write(w)?;
+		for item in *self {
+			item.write(w)?;
+		}
+
+		Ok(())
+	}
+
+	fn size<L: Len>(&self) -> usize {
+		size_of::<L>() + self.iter().map(Io::size).sum::<usize>()
+	}
+}
+
+/// Write-only Io implementation for references.
+/// Errors are runtime if you try to read it.
+impl<T: Io> Io for &T {
+	fn read(_: &mut Reader) -> Result<Self> {
+		Err(immutable_read())
+	}
+
+	fn write(&self, w: &mut Writer) -> Result<()> {
+		T::write(*self, w)
+	}
+
+	fn size(&self) -> usize {
+		T::size(*self)
+	}
+}
+
 // basically Error::other but not requiring nightly
 fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
 	Error::new(ErrorKind::Other, error)
@@ -320,3 +414,7 @@ fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
 fn conversion<T>(_: T) -> Error {
 	other("failed to convert length to u64")
 }
+
+fn immutable_read() -> Error {
+	other("immutable references cannot be read into")
+}

+ 2 - 2
src/io.rs

@@ -19,7 +19,7 @@ pub trait Io : Sized {
 
 	/// Create a Vec<u8> and write to it.
 	/// Should only be used for highest level types or when sending packets.
-	fn to_bytes(&self) -> Result<Vec<u8>> {
+	fn write_to_bytes(&self) -> Result<Vec<u8>> {
 		let size = self.size();
 		let mut bytes = Vec::with_capacity(size);
 		self.write(&mut bytes)?;
@@ -47,7 +47,7 @@ pub trait LenIo : Sized {
 
 	/// Create a Vec<u8> and write to it.
 	/// Should only be used for highest level types or when sending packets.
-	fn to_bytes<L: Len>(&self) -> Result<Vec<u8>> {
+	fn write_to_bytes<L: Len>(&self) -> Result<Vec<u8>> {
 		let size = self.size::<L>();
 		let mut bytes = Vec::with_capacity(size);
 		self.write::<L>(&mut bytes)?;

+ 77 - 14
src/tests.rs

@@ -114,7 +114,7 @@ fn write_people() -> Result<()> {
 			name: name.to_owned()
 		})
 		.collect::<Vec<_>>();
-	let bytes = people.to_bytes::<u16>()?;
+	let bytes = people.write_to_bytes::<u16>()?;
 
 	assert_eq!(bytes, b"\x03\x00\x04John\x03Bob\x05Harry");
 
@@ -124,7 +124,7 @@ fn write_people() -> Result<()> {
 #[test]
 fn string_vec_transmutation() -> Result<()> {
 	let num_vec = vec![b'H', b'e', b'l', b'l', b'o'];
-	let bytes = num_vec.to_bytes::<u8>()?;
+	let bytes = num_vec.write_to_bytes::<u8>()?;
 
 	let mut bytes = &bytes[..];
 	assert_eq!("Hello".to_owned(), String::read::<u8>(&mut bytes)?);
@@ -142,7 +142,7 @@ fn hashmap() -> Result<()> {
 		(Name("Bread".to_owned()), 12)
 	]);
 
-	let bytes = hashmap.to_bytes::<u16>()?;
+	let bytes = hashmap.write_to_bytes::<u16>()?;
 	assert_eq!(bytes, b"\x02\x00\x05Bread\x0c\x03Egg\x05");
 
 	let mut bytes = &bytes[..];
@@ -159,7 +159,7 @@ fn ignored_struct_field() -> Result<()> {
 		tasks_done: 3
 	};
 
-	let bytes = crewmate.to_bytes()?;
+	let bytes = crewmate.write_to_bytes()?;
 	assert_eq!(bytes, b"\x06\x00Yellow\x03");
 
 	let mut bytes = &bytes[..];
@@ -179,7 +179,7 @@ fn time_tests() -> Result<()> {
 	];
 
 	for (duration, expected) in tests {
-		let bytes = duration.to_bytes::<u32>()?;
+		let bytes = duration.write_to_bytes::<u32>()?;
 		assert_eq!(bytes, expected);
 
 		let mut bytes = &bytes[..];
@@ -187,7 +187,7 @@ fn time_tests() -> Result<()> {
 
 		// not hardcoding a time since that would be Very Unlikely to pass
 		let time = UNIX_EPOCH + duration;
-		let bytes = time.to_bytes()?;
+		let bytes = time.write_to_bytes()?;
 
 		let mut bytes = &bytes[..];
 		assert_eq!(time, SystemTime::read(&mut bytes)?);
@@ -210,7 +210,7 @@ fn egg_array() -> Result<()> {
 		}
 	];
 
-	let bytes = eggs.to_bytes()?;
+	let bytes = eggs.write_to_bytes()?;
 	assert_eq!(bytes, b"\x01\x00\x01");
 
 	let mut bytes = &bytes[..];
@@ -224,7 +224,7 @@ fn egg_array() -> Result<()> {
 fn usize_is_u64() -> Result<()> {
 	let n: usize = 0;
 
-	let bytes = n.to_bytes()?;
+	let bytes = n.write_to_bytes()?;
 	assert_eq!(bytes.len(), 8);
 
 	let mut bytes = &bytes[..];
@@ -252,7 +252,7 @@ fn giga_enum() -> Result<()> {
 		GigaEnum::Unit
 	];
 
-	let bytes = enums.to_bytes()?;
+	let bytes = enums.write_to_bytes()?;
 	assert_eq!(bytes, b"\x00\x04\x00chad\x01\x0c\x02");
 
 	let mut bytes = &bytes[..];
@@ -267,7 +267,7 @@ fn ignored_unnamed_fields() -> Result<()> {
 	struct Real(u8, #[io(ignore)] u16, u32);
 
 	let mut real = Real(17, 39, 263064);
-	let bytes = real.to_bytes()?;
+	let bytes = real.write_to_bytes()?;
 	assert_eq!(bytes, b"\x11\x98\x03\x04\x00");
 
 	// reading back ignored fields replaces them with default
@@ -285,7 +285,7 @@ fn u64_len() -> Result<()> {
 	struct Big(#[io(len(u64))] Vec<u8>);
 
 	let big = Big(vec![]);
-	let bytes = big.to_bytes()?;
+	let bytes = big.write_to_bytes()?;
 	assert_eq!(bytes, b"\x00\x00\x00\x00\x00\x00\x00\x00");
 
 	Ok(())
@@ -296,7 +296,7 @@ fn tuples() -> Result<()> {
 	type Tuple = (u8, u16, u8);
 
 	let tuple = (4, 512, 42);
-	let bytes = tuple.to_bytes()?;
+	let bytes = tuple.write_to_bytes()?;
 	assert_eq!(bytes, b"\x04\x00\x02\x2a");
 
 	let mut bytes = &bytes[..];
@@ -314,13 +314,76 @@ fn options() -> Result<()> {
 
 	let bytes = Optional {
 		thing: None
-	}.to_bytes()?;
+	}.write_to_bytes()?;
 	assert_eq!(bytes, b"\x00");
 
 	let bytes = Optional {
 		thing: Some(1234)
-	}.to_bytes()?;
+	}.write_to_bytes()?;
 	assert_eq!(bytes, b"\x01\xd2\x04");
 
 	Ok(())
 }
+
+#[test]
+fn results() -> Result<()> {
+	type R = std::result::Result::<u16, u8>;
+
+	let bytes = R::write_to_bytes(&Ok(512))?;
+	assert_eq!(bytes, b"\x01\x00\x02");
+
+	let bytes = R::write_to_bytes(&Err(64))?;
+	assert_eq!(bytes, b"\x00\x40");
+
+	Ok(())
+}
+
+#[test]
+fn str_slice() -> Result<()> {
+	let bytes = "".write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x00");
+
+	let bytes = "Hello".write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x05Hello");
+
+	Ok(())
+}
+
+#[cfg(feature = "char")]
+#[test]
+fn char_array_slice() -> Result<()> {
+	let arr = ['a', 'b', 'c', 'd', 'e'];
+
+	let bytes = (&arr[0..0]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x00");
+
+	let bytes = (&arr[..]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x05abcde");
+
+	let bytes = (&arr[1..]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x04bcde");
+
+	let bytes = (&arr[1..4]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x03bcd");
+
+	Ok(())
+}
+
+#[test]
+fn array_slice() -> Result<()> {
+	let arr = [b'a', b'b', b'c', b'd', b'e'];
+
+	let bytes = (&arr[0..0]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x00");
+
+	let bytes = (&arr[..]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x05abcde");
+
+	let bytes = (&arr[1..]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x04bcde");
+
+	let bytes = (&arr[1..4]).write_to_bytes::<u8>()?;
+	assert_eq!(bytes, b"\x03bcd");
+
+	Ok(())
+}