deltanedas 3 лет назад
Родитель
Сommit
785bdc4f6c
2 измененных файлов с 64 добавлено и 2 удалено
  1. 34 1
      src/impls.rs
  2. 30 1
      src/tests.rs

+ 34 - 1
src/impls.rs

@@ -4,7 +4,8 @@ use std::{
 	collections::HashMap,
 	collections::HashMap,
 	hash::Hash,
 	hash::Hash,
 	io::{Error, ErrorKind, Read, Result, Write},
 	io::{Error, ErrorKind, Read, Result, Write},
-	ops::Deref
+	ops::Deref,
+	time::{Duration, SystemTime, UNIX_EPOCH}
 };
 };
 
 
 use paste::paste;
 use paste::paste;
@@ -183,6 +184,38 @@ impl<T: Io> Io for Box<T> {
 	}
 	}
 }
 }
 
 
+// TODO: implement thing similar to string length type
+// once thats done SystemTime Io is a lot saner
+impl Io for Duration {
+	fn read(r: &mut Reader) -> Result<Self> {
+		u32::read(r)
+			.map(u64::from)
+			.map(Duration::from_millis)
+	}
+
+	fn write(&self, w: &mut Writer) -> Result<()> {
+		u32::try_from(self.as_millis())
+			.map_err(other)?
+			.write(w)
+	}
+}
+
+// TODO: configurable precision
+impl Io for SystemTime {
+	fn read(r: &mut Reader) -> Result<Self> {
+		u64::read(r)
+			.map(Duration::from_millis)
+			.map(|offset| UNIX_EPOCH + offset)
+	}
+
+	fn write(&self, w: &mut Writer) -> Result<()> {
+		self.duration_since(UNIX_EPOCH)
+			.map_err(other)
+			.map(|offset| offset.as_millis())?
+			.write(w)
+	}
+}
+
 // basically Error::other but not requiring nightly
 // basically Error::other but not requiring nightly
 fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
 fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
 	Error::new(ErrorKind::Other, error)
 	Error::new(ErrorKind::Other, error)

+ 30 - 1
src/tests.rs

@@ -2,7 +2,8 @@ use crate::*;
 
 
 use std::{
 use std::{
 	collections::HashMap,
 	collections::HashMap,
-	io::Result
+	io::Result,
+	time::{Duration, SystemTime, UNIX_EPOCH}
 };
 };
 
 
 // this is manually implemented to show how its done
 // this is manually implemented to show how its done
@@ -163,3 +164,31 @@ fn ignored_struct_field() -> Result<()> {
 
 
 	Ok(())
 	Ok(())
 }
 }
+
+#[test]
+fn time_tests() -> Result<()> {
+	let tests = [
+		(Duration::from_millis(16), b"\x10\x00\x00\x00"),
+		(Duration::from_secs(5), b"\x88\x13\x00\x00"),
+		(Duration::from_secs(600), b"\xc0\x27\x09\x00")
+	];
+
+	for (duration, expected) in tests {
+		let mut bytes = vec![];
+		duration.write(&mut bytes)?;
+		assert_eq!(bytes, expected);
+
+		let mut bytes = &bytes[..];
+		assert_eq!(duration, Duration::read(&mut bytes)?);
+
+		// not hardcoding a time since that would be Very Unlikely to pass
+		let mut bytes = vec![];
+		let time = UNIX_EPOCH + duration;
+		time.write(&mut bytes)?;
+
+		let mut bytes = &bytes[..];
+		assert_eq!(time, SystemTime::read(&mut bytes)?);
+	}
+
+	Ok(())
+}