Functions.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /// @file
  2. /// Contains misc functions
  3. #ifndef ANKI_UTIL_FUNCTIONS_H
  4. #define ANKI_UTIL_FUNCTIONS_H
  5. #include "anki/util/StdTypes.h"
  6. #include <string>
  7. namespace anki {
  8. /// @addtogroup util
  9. /// @{
  10. /// @addtogroup misc
  11. /// @{
  12. /// Pick a random number from min to max
  13. extern I32 randRange(I32 min, I32 max);
  14. /// Pick a random number from min to max
  15. extern U32 randRange(U32 min, U32 max);
  16. /// Pick a random number from min to max
  17. extern F32 randRange(F32 min, F32 max);
  18. /// Pick a random number from min to max
  19. extern F64 randRange(F64 min, F64 max);
  20. extern F32 randFloat(F32 max);
  21. /// Align memory
  22. /// @param alignment The bytes of alignment
  23. /// @param size The value to align
  24. inline PtrSize alignSizeRoundUp(PtrSize alignment, PtrSize size)
  25. {
  26. return (size + alignment - 1) & ~(alignment - 1);
  27. }
  28. /// Get the size in bytes of a vector
  29. template<typename Vec>
  30. inline PtrSize getVectorSizeInBytes(const Vec& v)
  31. {
  32. return v.size() * sizeof(typename Vec::value_type);
  33. }
  34. /// Trim a string
  35. inline std::string trimString(const std::string& str, const char* what = " ")
  36. {
  37. std::string out = str;
  38. out.erase(0, out.find_first_not_of(what));
  39. out.erase(out.find_last_not_of(what) + 1);
  40. return out;
  41. }
  42. /// Replace substring. Substitute occurances of @a from into @a to inside the
  43. /// @a str string
  44. extern std::string replaceAllString(const std::string& str,
  45. const std::string& from, const std::string& to);
  46. /// Delete a pointer properly
  47. template<typename T>
  48. inline void propperDelete(T*& x)
  49. {
  50. typedef char TypeMustBeComplete[sizeof(T) ? 1 : -1];
  51. (void) sizeof(TypeMustBeComplete);
  52. delete x;
  53. x = nullptr;
  54. }
  55. /// Delete a pointer properly
  56. template<typename T>
  57. inline void propperDeleteArray(T*& x)
  58. {
  59. typedef char TypeMustBeComplete[sizeof(T) ? 1 : -1];
  60. (void) sizeof(TypeMustBeComplete);
  61. delete[] x;
  62. x = nullptr;
  63. }
  64. /// A simple template trick to remove the pointer from one type
  65. ///
  66. /// Example:
  67. /// @code
  68. /// double a = 1234.456;
  69. /// RemovePointer<decltype(&a)>::Type b = a;
  70. /// @endcode
  71. /// The b is of type double
  72. template<typename T>
  73. struct RemovePointer;
  74. template<typename T>
  75. struct RemovePointer<T*>
  76. {
  77. typedef T Type;
  78. };
  79. /// @}
  80. /// @}
  81. } // end namespace anki
  82. #endif