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.

common.hpp 6.6KB

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