1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef PARTITION_ALLOC_PARTITION_ALLOC_BASE_STRINGS_CSTRING_BUILDER_H_
6 #define PARTITION_ALLOC_PARTITION_ALLOC_BASE_STRINGS_CSTRING_BUILDER_H_
7
8 #include "build/build_config.h"
9 #include "partition_alloc/partition_alloc_base/component_export.h"
10
11 #include <cstddef>
12
13 #if !BUILDFLAG(IS_WIN)
14 #include <unistd.h>
15 #endif
16
17 namespace partition_alloc::internal::base::strings {
18
19 // Similar to std::ostringstream, but creates a C string, i.e. nul-terminated
20 // char-type string, instead of std::string. To use inside memory allocation,
21 // this method must not allocate any memory with malloc, aligned_malloc,
22 // calloc, and so on.
PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE)23 class PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE) CStringBuilder {
24 public:
25 // If kBufferSize is too large, PA_LOG() and PA_BASE_*CHECK() will spend
26 // much more stack. This causes out-of-stack.
27 // ThreadTest.StartWithOptions_StackSize checks if threads can run with
28 // some specified stack size. If kBufferSize==1024u, the test will fail
29 // on 32bit bots.
30 static constexpr size_t kBufferSize = 256u;
31
32 CStringBuilder() : ptr_(buffer_) {}
33
34 CStringBuilder& operator<<(char ch);
35 CStringBuilder& operator<<(const char* text);
36 CStringBuilder& operator<<(float value);
37 CStringBuilder& operator<<(double value);
38 CStringBuilder& operator<<(int value);
39 CStringBuilder& operator<<(unsigned int value);
40 CStringBuilder& operator<<(long value);
41 CStringBuilder& operator<<(unsigned long value);
42 CStringBuilder& operator<<(long long value);
43 CStringBuilder& operator<<(unsigned long long value);
44 CStringBuilder& operator<<(const void* value);
45 CStringBuilder& operator<<(std::nullptr_t);
46 const char* c_str();
47
48 private:
49 template <typename T>
50 void PutInteger(T value);
51 void PutFloatingPoint(double value, unsigned num_digits10);
52 void PutNormalFloatingPoint(double value, unsigned num_digits10);
53 void PutText(const char* text);
54 void PutText(const char* text, size_t length);
55
56 char buffer_[kBufferSize];
57 char* ptr_;
58 };
59
60 } // namespace partition_alloc::internal::base::strings
61
62 #endif // PARTITION_ALLOC_PARTITION_ALLOC_BASE_STRINGS_CSTRING_BUILDER_H_
63