Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Cow<str> conversion to Value #550

Merged
merged 8 commits into from
Dec 15, 2022
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/value.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Container for all SQL value types.

use std::borrow::Cow;

#[cfg(feature = "with-json")]
use serde_json::Value as Json;
#[cfg(feature = "with-json")]
Expand Down Expand Up @@ -435,6 +437,33 @@ where
}
}

impl<'a> From<Cow<'a, str>> for Value {
fn from(x: Cow<'a, str>) -> Value {
x.into_owned().into()
}
}

impl<'a> ValueType for Cow<'a, str> {
ikrivosheev marked this conversation as resolved.
Show resolved Hide resolved
fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
match v {
Value::String(Some(x)) => Ok((*x).into()),
_ => Err(ValueTypeErr),
}
}

fn type_name() -> String {
"Cow<str>".into()
}

fn array_type() -> ArrayType {
ArrayType::String
}

fn column_type() -> ColumnType {
ColumnType::Text
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think ColumnType::String(None) is more appropriate and it align with the implementation of impl ValueType for String.

}
}

type_to_box_value!(Vec<u8>, Bytes, Binary(BlobSize::Blob(None)));
type_to_box_value!(String, String, String(None));

Expand Down Expand Up @@ -1458,6 +1487,15 @@ mod tests {
test_none!(i64, BigInt);
}

#[test]
fn test_cow_value() {
let val: Cow<str> = "hello".into();
let val2 = val.clone();
let v: Value = val.into();
let out: Cow<str> = v.unwrap();
assert_eq!(out, val2);
}

#[test]
fn test_box_value() {
let val: String = "hello".to_owned();
Expand Down