helpers.h 1.8KB

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