P4C
The P4 Compiler
 
Loading...
Searching...
No Matches
stringify.h
1/*
2Copyright 2013-present Barefoot Networks, Inc.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17/* -*-c++-*- */
18
19#ifndef LIB_STRINGIFY_H_
20#define LIB_STRINGIFY_H_
21
22#include <stdint.h>
23
24#include <cstdarg>
25
26#include "big_int_util.h"
27#include "cstring.h"
28
29// convert values to cstrings
30namespace Util {
31// Check whether type T has a method with signature
32// cstring toString() const
33template <typename T>
34class HasToString final {
35 template <typename U, cstring (U::*)() const>
36 struct Check;
37 template <typename U>
38 static char func(Check<U, &U::toString> *);
39 template <typename U>
40 static int func(...);
41
42 public:
43 typedef HasToString type;
44 enum { value = sizeof(func<T>(0)) == sizeof(char) };
45};
46
47template <typename T, typename = decltype(std::to_string(std::declval<T>()))>
48cstring toString(T value) {
49 return std::to_string(value);
50}
51
52template <typename T>
53auto toString(const T &value) -> typename std::enable_if_t<HasToString<T>::value, cstring> {
54 return value.toString();
55}
56
57template <typename T>
58auto toString(T &value) -> typename std::enable_if_t<HasToString<T>::value, cstring> {
59 return value.toString();
60}
61
62template <typename T>
63auto toString(const T *value) -> typename std::enable_if_t<HasToString<T>::value, cstring> {
64 return value->toString();
65}
66
67template <typename T>
68auto toString(T *value) -> typename std::enable_if_t<HasToString<T>::value, cstring> {
69 return value->toString();
70}
71
72cstring toString(bool value);
73cstring toString(std::string value);
74cstring toString(const char *value);
75cstring toString(cstring value);
76cstring toString(std::string_view value);
78cstring toString(const big_int value, unsigned width, bool sign, unsigned int base = 10);
79cstring toString(const void *value);
80
81// printf into a string
82cstring printf_format(const char *fmt_str, ...);
83// vprintf into a string
84cstring vprintf_format(const char *fmt_str, va_list ap);
85char DigitToChar(int digit);
86} // namespace Util
87#endif /* LIB_STRINGIFY_H_ */
Definition stringify.h:34
Definition cstring.h:72