diskann_vector/half.rs
1/*
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT license.
4 */
5use bytemuck::{Pod, Zeroable};
6use half::f16;
7use std::convert::AsRef;
8use std::fmt;
9
10// Define the Half type as a new type over f16.
11// the memory layout of the Half struct will be the same as the memory layout of the f16 type itself.
12// The Half struct serves as a simple wrapper around the f16 type and does not introduce any additional memory overhead.
13// Test function:
14// use half::f16;
15// pub struct Half(f16);
16// fn main() {
17// let size_of_half = std::mem::size_of::<Half>();
18// let alignment_of_half = std::mem::align_of::<Half>();
19// println!("Size of Half: {} bytes", size_of_half);
20// println!("Alignment of Half: {} bytes", alignment_of_half);
21// }
22// Output:
23// Size of Half: 2 bytes
24// Alignment of Half: 2 bytes
25pub struct Half(f16);
26
27unsafe impl Pod for Half {}
28unsafe impl Zeroable for Half {}
29
30// Implement From<f32> for Half
31impl From<Half> for f32 {
32 fn from(val: Half) -> Self {
33 val.0.to_f32()
34 }
35}
36
37// Implement AsRef<f16> for Half so that it can be used in distance_compare.
38impl AsRef<f16> for Half {
39 fn as_ref(&self) -> &f16 {
40 &self.0
41 }
42}
43
44// Implement From<f32> for Half.
45impl Half {
46 pub fn from_f32(value: f32) -> Self {
47 Self(f16::from_f32(value))
48 }
49}
50
51// Implement Default for Half.
52impl Default for Half {
53 fn default() -> Self {
54 Self(f16::from_f32(Default::default()))
55 }
56}
57
58// Implement Clone for Half.
59impl Clone for Half {
60 fn clone(&self) -> Self {
61 Half(self.0)
62 }
63}
64
65// Implement PartialEq for Half.
66impl fmt::Debug for Half {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 write!(f, "Half({:?})", self.0)
69 }
70}
71
72impl Copy for Half {}
73
74impl Half {
75 pub fn to_f32(&self) -> f32 {
76 self.0.to_f32()
77 }
78}
79
80unsafe impl Send for Half {}
81unsafe impl Sync for Half {}