Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support StringArray creation from String Vec #522

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions arrow/src/array/array_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,10 @@ impl<OffsetSize: StringOffsetSizeTrait> GenericStringArray<OffsetSize> {
Self::from(data)
}

pub(crate) fn from_vec(v: Vec<&str>) -> Self {
pub(crate) fn from_vec<Ptr>(v: Vec<Ptr>) -> Self
where
Ptr: AsRef<str>,
{
let mut offsets =
MutableBuffer::new((v.len() + 1) * std::mem::size_of::<OffsetSize>());
let mut values = MutableBuffer::new(0);
Expand All @@ -158,9 +161,9 @@ impl<OffsetSize: StringOffsetSizeTrait> GenericStringArray<OffsetSize> {
offsets.push(length_so_far);

for s in &v {
length_so_far += OffsetSize::from_usize(s.len()).unwrap();
length_so_far += OffsetSize::from_usize(s.as_ref().len()).unwrap();
offsets.push(length_so_far);
values.extend_from_slice(s.as_bytes());
values.extend_from_slice(s.as_ref().as_bytes());
}
let array_data = ArrayData::builder(OffsetSize::DATA_TYPE)
.len(v.len())
Expand Down Expand Up @@ -327,6 +330,14 @@ impl<OffsetSize: StringOffsetSizeTrait> From<Vec<&str>>
}
}

impl<OffsetSize: StringOffsetSizeTrait> From<Vec<String>>
for GenericStringArray<OffsetSize>
{
fn from(v: Vec<String>) -> Self {
GenericStringArray::<OffsetSize>::from_vec(v)
}
}

/// An array where each element is a variable-sized sequence of bytes representing a string
/// whose maximum length (in bytes) is represented by a i32.
///
Expand Down Expand Up @@ -530,4 +541,15 @@ mod tests {
// but the actual number of items in the array should be 10
assert_eq!(string_array.len(), 10);
}

#[test]
fn test_string_array_from_string_vec() {
let data = vec!["Foo".to_owned(), "Bar".to_owned(), "Baz".to_owned()];
let array = StringArray::from(data);

assert_eq!(array.len(), 3);
assert_eq!(array.value(0), "Foo");
assert_eq!(array.value(1), "Bar");
assert_eq!(array.value(2), "Baz");
}
}