Elffuss BraidHub

kikocis/lancedb public

main · 1.5 KiBRawPermalink
1// Copyright 2024 Lance Developers.
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::io::Cursor;
16use std::ops::Deref;
17
18use arrow_array::RecordBatch;
19use arrow_ipc::reader::FileReader;
20use arrow_ipc::writer::FileWriter;
21use arrow_schema::SchemaRef;
22
23use crate::error::Result;
24
25pub fn arrow_buffer_to_record_batch(slice: &[u8]) -> Result<(Vec<RecordBatch>, SchemaRef)> {
26 let mut batches: Vec<RecordBatch> = Vec::new();
27 let file_reader = FileReader::try_new(Cursor::new(slice), None)?;
28 let schema = file_reader.schema();
29 for b in file_reader {
30 let record_batch = b?;
31 batches.push(record_batch);
32 }
33 Ok((batches, schema))
34}
35
36pub fn record_batch_to_buffer(batches: Vec<RecordBatch>) -> Result<Vec<u8>> {
37 if batches.is_empty() {
38 return Ok(Vec::new());
39 }
40
41 let schema = batches.first().unwrap().schema();
42 let mut fr = FileWriter::try_new(Vec::new(), schema.deref())?;
43 for batch in batches.iter() {
44 fr.write(batch)?
45 }
46 fr.finish()?;
47 Ok(fr.into_inner()?)
48}