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 all 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
44 changes: 43 additions & 1 deletion arrow-schema/src/datatype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@
// under the License.

use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

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

/// The set of datatypes that are supported by this implementation of Apache Arrow.
///
Expand Down Expand Up @@ -373,6 +374,35 @@ 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 = "Int32".parse().unwrap();
/// assert_eq!(data_type, DataType::Int32);
/// ```
impl FromStr for DataType {
type Err = ArrowError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
crate::datatype_parse::parse_data_type(s)
}
}

impl TryFrom<&str> for DataType {
type Error = ArrowError;

fn try_from(value: &str) -> Result<Self, Self::Error> {
value.parse()
}
}

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

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

#[test]
fn test_from_str() {
let data_type: DataType = "UInt64".parse().unwrap();
assert_eq!(data_type, DataType::UInt64);
}
}
Loading
Loading