瀏覽代碼

add [impl Io; N] array support

deltanedas 3 年之前
父節點
當前提交
9085162cb2
共有 4 個文件被更改,包括 50 次插入 和 3 次删除
  1. 4 2
      Cargo.toml
  2. 1 1
      orio-derive/Cargo.toml
  3. 21 0
      src/impls.rs
  4. 24 0
      src/tests.rs

+ 4 - 2
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "orio"
-version = "0.1.0"
+version = "0.2.0"
 authors = ["deltanedas"]
 edition = "2021"
 readme = "README.md"
@@ -11,8 +11,10 @@ categories = ["encoding"]
 keywords = ["serialization"]
 
 [dependencies]
+# only used as a workaround to array try_from_fn not being stable
+arrayvec = "0.7"
 byteorder = "1"
-orio-derive = {path = "orio-derive", version = "0.1.1", optional = true}
+orio-derive = {path = "orio-derive", version = "0.2.0", optional = true}
 paste = "1"
 
 [features]

+ 1 - 1
orio-derive/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "orio-derive"
-version = "0.1.1"
+version = "0.2.0"
 authors = ["deltanedas"]
 edition = "2021"
 readme = "README.md"

+ 21 - 0
src/impls.rs

@@ -8,6 +8,7 @@ use std::{
 	time::{Duration, SystemTime, UNIX_EPOCH}
 };
 
+use arrayvec::ArrayVec;
 use paste::paste;
 
 macro_rules! impl_basic {
@@ -216,6 +217,26 @@ impl Io for SystemTime {
 	}
 }
 
+impl<T: Io, const N: usize> Io for [T; N] {
+	fn read(r: &mut Reader) -> Result<Self> {
+		// this is used as a workaround for https://github.com/rust-lang/rust/issues/89379 not being stable
+		// :(((( literally 1 line and no unsafe
+		let array = [(); N]
+			.iter()
+			.map(|_| T::read(r))
+			.collect::<Result<ArrayVec<T, N>>>()?
+			.into_inner();
+		// SAFETY: this will never fail since [(); N] always has N items
+		Ok(unsafe { array.unwrap_unchecked() })
+	}
+
+	fn write(&self, w: &mut Writer) -> Result<()> {
+		self.iter()
+			.map(|item| item.write(w))
+			.collect()
+	}
+}
+
 // 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)

+ 24 - 0
src/tests.rs

@@ -192,3 +192,27 @@ fn time_tests() -> Result<()> {
 
 	Ok(())
 }
+
+#[test]
+fn egg_array() -> Result<()> {
+	let eggs = [
+		Egg {
+			hatched: true
+		},
+		Egg {
+			hatched: false
+		},
+		Egg {
+			hatched: true
+		}
+	];
+
+	let mut bytes = vec![];
+	eggs.write(&mut bytes)?;
+	assert_eq!(bytes, b"\x01\x00\x01");
+
+	let mut bytes = &bytes[..];
+	assert_eq!(eggs, <[Egg; 3]>::read(&mut bytes)?);
+
+	Ok(())
+}