Skip to content

Commit

Permalink
RUST-1421 Implement FromStr for Namespace (#889)
Browse files Browse the repository at this point in the history
* RUST-1421 Implement FromStr for Namespace
  • Loading branch information
drshika authored Jun 9, 2023
1 parent d9490a2 commit 9ef3ada
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/coll/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod options;

use std::{borrow::Borrow, collections::HashSet, fmt, fmt::Debug, sync::Arc};
use std::{borrow::Borrow, collections::HashSet, fmt, fmt::Debug, str::FromStr, sync::Arc};

use futures_util::{
future,
Expand Down Expand Up @@ -1501,3 +1501,23 @@ impl Serialize for Namespace {
serializer.serialize_str(&(self.db.clone() + "." + &self.coll))
}
}

impl FromStr for Namespace {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let mut parts = s.split('.');

let db = parts.next();
let coll = parts.collect::<Vec<_>>().join(".");

match (db, coll) {
(Some(db), coll) if !coll.is_empty() => Ok(Self {
db: db.to_string(),
coll,
}),
_ => Err(Self::Err::invalid_argument(
"Missing one or more fields in namespace",
)),
}
}
}
13 changes: 13 additions & 0 deletions src/test/coll.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{fmt::Debug, time::Duration};

use crate::Namespace;
use futures::stream::{StreamExt, TryStreamExt};
use lazy_static::lazy_static;
use semver::VersionReq;
Expand Down Expand Up @@ -1201,3 +1202,15 @@ fn assert_duplicate_key_error_with_utf8_replacement(error: &ErrorKind) {
),
}
}

#[test]
fn test_namespace_fromstr() {
let t: Namespace = "something.somethingelse".parse().unwrap();
assert_eq!(t.db, "something");
assert_eq!(t.coll, "somethingelse");
let t2: Result<Namespace> = "blahblah".parse();
assert!(t2.is_err());
let t: Namespace = "something.something.else".parse().unwrap();
assert_eq!(t.db, "something");
assert_eq!(t.coll, "something.else");
}

0 comments on commit 9ef3ada

Please sign in to comment.