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