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.

285 lines
7.1KB

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