Skip to main content

arrow_cast/cast/
map.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 crate::cast::*;
19
20/// Helper function that takes a map container and casts the inner datatype.
21pub(crate) fn cast_map_values(
22    from: &MapArray,
23    to_data_type: &DataType,
24    cast_options: &CastOptions,
25    to_ordered: bool,
26) -> Result<ArrayRef, ArrowError> {
27    let DataType::Map(entries_field, _) = to_data_type else {
28        return Err(ArrowError::CastError(
29            "Internal Error: to_data_type is not a map type.".to_string(),
30        ));
31    };
32
33    let key_field = key_field(entries_field).ok_or(ArrowError::CastError(
34        "map is missing key field".to_string(),
35    ))?;
36    let value_field = value_field(entries_field).ok_or(ArrowError::CastError(
37        "map is missing value field".to_string(),
38    ))?;
39
40    let key_array = cast_with_options(from.keys(), key_field.data_type(), cast_options)?;
41    let value_array = cast_with_options(from.values(), value_field.data_type(), cast_options)?;
42
43    Ok(Arc::new(MapArray::try_new(
44        entries_field.clone(),
45        from.offsets().clone(),
46        StructArray::try_new(
47            Fields::from(vec![key_field, value_field]),
48            vec![key_array, value_array],
49            from.entries().nulls().cloned(),
50        )?,
51        from.nulls().cloned(),
52        to_ordered,
53    )?))
54}
55
56/// Gets the key field from the entries of a map.  For all other types returns None.
57pub(crate) fn key_field(entries_field: &FieldRef) -> Option<FieldRef> {
58    if let DataType::Struct(fields) = entries_field.data_type() {
59        fields.first().cloned()
60    } else {
61        None
62    }
63}
64
65/// Gets the value field from the entries of a map.  For all other types returns None.
66pub(crate) fn value_field(entries_field: &FieldRef) -> Option<FieldRef> {
67    if let DataType::Struct(fields) = entries_field.data_type() {
68        fields.get(1).cloned()
69    } else {
70        None
71    }
72}