arrow_data/byte_view.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use arrow_buffer::Buffer;
19use arrow_schema::ArrowError;
20
21/// Helper to access views of [`GenericByteViewArray`] (`StringViewArray` and
22/// `BinaryViewArray`) where the length is greater than 12 bytes.
23///
24/// See Also:
25/// * [`GenericByteViewArray`] for more information on the layout of the views.
26/// * [`validate_binary_view`] and [`validate_string_view`] to validate
27///
28/// # Example: Create a new u128 view
29///
30/// ```rust
31/// # use arrow_data::ByteView;;
32/// // Create a view for a string of length 20
33/// // first four bytes are "Rust"
34/// // stored in buffer 3
35/// // at offset 42
36/// let prefix = "Rust";
37/// let view = ByteView::new(20, prefix.as_bytes())
38/// .with_buffer_index(3)
39/// .with_offset(42);
40///
41/// // create the final u128
42/// let v = view.as_u128();
43/// assert_eq!(v, 0x2a000000037473755200000014);
44/// ```
45///
46/// # Example: decode a `u128` into its constituent fields
47/// ```rust
48/// # use arrow_data::ByteView;
49/// // Convert a u128 to a ByteView
50/// // See validate_{string,binary}_view functions to validate
51/// let v = ByteView::from(0x2a000000037473755200000014);
52///
53/// assert_eq!(v.length, 20);
54/// assert_eq!(v.prefix, 0x74737552);
55/// assert_eq!(v.buffer_index, 3);
56/// assert_eq!(v.offset, 42);
57/// ```
58///
59/// [`GenericByteViewArray`]: https://docs.rs/arrow/latest/arrow/array/struct.GenericByteViewArray.html
60#[derive(Debug, Copy, Clone, Default)]
61#[repr(C)]
62pub struct ByteView {
63 /// The length of the string/bytes.
64 pub length: u32,
65 /// First 4 bytes of string/bytes data.
66 pub prefix: u32,
67 /// The buffer index.
68 pub buffer_index: u32,
69 /// The offset into the buffer.
70 pub offset: u32,
71}
72
73impl ByteView {
74 /// Construct a [`ByteView`] for data `length` of bytes with the specified prefix.
75 ///
76 /// See example on [`ByteView`] docs
77 ///
78 /// Notes:
79 /// * the length should always be greater than 12 (Data less than 12
80 /// bytes is stored as an inline view)
81 /// * buffer and offset are set to `0`
82 ///
83 /// # Panics
84 /// If the prefix is not exactly 4 bytes
85 #[inline]
86 pub fn new(length: u32, prefix: &[u8]) -> Self {
87 debug_assert!(length > 12);
88 Self {
89 length,
90 prefix: u32::from_le_bytes(prefix.try_into().unwrap()),
91 buffer_index: 0,
92 offset: 0,
93 }
94 }
95
96 /// Set the [`Self::buffer_index`] field
97 #[inline]
98 pub fn with_buffer_index(mut self, buffer_index: u32) -> Self {
99 self.buffer_index = buffer_index;
100 self
101 }
102
103 /// Set the [`Self::offset`] field
104 #[inline]
105 pub fn with_offset(mut self, offset: u32) -> Self {
106 self.offset = offset;
107 self
108 }
109
110 #[inline(always)]
111 /// Convert `ByteView` to `u128` by concatenating the fields
112 pub fn as_u128(self) -> u128 {
113 (self.length as u128)
114 | ((self.prefix as u128) << 32)
115 | ((self.buffer_index as u128) << 64)
116 | ((self.offset as u128) << 96)
117 }
118}
119
120impl From<u128> for ByteView {
121 #[inline]
122 fn from(value: u128) -> Self {
123 Self {
124 length: value as u32,
125 prefix: (value >> 32) as u32,
126 buffer_index: (value >> 64) as u32,
127 offset: (value >> 96) as u32,
128 }
129 }
130}
131
132impl From<ByteView> for u128 {
133 #[inline]
134 fn from(value: ByteView) -> Self {
135 value.as_u128()
136 }
137}
138
139/// Validates the combination of `views` and `buffers` is a valid BinaryView
140pub fn validate_binary_view(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
141 validate_view_impl(views, buffers, |_, _| Ok(()))
142}
143
144/// Validates the combination of `views` and `buffers` is a valid StringView
145pub fn validate_string_view(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
146 validate_view_impl(views, buffers, |idx, b| {
147 std::str::from_utf8(b).map_err(|e| {
148 ArrowError::InvalidArgumentError(format!(
149 "Encountered non-UTF-8 data at index {idx}: {e}"
150 ))
151 })?;
152 Ok(())
153 })
154}
155
156fn validate_view_impl<F>(views: &[u128], buffers: &[Buffer], f: F) -> Result<(), ArrowError>
157where
158 F: Fn(usize, &[u8]) -> Result<(), ArrowError>,
159{
160 for (idx, v) in views.iter().enumerate() {
161 let len = *v as u32;
162 if len <= 12 {
163 if len < 12 && (v >> (32 + len * 8)) != 0 {
164 return Err(ArrowError::InvalidArgumentError(format!(
165 "View at index {idx} contained non-zero padding for string of length {len}",
166 )));
167 }
168 f(idx, &v.to_le_bytes()[4..4 + len as usize])?;
169 } else {
170 let view = ByteView::from(*v);
171 let data = buffers.get(view.buffer_index as usize).ok_or_else(|| {
172 ArrowError::InvalidArgumentError(format!(
173 "Invalid buffer index at {idx}: got index {} but only has {} buffers",
174 view.buffer_index,
175 buffers.len()
176 ))
177 })?;
178
179 let start = view.offset as usize;
180 let end = start + len as usize;
181 let b = data.get(start..end).ok_or_else(|| {
182 ArrowError::InvalidArgumentError(format!(
183 "Invalid buffer slice at {idx}: got {start}..{end} but buffer {} has length {}",
184 view.buffer_index,
185 data.len()
186 ))
187 })?;
188
189 if !b.starts_with(&view.prefix.to_le_bytes()) {
190 return Err(ArrowError::InvalidArgumentError(
191 "Mismatch between embedded prefix and data".to_string(),
192 ));
193 }
194
195 f(idx, b)?;
196 }
197 }
198 Ok(())
199}