Skip to content

Commit 1f0b000

Browse files
authored
implement DataType::try_form(&str) (#5994)
* implement "DataType::try_form(&str)" * add missing file * add FromStr as well as TryFrom<&str> * fmt
1 parent e7a0008 commit 1f0b000

File tree

3 files changed

+827
-1
lines changed

3 files changed

+827
-1
lines changed

arrow-schema/src/datatype.rs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@
1616
// under the License.
1717

1818
use std::fmt;
19+
use std::str::FromStr;
1920
use std::sync::Arc;
2021

21-
use crate::{Field, FieldRef, Fields, UnionFields};
22+
use crate::{ArrowError, Field, FieldRef, Fields, UnionFields};
2223

2324
/// The set of datatypes that are supported by this implementation of Apache Arrow.
2425
///
@@ -373,6 +374,35 @@ impl fmt::Display for DataType {
373374
}
374375
}
375376

377+
/// Parses `str` into a `DataType`.
378+
///
379+
/// This is the reverse of [`DataType`]'s `Display`
380+
/// impl, and maintains the invariant that
381+
/// `DataType::try_from(&data_type.to_string()).unwrap() == data_type`
382+
///
383+
/// # Example
384+
/// ```
385+
/// use arrow_schema::DataType;
386+
///
387+
/// let data_type: DataType = "Int32".parse().unwrap();
388+
/// assert_eq!(data_type, DataType::Int32);
389+
/// ```
390+
impl FromStr for DataType {
391+
type Err = ArrowError;
392+
393+
fn from_str(s: &str) -> Result<Self, Self::Err> {
394+
crate::datatype_parse::parse_data_type(s)
395+
}
396+
}
397+
398+
impl TryFrom<&str> for DataType {
399+
type Error = ArrowError;
400+
401+
fn try_from(value: &str) -> Result<Self, Self::Error> {
402+
value.parse()
403+
}
404+
}
405+
376406
impl DataType {
377407
/// Returns true if the type is primitive: (numeric, temporal).
378408
#[inline]
@@ -985,4 +1015,16 @@ mod tests {
9851015
UnionMode::Dense,
9861016
);
9871017
}
1018+
1019+
#[test]
1020+
fn test_try_from_str() {
1021+
let data_type: DataType = "Int32".try_into().unwrap();
1022+
assert_eq!(data_type, DataType::Int32);
1023+
}
1024+
1025+
#[test]
1026+
fn test_from_str() {
1027+
let data_type: DataType = "UInt64".parse().unwrap();
1028+
assert_eq!(data_type, DataType::UInt64);
1029+
}
9881030
}

0 commit comments

Comments
 (0)