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