Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
fp_roundtrip_conv.h
Go to the documentation of this file.
1// Copyright 2010-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// Classes and function to convert floating point numbers to string so that no
15// information is lost (i.e. that we can make a round trip from double to string
16// and back to double without losing data).
17#ifndef OR_TOOLS_UTIL_FP_ROUNDTRIP_CONV_H_
18#define OR_TOOLS_UTIL_FP_ROUNDTRIP_CONV_H_
19
20#include <ostream>
21#include <string>
22
23#include "absl/base/attributes.h"
24#include "absl/status/statusor.h"
25#include "absl/strings/string_view.h"
26
27namespace operations_research {
28
29// True if the plateform supports `double` to std::to_chars().
30//
31// std::to_chars() for double is not yet supported on Emscripten, Android and
32// iOS; they only implement std::to_chars() for integers.
33ABSL_CONST_INIT extern const bool kStdToCharsDoubleIsSupported;
34
35// Formatter using std::to_chars() to print a `double` so that a round trip
36// conversion back to double will result in the same number (using
37// absl::from_chars()). One exception are NaNs that may not round trip
38// (i.e. multiple NaNs could end up being printed the same).
39//
40// Usage:
41//
42// const double x = ...;
43// LOG(INFO) << "x: " << RoundTripDoubleFormat(x);
44//
45// const std::string x_str =
46// absl::StrCat("x: ", RoundTripDoubleFormat(x));
47//
48// ASSIGN_OR_RETURN(const double y,
49// RoundTripDoubleFormat::Parse(x_str));
50//
51// Note that some operating systems do not support std::to_chars() for double
52// yet but only implement it for integers (see kStdToCharsDoubleIsSupported). On
53// those operating systems, a formatting equivalent to using "%.*g" with
54// max_digits10 precision is used.
56 public:
57 explicit RoundTripDoubleFormat(const double value) : value_(value) {}
58
59 // Prints the formatted double to the provided stream.
60 friend std::ostream& operator<<(std::ostream& out,
61 const RoundTripDoubleFormat& format);
62
63 // Prints the formatted double to the provided sink.
64 //
65 // PERFORMANCE: the current implementation uses ToString() as the code has to
66 // be templated and thus inlined. It could be optimized a bit by using the
67 // same implementation pattern as operator<< (i.e. a stack-allocated buffer)
68 // but this would require exposing some internals here. It may not even be
69 // that bad for most practical case for the rationale explained in ToString()
70 // documentation.
71 template <typename Sink>
72 friend void AbslStringify(Sink& sink, const RoundTripDoubleFormat& format) {
73 sink.Append(RoundTripDoubleFormat::ToString(format.value_));
74 }
75
76 // Returns a string with the provided double formatted.
77 //
78 // Prefer using operator<< when possible (with LOG(), StatusBuilder,
79 // std::cout...) since it avoids allocating a temporary string.
80 //
81 // PERFORMANCE: operator<< may be noticeably faster in some extreme cases,
82 // especially in non-64bit platforms or when value is in (-∞, -1e+100] or in
83 // [-1e-100, 0). This is because the string won't fit in
84 // small-string-optimization buffer, and will thus need a heap memory
85 // allocation which is slow.
86 static std::string ToString(double value);
87
88 // Parses the input string with absl::from_chars(), returning an error if the
89 // input string does not start with a number or has extra characters after
90 // it. It also fails if the number can't fit in a `double`.
91 //
92 // This function offers a round-trip from string printed/built by this
93 // formatter.
94 static absl::StatusOr<double> Parse(absl::string_view str_value);
95
96 private:
97 const double value_;
98};
99
100} // namespace operations_research
101
102#endif // OR_TOOLS_UTIL_FP_ROUNDTRIP_CONV_H_
static absl::StatusOr< double > Parse(absl::string_view str_value)
friend void AbslStringify(Sink &sink, const RoundTripDoubleFormat &format)
friend std::ostream & operator<<(std::ostream &out, const RoundTripDoubleFormat &format)
Prints the formatted double to the provided stream.
static std::string ToString(double value)
int64_t value
In SWIG mode, we don't want anything besides these top-level includes.
ABSL_CONST_INIT const bool kStdToCharsDoubleIsSupported