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.

89 lines
2.0KB

  1. #pragma once
  2. // Include most of the C standard library for convenience
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <stdint.h>
  6. #include <assert.h>
  7. #include <string>
  8. #include <condition_variable>
  9. #include <mutex>
  10. /** Surrounds raw text with quotes
  11. Example:
  12. printf("Hello " STRINGIFY(world))
  13. will expand to
  14. printf("Hello " "world")
  15. and of course the C++ lexer/parser will then concatenate the string literals
  16. */
  17. #define STRINGIFY(x) #x
  18. /** Converts a macro to a string literal
  19. Example:
  20. #define NAME "world"
  21. printf("Hello " TOSTRING(NAME))
  22. will expand to
  23. printf("Hello " "world")
  24. */
  25. #define TOSTRING(x) STRINGIFY(x)
  26. namespace rack {
  27. ////////////////////
  28. // RNG
  29. ////////////////////
  30. uint32_t randomu32();
  31. /** Returns a uniform random float in the interval [0.0, 1.0) */
  32. float randomf();
  33. /** Returns a normal random number with mean 0 and std dev 1 */
  34. float randomNormal();
  35. ////////////////////
  36. // Helper functions
  37. ////////////////////
  38. /** Converts a printf format string and optional arguments into a std::string */
  39. std::string stringf(const char *format, ...);
  40. /** Truncates and adds "..." to a string, not exceeding `len` characters */
  41. std::string ellipsize(std::string s, size_t len);
  42. void openBrowser(std::string url);
  43. /** Threads which obtain a VIPLock will cause wait() to block for other less important threads.
  44. This does not provide the VIPs with an exclusive lock. That should be left up to another mutex shared between the less important thread.
  45. */
  46. struct VIPMutex {
  47. int count = 0;
  48. std::condition_variable cv;
  49. std::mutex countMutex;
  50. /** Blocks until there are no remaining VIPLocks */
  51. void wait() {
  52. std::unique_lock<std::mutex> lock(countMutex);
  53. while (count > 0)
  54. cv.wait(lock);
  55. }
  56. };
  57. struct VIPLock {
  58. VIPMutex &m;
  59. VIPLock(VIPMutex &m) : m(m) {
  60. std::unique_lock<std::mutex> lock(m.countMutex);
  61. m.count++;
  62. }
  63. ~VIPLock() {
  64. std::unique_lock<std::mutex> lock(m.countMutex);
  65. m.count--;
  66. lock.unlock();
  67. m.cv.notify_all();
  68. }
  69. };
  70. } // namespace rack