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 #include "arrow/util/formatting.h"
19 #include "arrow/util/config.h"
20 #include "arrow/util/double_conversion.h"
21 #include "arrow/util/logging.h"
22
23 namespace arrow {
24
25 using util::double_conversion::DoubleToStringConverter;
26
27 static constexpr int kMinBufferSize = DoubleToStringConverter::kBase10MaximalLength + 1;
28
29 namespace internal {
30 namespace detail {
31
32 const char digit_pairs[] =
33 "0001020304050607080910111213141516171819"
34 "2021222324252627282930313233343536373839"
35 "4041424344454647484950515253545556575859"
36 "6061626364656667686970717273747576777879"
37 "8081828384858687888990919293949596979899";
38
39 } // namespace detail
40
41 struct FloatToStringFormatter::Impl {
Implarrow::internal::FloatToStringFormatter::Impl42 Impl()
43 : converter_(DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN, "inf", "nan",
44 'e', -6, 10, 6, 0) {}
45
46 DoubleToStringConverter converter_;
47 };
48
FloatToStringFormatter()49 FloatToStringFormatter::FloatToStringFormatter() : impl_(new Impl()) {}
50
~FloatToStringFormatter()51 FloatToStringFormatter::~FloatToStringFormatter() {}
52
FormatFloat(float v,char * out_buffer,int out_size)53 int FloatToStringFormatter::FormatFloat(float v, char* out_buffer, int out_size) {
54 DCHECK_GE(out_size, kMinBufferSize);
55 // StringBuilder checks bounds in debug mode for us
56 util::double_conversion::StringBuilder builder(out_buffer, out_size);
57 bool result = impl_->converter_.ToShortestSingle(v, &builder);
58 DCHECK(result);
59 ARROW_UNUSED(result);
60 return builder.position();
61 }
62
FormatFloat(double v,char * out_buffer,int out_size)63 int FloatToStringFormatter::FormatFloat(double v, char* out_buffer, int out_size) {
64 DCHECK_GE(out_size, kMinBufferSize);
65 util::double_conversion::StringBuilder builder(out_buffer, out_size);
66 bool result = impl_->converter_.ToShortest(v, &builder);
67 DCHECK(result);
68 ARROW_UNUSED(result);
69 return builder.position();
70 }
71
72 } // namespace internal
73 } // namespace arrow
74