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

implement DataType::try_form(&str) #5994

Merged
merged 4 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
29 changes: 28 additions & 1 deletion arrow-schema/src/datatype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
use std::fmt;
use std::sync::Arc;

use crate::{Field, FieldRef, Fields, UnionFields};
use crate::{Field, FieldRef, Fields, UnionFields, ArrowError};

/// The set of datatypes that are supported by this implementation of Apache Arrow.
///
Expand Down Expand Up @@ -373,6 +373,27 @@ impl fmt::Display for DataType {
}
}

/// Parses `str` into a `DataType`.
///
/// This is the reverse of [`DataType`]'s `Display`
/// impl, and maintains the invariant that
/// `DataType::try_from(&data_type.to_string()).unwrap() == data_type`
///
/// # Example
/// ```
/// use arrow_schema::DataType;
///
/// let data_type: DataType = DataType::try_from("Int32").unwrap();
/// assert_eq!(data_type, DataType::Int32);
/// ```
impl TryFrom<&str> for DataType {
type Error = ArrowError;

fn try_from(value: &str) -> Result<Self, ArrowError> {
crate::datatype_parse::parse_data_type(value)
}
}

impl DataType {
/// Returns true if the type is primitive: (numeric, temporal).
#[inline]
Expand Down Expand Up @@ -985,4 +1006,10 @@ mod tests {
UnionMode::Dense,
);
}

#[test]
fn test_try_from_str() {
let data_type: DataType = "Int32".try_into().unwrap();
assert_eq!(data_type, DataType::Int32);
}
}
Loading