From 7785b3b517ad258eb488bf6f88f9dcb9daf96b5f Mon Sep 17 00:00:00 2001 From: Nicolas <344493+haricot@users.noreply.github.com> Date: Sat, 15 Feb 2025 16:39:25 +0100 Subject: [PATCH] refactor(dtype): deduplicate type conversion patterns in as_ macro --- candle-core/src/dtype.rs | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/candle-core/src/dtype.rs b/candle-core/src/dtype.rs index 9430802c5..13194a8dc 100644 --- a/candle-core/src/dtype.rs +++ b/candle-core/src/dtype.rs @@ -119,25 +119,25 @@ pub trait WithDType: fn cpu_storage_as(s: &CpuStorage, layout: &crate::Layout, dtype: DType) -> Result; } +macro_rules! as_ { + (U8, U8, $v:expr) => {$v}; + (U32, U32, $v:expr) => {$v}; + (I64, I64, $v:expr) => {$v}; + (F32, F32, $v:expr) => {$v}; + (F64, F64, $v:expr) => {$v}; + (BF16, BF16, $v:expr) => {$v}; + (F16, F16, $v:expr) => {$v}; + ($in:expr, U8, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; + ($in:expr, U32, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; + ($in:expr, I64, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; + ($in:expr, F32, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; + ($in:expr, F64, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; + ($in:expr, BF16, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; + ($in:expr, F16, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; +} + macro_rules! cpu_storage_as { (match:($cpu_storage: expr, $match_dtype: ident), $layout: ident, $with_dtype: ident, ($($dtype: ident),+)) => {{ - macro_rules! as_ { - (U8, U8, $v:expr) => {$v}; - (U32, U32, $v:expr) => {$v}; - (I64, I64, $v:expr) => {$v}; - (F32, F32, $v:expr) => {$v}; - (F64, F64, $v:expr) => {$v}; - (BF16, BF16, $v:expr) => {$v}; - (F16, F16, $v:expr) => {$v}; - ($in:expr, U8, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; - ($in:expr, U32, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; - ($in:expr, I64, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; - ($in:expr, F32, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; - ($in:expr, F64, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; - ($in:expr, BF16, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; - ($in:expr, F16, $v:expr) => { num_traits::AsPrimitive::::as_($v)}; - } - match ($cpu_storage, $match_dtype) { $((CpuStorage::$with_dtype(storage), DType::$dtype) => { Ok({ let data = crate::cpu_backend::unary_map(&storage, $layout,