1/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16// See docs in ../ops/parse_ops.cc.
17
18#include <errno.h>
19#include <string>
20
21#include "tensorflow/core/framework/kernel_def_builder.h"
22#include "tensorflow/core/framework/op_kernel.h"
23#include "tensorflow/core/framework/tensor.h"
24#include "tensorflow/core/lib/core/errors.h"
25#include "tensorflow/core/lib/core/status.h"
26#include "tensorflow/core/lib/strings/numbers.h"
27
28namespace tensorflow {
29
30static constexpr char kErrorMessage[] =
31 "StringToNumberOp could not correctly convert string: ";
32
33template <typename OutputType>
34class StringToNumberOp : public OpKernel {
35 public:
36 using OpKernel::OpKernel;
37
38 void Compute(OpKernelContext* context) override {
39 // This is not a deep copy of the input tensor; they will share the same
40 // underlying storage.
41 const Tensor* input_tensor;
42 OP_REQUIRES_OK(context, context->input("string_tensor", &input_tensor));
43 const auto& input_flat = input_tensor->flat<tstring>();
44
45 Tensor* output_tensor = nullptr;
46 OP_REQUIRES_OK(context,
47 context->allocate_output("output", input_tensor->shape(),
48 &output_tensor));
49 auto output_flat = output_tensor->flat<OutputType>();
50
51 for (int i = 0; i < input_flat.size(); ++i) {
52 OP_REQUIRES(
53 context,
54 strings::SafeStringToNumeric<OutputType>(input_flat(i),
55 &output_flat(i)),
56 errors::InvalidArgument(kErrorMessage, input_flat(i).c_str()));
57 }
58 }
59};
60
61// Registers the currently supported output types.
62#define REGISTER(type) \
63 REGISTER_KERNEL_BUILDER(Name("StringToNumber") \
64 .Device(DEVICE_CPU) \
65 .TypeConstraint<type>("out_type"), \
66 StringToNumberOp<type>)
67REGISTER(float);
68REGISTER(double);
69REGISTER(int32);
70REGISTER(int64_t);
71#undef REGISTER
72
73} // namespace tensorflow
74