|
16 | 16 | // under the License.
|
17 | 17 |
|
18 | 18 | use std::fmt;
|
| 19 | +use std::str::FromStr; |
19 | 20 | use std::sync::Arc;
|
20 | 21 |
|
21 |
| -use crate::{Field, FieldRef, Fields, UnionFields}; |
| 22 | +use crate::{ArrowError, Field, FieldRef, Fields, UnionFields}; |
22 | 23 |
|
23 | 24 | /// The set of datatypes that are supported by this implementation of Apache Arrow.
|
24 | 25 | ///
|
@@ -373,6 +374,35 @@ impl fmt::Display for DataType {
|
373 | 374 | }
|
374 | 375 | }
|
375 | 376 |
|
| 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 | + |
376 | 406 | impl DataType {
|
377 | 407 | /// Returns true if the type is primitive: (numeric, temporal).
|
378 | 408 | #[inline]
|
@@ -985,4 +1015,16 @@ mod tests {
|
985 | 1015 | UnionMode::Dense,
|
986 | 1016 | );
|
987 | 1017 | }
|
| 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 | + } |
988 | 1030 | }
|
0 commit comments