Attempt to create a new DictionaryArray with a specified keys (indexes into the dictionary) and values (dictionary) array. # Errors Returns an error if any `keys[i] >= values.len() || keys[i] < 0`
(keys: PrimitiveArray<K>, values: ArrayRef)
| 287 | /// |
| 288 | /// Returns an error if any `keys[i] >= values.len() || keys[i] < 0` |
| 289 | pub fn try_new(keys: PrimitiveArray<K>, values: ArrayRef) -> Result<Self, ArrowError> { |
| 290 | let data_type = DataType::Dictionary( |
| 291 | Box::new(keys.data_type().clone()), |
| 292 | Box::new(values.data_type().clone()), |
| 293 | ); |
| 294 | |
| 295 | // // we can skip the validating the keys if they are all null |
| 296 | let all_null = keys.null_count() == keys.len(); |
| 297 | |
| 298 | if !all_null { |
| 299 | let zero = K::Native::usize_as(0); |
| 300 | let values_len = values.len(); |
| 301 | |
| 302 | if let Some((idx, v)) = keys.values().iter().enumerate().find(|(idx, v)| { |
| 303 | (v.is_lt(zero) || v.as_usize() >= values_len) && keys.is_valid(*idx) |
| 304 | }) { |
| 305 | return Err(ArrowError::InvalidArgumentError(format!( |
| 306 | "Invalid dictionary key {v:?} at index {idx}, expected 0 <= key < {values_len}", |
| 307 | ))); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | Ok(Self { |
| 312 | data_type, |
| 313 | keys, |
| 314 | values, |
| 315 | is_ordered: false, |
| 316 | }) |
| 317 | } |
| 318 | |
| 319 | /// Create a new [`Scalar`] from `value` |
| 320 | pub fn new_scalar<T: Array + 'static>(value: Scalar<T>) -> Scalar<Self> { |