Skip to content

Commit

Permalink
implement DataType::try_form(&str) (#5994)
Browse files Browse the repository at this point in the history
* implement "DataType::try_form(&str)"

* add missing file

* add FromStr as well as TryFrom<&str>

* fmt
  • Loading branch information
samuelcolvin committed Jul 3, 2024
1 parent e7a0008 commit 1f0b000
Show file tree
Hide file tree
Showing 3 changed files with 827 additions and 1 deletion.
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

0 comments on commit 1f0b000

Please sign in to comment.