Skip to content

Commit 986a7d4

Browse files
klion26mbrobbel
andauthored
[Variant] Add Variant::as_f16 (#8232)
# Which issue does this PR close? - Closes #8228. # What changes are included in this PR? Add `Variant::as_f16` # Are these changes tested? Added doc tests # Are there any user-facing changes? Added doc for the function --------- Co-authored-by: Matthijs Brobbel <m1brobbel@gmail.com>
1 parent f337933 commit 986a7d4

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

parquet-variant/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ rust-version = { workspace = true }
3333
[dependencies]
3434
arrow-schema = { workspace = true }
3535
chrono = { workspace = true }
36+
half = { version = "2.1", default-features = false }
3637
indexmap = "2.10.0"
3738
uuid = { version = "1.18.0", features = ["v4"]}
3839

parquet-variant/src/variant.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ use std::ops::Deref;
2828

2929
use arrow_schema::ArrowError;
3030
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc};
31+
use half::f16;
3132
use uuid::Uuid;
3233

3334
mod decimal;
@@ -915,6 +916,37 @@ impl<'m, 'v> Variant<'m, 'v> {
915916
_ => None,
916917
}
917918
}
919+
920+
/// Converts this variant to an `f16` if possible.
921+
///
922+
/// Returns `Some(f16)` for float and double variants,
923+
/// `None` for non-floating-point variants.
924+
///
925+
/// # Example
926+
///
927+
/// ```
928+
/// use parquet_variant::Variant;
929+
/// use half::f16;
930+
///
931+
/// // you can extract an f16 from a float variant
932+
/// let v1 = Variant::from(std::f32::consts::PI);
933+
/// assert_eq!(v1.as_f16(), Some(f16::from_f32(std::f32::consts::PI)));
934+
///
935+
/// // and from a double variant (with loss of precision to nearest f16)
936+
/// let v2 = Variant::from(std::f64::consts::PI);
937+
/// assert_eq!(v2.as_f16(), Some(f16::from_f64(std::f64::consts::PI)));
938+
///
939+
/// // but not from other variants
940+
/// let v3 = Variant::from("hello!");
941+
/// assert_eq!(v3.as_f16(), None);
942+
pub fn as_f16(&self) -> Option<f16> {
943+
match *self {
944+
Variant::Float(i) => Some(f16::from_f32(i)),
945+
Variant::Double(i) => Some(f16::from_f64(i)),
946+
_ => None,
947+
}
948+
}
949+
918950
/// Converts this variant to an `f32` if possible.
919951
///
920952
/// Returns `Some(f32)` for float and double variants,

0 commit comments

Comments
 (0)