From 4630a51d1c73acf61c4527b640ba43bd6d4fb9b2 Mon Sep 17 00:00:00 2001 From: Clark McCauley Date: Tue, 11 Oct 2022 12:59:34 -0600 Subject: [PATCH] Implemented TryFrom for ObjectId --- src/oid.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/oid.rs b/src/oid.rs index 010c691b..139cc533 100644 --- a/src/oid.rs +++ b/src/oid.rs @@ -1,7 +1,7 @@ //! ObjectId use std::{ - convert::TryInto, + convert::{TryFrom, TryInto}, error, fmt, result, @@ -9,7 +9,6 @@ use std::{ sync::atomic::{AtomicUsize, Ordering}, time::SystemTime, }; -use std::convert::TryFrom; use hex::{self, FromHexError}; use rand::{thread_rng, Rng}; @@ -230,6 +229,13 @@ impl TryFrom<&str> for ObjectId { } } +impl TryFrom for ObjectId { + type Error = Error; + fn try_from(value: String) -> result::Result { + ObjectId::parse_str(value.as_str()) + } +} + #[cfg(test)] use crate::tests::LOCK; @@ -291,9 +297,12 @@ fn test_counter_overflow_usize_max() { #[cfg(test)] mod test { - use std::convert::{TryFrom, TryInto}; - use time::macros::datetime; use crate::oid::ObjectId; + use std::{ + convert::{TryFrom, TryInto}, + fmt::Debug, + }; + use time::macros::datetime; #[test] fn test_display() { @@ -346,9 +355,12 @@ mod test { #[test] fn test_string_conversions() { - let str = "000000000000000000000000"; - let id1 = ObjectId::try_from(str).expect("Unable to convert from string"); - let id2: ObjectId = str.try_into().unwrap(); - assert_eq!(id1, id2); + let str1 = "000000000000000000000000"; + let str2 = String::from("000000000000000000000000"); + let id1 = ObjectId::try_from(str1).expect("Unable to convert from string"); + let id2 = ObjectId::try_from(str2).expect("Unable to convert from string"); + let id3: ObjectId = str1.try_into().unwrap(); + assert_eq!(id1, id3); + assert_eq!(id2, id3); } }