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 
18 // Cast types to boolean
19 
20 #include "arrow/array/builder_primitive.h"
21 #include "arrow/compute/kernels/common.h"
22 #include "arrow/compute/kernels/scalar_cast_internal.h"
23 #include "arrow/util/value_parsing.h"
24 
25 namespace arrow {
26 
27 using internal::ParseValue;
28 
29 namespace compute {
30 namespace internal {
31 
32 struct IsNonZero {
33   template <typename OutValue, typename Arg0Value>
Callarrow::compute::internal::IsNonZero34   static OutValue Call(KernelContext*, Arg0Value val) {
35     return val != 0;
36   }
37 };
38 
39 struct ParseBooleanString {
40   template <typename OutValue, typename Arg0Value>
Callarrow::compute::internal::ParseBooleanString41   static OutValue Call(KernelContext* ctx, Arg0Value val) {
42     bool result = false;
43     if (ARROW_PREDICT_FALSE(!ParseValue<BooleanType>(val.data(), val.size(), &result))) {
44       ctx->SetStatus(Status::Invalid("Failed to parse value: ", val));
45     }
46     return result;
47   }
48 };
49 
GetBooleanCasts()50 std::vector<std::shared_ptr<CastFunction>> GetBooleanCasts() {
51   auto func = std::make_shared<CastFunction>("cast_boolean", Type::BOOL);
52   AddCommonCasts(Type::BOOL, boolean(), func.get());
53   AddZeroCopyCast(Type::BOOL, boolean(), boolean(), func.get());
54 
55   for (const auto& ty : NumericTypes()) {
56     ArrayKernelExec exec =
57         GenerateNumeric<applicator::ScalarUnary, BooleanType, IsNonZero>(*ty);
58     DCHECK_OK(func->AddKernel(ty->id(), {ty}, boolean(), exec));
59   }
60   for (const auto& ty : BaseBinaryTypes()) {
61     ArrayKernelExec exec = GenerateVarBinaryBase<applicator::ScalarUnaryNotNull,
62                                                  BooleanType, ParseBooleanString>(*ty);
63     DCHECK_OK(func->AddKernel(ty->id(), {ty}, boolean(), exec));
64   }
65   return {func};
66 }
67 
68 }  // namespace internal
69 }  // namespace compute
70 }  // namespace arrow
71