helpers.h 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef LIGHT_HELPERS_H
  2. #define LIGHT_HELPERS_H
  3. #include <stdbool.h>
  4. /* Clamps x(value) between y(min) and z(max) in a nested ternary operation */
  5. #define LIGHT_CLAMP(val, min, max) \
  6. (val < min \
  7. ? light_log_clamp_min(min) \
  8. : (val > max \
  9. ? light_log_clamp_max(max) \
  10. : val ))
  11. /* Verbosity levels:
  12. * 0 - No output
  13. * 1 - Errors
  14. * 2 - Errors, warnings
  15. * 3 - Errors, warnings, notices
  16. */
  17. typedef enum {
  18. LIGHT_ERROR_LEVEL = 1,
  19. LIGHT_WARN_LEVEL,
  20. LIGHT_NOTE_LEVEL
  21. } light_loglevel_t;
  22. light_loglevel_t light_loglevel;
  23. #define LIGHT_LOG(lvl, fp, fmt, args...) \
  24. if (light_loglevel >= lvl) \
  25. fprintf(fp, "%s:%d:" fmt, __FILE__, __LINE__, ##args)
  26. #define LIGHT_NOTE(fmt, args...) LIGHT_LOG(LIGHT_NOTE_LEVEL, stdout, "NOTE:" fmt, ##args)
  27. #define LIGHT_WARN(fmt, args...) LIGHT_LOG(LIGHT_WARN_LEVEL, stderr, "WARN:" fmt, ##args)
  28. #define LIGHT_ERR(fmt, args...) LIGHT_LOG(LIGHT_ERROR_LEVEL, stderr, "!ERR:" fmt, ##args)
  29. #define LIGHT_MEMERR() LIGHT_ERR("memory error");
  30. #define LIGHT_PERMLOG(act, log) \
  31. do { \
  32. log("could not open '%s' for " act, filename); \
  33. log("Verify it exists with the right permissions"); \
  34. } while (0)
  35. #define LIGHT_PERMERR(x) LIGHT_PERMLOG(x, LIGHT_ERR)
  36. #define LIGHT_PERMWARN(x) LIGHT_PERMLOG(x, LIGHT_WARN)
  37. bool light_file_write_val (char const *filename, unsigned long val);
  38. bool light_file_read_val (char const *filename, unsigned long *val);
  39. bool light_file_is_writable (char const *filename);
  40. bool light_file_is_readable (char const *filename);
  41. unsigned long light_log_clamp_min(unsigned long min);
  42. unsigned long light_log_clamp_max(unsigned long max);
  43. double light_percent_clamp(double percent);
  44. #endif /* LIGHT_HELPERS_H */