FormatArg.h 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * Copyright 2012-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <stdexcept>
  18. #include <folly/CPortability.h>
  19. #include <folly/Conv.h>
  20. #include <folly/Likely.h>
  21. #include <folly/Portability.h>
  22. #include <folly/Range.h>
  23. #include <folly/lang/Exception.h>
  24. namespace folly {
  25. class FOLLY_EXPORT BadFormatArg : public std::invalid_argument {
  26. using invalid_argument::invalid_argument;
  27. };
  28. /**
  29. * Parsed format argument.
  30. */
  31. struct FormatArg {
  32. /**
  33. * Parse a format argument from a string. Keeps a reference to the
  34. * passed-in string -- does not copy the given characters.
  35. */
  36. explicit FormatArg(StringPiece sp)
  37. : fullArgString(sp),
  38. fill(kDefaultFill),
  39. align(Align::DEFAULT),
  40. sign(Sign::DEFAULT),
  41. basePrefix(false),
  42. thousandsSeparator(false),
  43. trailingDot(false),
  44. width(kDefaultWidth),
  45. widthIndex(kNoIndex),
  46. precision(kDefaultPrecision),
  47. presentation(kDefaultPresentation),
  48. nextKeyMode_(NextKeyMode::NONE) {
  49. if (!sp.empty()) {
  50. initSlow();
  51. }
  52. }
  53. enum class Type {
  54. INTEGER,
  55. FLOAT,
  56. OTHER,
  57. };
  58. /**
  59. * Validate the argument for the given type; throws on error.
  60. */
  61. void validate(Type type) const;
  62. /**
  63. * Throw an exception if the first argument is false. The exception
  64. * message will contain the argument string as well as any passed-in
  65. * arguments to enforce, formatted using folly::to<std::string>.
  66. */
  67. template <typename... Args>
  68. void enforce(bool v, Args&&... args) const {
  69. if (UNLIKELY(!v)) {
  70. error(std::forward<Args>(args)...);
  71. }
  72. }
  73. template <typename... Args>
  74. std::string errorStr(Args&&... args) const;
  75. template <typename... Args>
  76. [[noreturn]] void error(Args&&... args) const;
  77. /**
  78. * Full argument string, as passed in to the constructor.
  79. */
  80. StringPiece fullArgString;
  81. /**
  82. * Fill
  83. */
  84. static constexpr char kDefaultFill = '\0';
  85. char fill;
  86. /**
  87. * Alignment
  88. */
  89. enum class Align : uint8_t {
  90. DEFAULT,
  91. LEFT,
  92. RIGHT,
  93. PAD_AFTER_SIGN,
  94. CENTER,
  95. INVALID,
  96. };
  97. Align align;
  98. /**
  99. * Sign
  100. */
  101. enum class Sign : uint8_t {
  102. DEFAULT,
  103. PLUS_OR_MINUS,
  104. MINUS,
  105. SPACE_OR_MINUS,
  106. INVALID,
  107. };
  108. Sign sign;
  109. /**
  110. * Output base prefix (0 for octal, 0x for hex)
  111. */
  112. bool basePrefix;
  113. /**
  114. * Output thousands separator (comma)
  115. */
  116. bool thousandsSeparator;
  117. /**
  118. * Force a trailing decimal on doubles which could be rendered as ints
  119. */
  120. bool trailingDot;
  121. /**
  122. * Field width and optional argument index
  123. */
  124. static constexpr int kDefaultWidth = -1;
  125. static constexpr int kDynamicWidth = -2;
  126. static constexpr int kNoIndex = -1;
  127. int width;
  128. int widthIndex;
  129. /**
  130. * Precision
  131. */
  132. static constexpr int kDefaultPrecision = -1;
  133. int precision;
  134. /**
  135. * Presentation
  136. */
  137. static constexpr char kDefaultPresentation = '\0';
  138. char presentation;
  139. /**
  140. * Split a key component from "key", which must be non-empty (an exception
  141. * is thrown otherwise).
  142. */
  143. template <bool emptyOk = false>
  144. StringPiece splitKey();
  145. /**
  146. * Is the entire key empty?
  147. */
  148. bool keyEmpty() const {
  149. return nextKeyMode_ == NextKeyMode::NONE && key_.empty();
  150. }
  151. /**
  152. * Split an key component from "key", which must be non-empty and a valid
  153. * integer (an exception is thrown otherwise).
  154. */
  155. int splitIntKey();
  156. void setNextIntKey(int val) {
  157. assert(nextKeyMode_ == NextKeyMode::NONE);
  158. nextKeyMode_ = NextKeyMode::INT;
  159. nextIntKey_ = val;
  160. }
  161. void setNextKey(StringPiece val) {
  162. assert(nextKeyMode_ == NextKeyMode::NONE);
  163. nextKeyMode_ = NextKeyMode::STRING;
  164. nextKey_ = val;
  165. }
  166. private:
  167. void initSlow();
  168. template <bool emptyOk>
  169. StringPiece doSplitKey();
  170. StringPiece key_;
  171. int nextIntKey_;
  172. StringPiece nextKey_;
  173. enum class NextKeyMode {
  174. NONE,
  175. INT,
  176. STRING,
  177. };
  178. NextKeyMode nextKeyMode_;
  179. };
  180. template <typename... Args>
  181. inline std::string FormatArg::errorStr(Args&&... args) const {
  182. return to<std::string>(
  183. "invalid format argument {",
  184. fullArgString,
  185. "}: ",
  186. std::forward<Args>(args)...);
  187. }
  188. template <typename... Args>
  189. [[noreturn]] inline void FormatArg::error(Args&&... args) const {
  190. throw_exception<BadFormatArg>(errorStr(std::forward<Args>(args)...));
  191. }
  192. template <bool emptyOk>
  193. inline StringPiece FormatArg::splitKey() {
  194. enforce(nextKeyMode_ != NextKeyMode::INT, "integer key expected");
  195. return doSplitKey<emptyOk>();
  196. }
  197. template <bool emptyOk>
  198. inline StringPiece FormatArg::doSplitKey() {
  199. if (nextKeyMode_ == NextKeyMode::STRING) {
  200. nextKeyMode_ = NextKeyMode::NONE;
  201. if (!emptyOk) { // static
  202. enforce(!nextKey_.empty(), "non-empty key required");
  203. }
  204. return nextKey_;
  205. }
  206. if (key_.empty()) {
  207. if (!emptyOk) { // static
  208. error("non-empty key required");
  209. }
  210. return StringPiece();
  211. }
  212. const char* b = key_.begin();
  213. const char* e = key_.end();
  214. const char* p;
  215. if (e[-1] == ']') {
  216. --e;
  217. p = static_cast<const char*>(memchr(b, '[', size_t(e - b)));
  218. enforce(p != nullptr, "unmatched ']'");
  219. } else {
  220. p = static_cast<const char*>(memchr(b, '.', size_t(e - b)));
  221. }
  222. if (p) {
  223. key_.assign(p + 1, e);
  224. } else {
  225. p = e;
  226. key_.clear();
  227. }
  228. if (!emptyOk) { // static
  229. enforce(b != p, "non-empty key required");
  230. }
  231. return StringPiece(b, p);
  232. }
  233. inline int FormatArg::splitIntKey() {
  234. if (nextKeyMode_ == NextKeyMode::INT) {
  235. nextKeyMode_ = NextKeyMode::NONE;
  236. return nextIntKey_;
  237. }
  238. try {
  239. return to<int>(doSplitKey<true>());
  240. } catch (const std::out_of_range&) {
  241. error("integer key required");
  242. return 0; // unreached
  243. }
  244. }
  245. } // namespace folly