Skip to main content

common_function/scalars/vector/
impl_conv.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::borrow::Cow;
16
17use common_query::error::{InvalidFuncArgsSnafu, Result};
18use datafusion_common::ScalarValue;
19
20/// Convert a string or binary literal to a vector literal.
21pub fn as_veclit(arg: &ScalarValue) -> Result<Option<Cow<'_, [f32]>>> {
22    match arg {
23        ScalarValue::Binary(b) | ScalarValue::BinaryView(b) => {
24            b.as_ref().map(|x| binlit_as_veclit(x)).transpose()
25        }
26        ScalarValue::Utf8(s) | ScalarValue::Utf8View(s) => s
27            .as_ref()
28            .map(|x| parse_veclit_from_strlit(x).map(Cow::Owned))
29            .transpose(),
30        _ => InvalidFuncArgsSnafu {
31            err_msg: format!("Unsupported data type: {:?}", arg.data_type()),
32        }
33        .fail(),
34    }
35}
36
37/// Convert a u8 slice to a vector literal.
38pub fn binlit_as_veclit(bytes: &[u8]) -> Result<Cow<'_, [f32]>> {
39    if !bytes.len().is_multiple_of(size_of::<f32>()) {
40        return InvalidFuncArgsSnafu {
41            err_msg: format!("Invalid binary length of vector: {}", bytes.len()),
42        }
43        .fail();
44    }
45
46    if cfg!(target_endian = "little") && bytes.as_ptr().align_offset(align_of::<f32>()) == 0 {
47        // The length is a multiple of four, the pointer is aligned, and every f32 bit
48        // pattern is valid. The borrowed slice cannot outlive the input bytes.
49        Ok(unsafe {
50            let vec = std::slice::from_raw_parts(
51                bytes.as_ptr() as *const f32,
52                bytes.len() / std::mem::size_of::<f32>(),
53            );
54            Cow::Borrowed(vec)
55        })
56    } else {
57        let v = bytes
58            .as_chunks::<{ std::mem::size_of::<f32>() }>()
59            .0
60            .iter()
61            .map(|chunk| f32::from_le_bytes(*chunk))
62            .collect::<Vec<f32>>();
63        Ok(Cow::Owned(v))
64    }
65}
66
67/// Parse a string literal to a vector literal.
68/// Valid inputs are strings like "[1.0, 2.0, 3.0]".
69pub fn parse_veclit_from_strlit(s: &str) -> Result<Vec<f32>> {
70    let trimmed = s.trim();
71    if !trimmed.starts_with('[') || !trimmed.ends_with(']') {
72        return InvalidFuncArgsSnafu {
73            err_msg: format!(
74                "Failed to parse {s} to Vector value: not properly enclosed in brackets"
75            ),
76        }
77        .fail();
78    }
79    let content = trimmed[1..trimmed.len() - 1].trim();
80    if content.is_empty() {
81        return Ok(Vec::new());
82    }
83
84    content
85        .split(',')
86        .map(|s| s.trim().parse::<f32>())
87        .collect::<std::result::Result<_, _>>()
88        .map_err(|e| {
89            InvalidFuncArgsSnafu {
90                err_msg: format!("Failed to parse {s} to Vector value: {e}"),
91            }
92            .build()
93        })
94}
95
96/// Convert a vector literal to a binary literal.
97pub fn veclit_to_binlit(vec: &[f32]) -> Vec<u8> {
98    if cfg!(target_endian = "little") {
99        unsafe {
100            std::slice::from_raw_parts(vec.as_ptr() as *const u8, std::mem::size_of_val(vec))
101                .to_vec()
102        }
103    } else {
104        let mut bytes = Vec::with_capacity(std::mem::size_of_val(vec));
105        for e in vec {
106            bytes.extend_from_slice(&e.to_le_bytes());
107        }
108        bytes
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn test_parse_veclit_from_strlit() {
118        let result = parse_veclit_from_strlit("[1.0, 2.0, 3.0]").unwrap();
119        assert_eq!(result, vec![1.0, 2.0, 3.0]);
120
121        let result = parse_veclit_from_strlit("[]").unwrap();
122        assert_eq!(result, Vec::<f32>::new());
123
124        let result = parse_veclit_from_strlit("[1.0, a, 3.0]");
125        assert!(result.is_err());
126    }
127
128    #[test]
129    fn test_binlit_as_veclit_alignment() {
130        #[repr(align(4))]
131        struct Aligned([u8; 16]);
132        let mut storage = Aligned([0; 16]);
133        let values = [1.25, -2.5, 3.0];
134        let bytes = veclit_to_binlit(&values);
135        for offset in 0..4 {
136            storage.0[offset..offset + bytes.len()].copy_from_slice(&bytes);
137            let result = binlit_as_veclit(&storage.0[offset..offset + bytes.len()]).unwrap();
138            assert_eq!(result.as_ref(), values);
139            assert_eq!(
140                matches!(result, Cow::Borrowed(_)),
141                cfg!(target_endian = "little") && offset == 0
142            );
143            assert!(
144                binlit_as_veclit(&storage.0[offset..offset])
145                    .unwrap()
146                    .is_empty()
147            );
148        }
149    }
150
151    #[test]
152    fn test_binlit_as_veclit() {
153        let vec = &[1.0, 2.0, 3.0];
154        let bytes = veclit_to_binlit(vec);
155        let result = binlit_as_veclit(&bytes).unwrap();
156        assert_eq!(result.as_ref(), vec);
157
158        let invalid_bytes = [0, 0, 128];
159        let result = binlit_as_veclit(&invalid_bytes);
160        assert!(result.is_err());
161    }
162}