Skip to main content

diskann_benchmark_runner/dispatcher/
examples.rs

1/*
2 * Copyright (c) Microsoft Corporation.
3 * Licensed under the MIT license.
4 */
5
6//! Example types for `dispatcher` module-level documentation.
7
8use crate::{
9    dispatcher::{DispatchRule, FailureScore, Map, MatchScore},
10    self_map,
11};
12
13/// An example type representing Rust primitive type.
14#[derive(Debug, Clone, Copy)]
15pub enum DataType {
16    Float64,
17    Float32,
18    UInt8,
19    UInt16,
20    UInt32,
21    UInt64,
22    Int8,
23    Int16,
24    Int32,
25    Int64,
26}
27
28// Make `DataType` a dispatch type.
29self_map!(DataType);
30
31/// A type-domain lifting of Rust primitive types.
32pub struct Type<T>(std::marker::PhantomData<T>);
33
34/// Make `Type` reflexive to facilitate dispatch.
35impl<T: 'static> Map for Type<T> {
36    type Type<'a> = Self;
37}
38
39macro_rules! type_map {
40    ($variant:ident, $T:ty) => {
41        impl DispatchRule<DataType> for Type<$T> {
42            type Error = std::convert::Infallible;
43
44            fn try_match(from: &DataType) -> Result<MatchScore, FailureScore> {
45                match from {
46                    DataType::$variant => Ok(MatchScore(0)),
47                    _ => Err(FailureScore(u32::MAX)),
48                }
49            }
50
51            fn convert(from: DataType) -> Result<Self, Self::Error> {
52                assert!(matches!(from, DataType::$variant));
53                Ok(Self(std::marker::PhantomData))
54            }
55
56            fn description(
57                f: &mut std::fmt::Formatter<'_>,
58                from: Option<&DataType>,
59            ) -> std::fmt::Result {
60                match from {
61                    None => write!(f, "{:?}", DataType::$variant),
62                    Some(v) => {
63                        if matches!(v, DataType::$variant) {
64                            write!(f, "success")
65                        } else {
66                            write!(f, "expected {:?} but got {:?}", DataType::$variant, v)
67                        }
68                    }
69                }
70            }
71        }
72    };
73}
74
75type_map!(Float64, f64);
76type_map!(Float32, f32);
77type_map!(UInt8, u8);
78type_map!(UInt16, u16);
79type_map!(UInt32, u32);
80type_map!(UInt64, u64);
81type_map!(Int8, i8);
82type_map!(Int16, i16);
83type_map!(Int32, i32);
84type_map!(Int64, i64);