Open Source Tomb Raider Engine
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.

binary.cpp 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*!
  2. * \file test/binary.cpp
  3. * \brief Binary Unit Test
  4. *
  5. * \author xythobuz
  6. */
  7. #include <cstdio>
  8. #include <iostream>
  9. #include <fstream>
  10. #include "utils/binary.h"
  11. namespace {
  12. const char testData[] = {
  13. // Unsigned Integers
  14. -1, // u 8 -> 255
  15. -1, -1, // u16 -> 65535
  16. 42, 0, 0, 0, // u32 -> 42
  17. 1, 0, 0, 0, 0, 0, 0, 0, // u64 -> 1
  18. // Signed Integers
  19. -1, // 8 -> -1
  20. 92, -2, // 16 -> -420
  21. 102, -3, -1, -1, // 32 -> -666
  22. -5, -1, -1, -1,
  23. -1, -1, -1, -1 // 64 -> -5
  24. };
  25. float f1 = 3.1415926f;
  26. float f2 = 42.23f;
  27. void fillFile(const char *name) {
  28. std::ofstream file(name, std::ios_base::out | std::ios_base::binary);
  29. file.write(testData, sizeof(testData) / sizeof(testData[0]));
  30. file.write(reinterpret_cast<char *>(&f1), sizeof(f1));
  31. file.write(reinterpret_cast<char *>(&f2), sizeof(f2));
  32. }
  33. int assertImplementation(const char *exp, const char *file, int line) {
  34. std::cout << "Failed: \"" << exp << "\" in " << file << " at " << line << std::endl;
  35. return 1;
  36. }
  37. #define assert(x) if (!(x)) { return assertImplementation(#x, __FILE__, __LINE__); }
  38. int test(const char *name) {
  39. BinaryFile file(name);
  40. uint8_t a = file.readU8();
  41. uint16_t b = file.readU16();
  42. uint32_t c = file.readU32();
  43. uint64_t d = file.readU64();
  44. int8_t e = file.read8();
  45. int16_t f = file.read16();
  46. int32_t g = file.read32();
  47. int64_t h = file.read64();
  48. float i = file.readFloat();
  49. float j = file.readFloat();
  50. assert(a == 255);
  51. assert(b == 65535);
  52. assert(c == 42);
  53. assert(d == 1);
  54. assert(e == -1);
  55. assert(f == -420);
  56. assert(g == -666);
  57. assert(h == -5);
  58. assert(i == f1);
  59. assert(j == f2);
  60. return 0;
  61. }
  62. }
  63. int main(int argc, char *argv[]) {
  64. char *tmpFile = tmpnam(NULL);
  65. std::cout << "Temporary test-file: " << tmpFile << std::endl;
  66. fillFile(tmpFile);
  67. int error = test(tmpFile);
  68. remove(tmpFile);
  69. return error;
  70. }