You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

274 lines
6.8KB

  1. #pragma once
  2. // Include most of the C stdlib for convenience
  3. #include <cstddef>
  4. #include <cstdlib>
  5. #include <cstdio>
  6. #include <cstdint>
  7. #include <cinttypes>
  8. #include <cstdarg>
  9. #include <climits>
  10. #include <cmath>
  11. #include <cstring>
  12. #include <cassert>
  13. // Include some of the C++ stdlib for convenience
  14. #include <string>
  15. #include <stdexcept>
  16. /** Attribute for deprecated functions and symbols.
  17. E.g.
  18. DEPRECATED void foo();
  19. */
  20. #if defined __GNUC__ || defined __clang__
  21. #define DEPRECATED __attribute__((deprecated))
  22. #elif defined _MSC_VER
  23. #define DEPRECATED __declspec(deprecated)
  24. #endif
  25. /** Attribute for private functions and symbols not intended to be used by plugins.
  26. When #including rack.hpp, attempting to call PRIVATE functions or access variables will result in a compile-time error.
  27. */
  28. #ifndef PRIVATE
  29. #define PRIVATE
  30. #endif
  31. /** Concatenates two literals or two macros
  32. Example:
  33. #define COUNT 42
  34. CONCAT(myVariable, COUNT)
  35. expands to
  36. myVariable42
  37. */
  38. #define CONCAT_LITERAL(x, y) x ## y
  39. #define CONCAT(x, y) CONCAT_LITERAL(x, y)
  40. /** Surrounds raw text with quotes
  41. Example:
  42. #define NAME "world"
  43. printf("Hello " TOSTRING(NAME))
  44. expands to
  45. printf("Hello " "world")
  46. and of course the C++ lexer/parser then concatenates the string literals.
  47. */
  48. #define TOSTRING_LITERAL(x) #x
  49. #define TOSTRING(x) TOSTRING_LITERAL(x)
  50. /** Produces the length of a static array in number of elements */
  51. #define LENGTHOF(arr) (sizeof(arr) / sizeof((arr)[0]))
  52. /** Reserve space for `count` enums starting with `name`.
  53. Example:
  54. enum Foo {
  55. ENUMS(BAR, 14),
  56. BAZ
  57. };
  58. `BAR + 0` to `BAR + 13` is reserved. `BAZ` has a value of 14.
  59. */
  60. #define ENUMS(name, count) name, name ## _LAST = name + (count) - 1
  61. /** References binary files compiled into the program.
  62. For example, to include a file "Test.dat" directly into your program binary, add
  63. BINARIES += Test.dat
  64. to your Makefile and declare
  65. BINARY(Test_dat);
  66. at the root of a .c or .cpp source file. Note that special characters are replaced with "_". Then use
  67. BINARY_START(Test_dat)
  68. BINARY_END(Test_dat)
  69. to reference the data beginning and end as a void* array, and
  70. BINARY_SIZE(Test_dat)
  71. to get its size in bytes.
  72. */
  73. #if defined ARCH_MAC
  74. // Use output from `xxd -i`
  75. #define BINARY(sym) extern unsigned char sym[]; extern unsigned int sym##_len
  76. #define BINARY_START(sym) ((const void*) sym)
  77. #define BINARY_END(sym) ((const void*) sym + sym##_len)
  78. #define BINARY_SIZE(sym) (sym##_len)
  79. #else
  80. #define BINARY(sym) extern char _binary_##sym##_start, _binary_##sym##_end, _binary_##sym##_size
  81. #define BINARY_START(sym) ((const void*) &_binary_##sym##_start)
  82. #define BINARY_END(sym) ((const void*) &_binary_##sym##_end)
  83. // The symbol "_binary_##sym##_size" doesn't seem to be valid after a plugin is dynamically loaded, so simply take the difference between the two addresses.
  84. #define BINARY_SIZE(sym) ((size_t) (&_binary_##sym##_end - &_binary_##sym##_start))
  85. #endif
  86. /** Helpful user-defined literals for specifying exact integer and float types.
  87. Usage examples:
  88. 42_i8
  89. -4242_u16
  90. 0x4a2b_i32
  91. 0b11010111000000_u64
  92. 42_f32
  93. 4.2e-4_f64
  94. */
  95. inline int8_t operator"" _i8(unsigned long long x) {return x;}
  96. inline int16_t operator"" _i16(unsigned long long x) {return x;}
  97. inline int32_t operator"" _i32(unsigned long long x) {return x;}
  98. inline int64_t operator"" _i64(unsigned long long x) {return x;}
  99. inline uint8_t operator"" _u8(unsigned long long x) {return x;}
  100. inline uint16_t operator"" _u16(unsigned long long x) {return x;}
  101. inline uint32_t operator"" _u32(unsigned long long x) {return x;}
  102. inline uint64_t operator"" _u64(unsigned long long x) {return x;}
  103. inline float operator"" _f32(long double x) {return x;}
  104. inline float operator"" _f32(unsigned long long x) {return x;}
  105. inline double operator"" _f64(long double x) {return x;}
  106. inline double operator"" _f64(unsigned long long x) {return x;}
  107. #if defined ARCH_WIN
  108. // wchar_t on Windows should be 2 bytes
  109. static_assert(sizeof(wchar_t) == 2);
  110. // Windows C standard functions are ASCII-8 instead of UTF-8, so redirect these functions to wrappers which convert to UTF-8
  111. #define fopen fopen_u8
  112. extern "C" {
  113. FILE* fopen_u8(const char* filename, const char* mode);
  114. }
  115. namespace std {
  116. using ::fopen_u8;
  117. }
  118. #endif
  119. /** Root namespace for the Rack API */
  120. namespace rack {
  121. /** Casts a primitive, preserving its bits instead of converting. */
  122. template <typename To, typename From>
  123. To bitCast(From from) {
  124. static_assert(sizeof(From) == sizeof(To), "Types must be the same size");
  125. To to;
  126. // This is optimized out
  127. std::memcpy(&to, &from, sizeof(From));
  128. return to;
  129. }
  130. /** C#-style property constructor
  131. Example:
  132. Foo *foo = construct<Foo>(&Foo::greeting, "Hello world", &Foo::legs, 2);
  133. */
  134. template <typename T>
  135. T* construct() {
  136. return new T;
  137. }
  138. template <typename T, typename F, typename V, typename... Args>
  139. T* construct(F f, V v, Args... args) {
  140. T* o = construct<T>(args...);
  141. o->*f = v;
  142. return o;
  143. }
  144. /** Defers running code until the scope is destructed
  145. From http://www.gingerbill.org/article/defer-in-cpp.html.
  146. Example:
  147. file = fopen(...);
  148. DEFER({
  149. fclose(file);
  150. });
  151. */
  152. template <typename F>
  153. struct DeferWrapper {
  154. F f;
  155. DeferWrapper(F f) : f(f) {}
  156. ~DeferWrapper() {
  157. f();
  158. }
  159. };
  160. template <typename F>
  161. DeferWrapper<F> deferWrapper(F f) {
  162. return DeferWrapper<F>(f);
  163. }
  164. #define DEFER(code) auto CONCAT(_defer_, __COUNTER__) = rack::deferWrapper([&]() code)
  165. /** An exception explicitly thrown by Rack or a Rack plugin.
  166. Can be subclassed to throw/catch specific custom exceptions.
  167. */
  168. struct Exception : std::exception {
  169. std::string msg;
  170. // Attribute index 1 refers to `Exception*` argument so use 2.
  171. __attribute__((format(printf, 2, 3)))
  172. Exception(const char* format, ...);
  173. Exception(const std::string& msg) : msg(msg) {}
  174. const char* what() const noexcept override {
  175. return msg.c_str();
  176. }
  177. };
  178. /** Given a std::map, returns the value of the given key, or returns `def` if the key doesn't exist.
  179. Does *not* add the default value to the map.
  180. Posted to https://stackoverflow.com/a/63683271/272642.
  181. Example:
  182. std::map<std::string, int> m;
  183. int v = get(m, "a", 3);
  184. // v is 3 because the key "a" does not exist
  185. int w = get(m, "a");
  186. // w is 0 because no default value is given, so it assumes the default int.
  187. */
  188. template <typename C>
  189. typename C::mapped_type get(const C& m, const typename C::key_type& key, const typename C::mapped_type& def = typename C::mapped_type()) {
  190. typename C::const_iterator it = m.find(key);
  191. if (it == m.end())
  192. return def;
  193. return it->second;
  194. }
  195. // config
  196. extern const std::string APP_NAME;
  197. extern const std::string APP_EDITION;
  198. extern const std::string APP_EDITION_NAME;
  199. extern const std::string APP_VERSION_MAJOR;
  200. extern const std::string APP_VERSION;
  201. extern const std::string APP_OS;
  202. extern const std::string API_URL;
  203. } // namespace rack
  204. // Logger depends on common.hpp, but it is handy to include it along with common.hpp.
  205. #include <logger.hpp>