swab.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <unistd.h>
  2. int main(int argc, char ** argv) {
  3. const char source[] = {0, 1, 2, 3, 4, 5, 6};
  4. char destination[] = {0, 0, 0, 0, 0, 0};
  5. const char flipped_source[] = {1, 0, 3, 2, 5, 4};
  6. const char first_two_source_bytes_flipped[] = {1, 0};
  7. swab(source, destination, /* nbytes */ -3);
  8. for (int i = 0; i < sizeof(destination); ++i) {
  9. if (destination[i] != 0) {
  10. puts("If nbytes is negative destionation shouldn't be modified");
  11. return 1;
  12. }
  13. }
  14. swab(source, destination, /* nbytes */ 0);
  15. for (int i = 0; i < sizeof(destination); ++i) {
  16. if (destination[i] != 0) {
  17. puts("If nbytes is zero destionation shouldn't be modified");
  18. return 1;
  19. }
  20. }
  21. swab(source, destination, /* nbytes */ 3);
  22. for (int i = 0; i < sizeof(first_two_source_bytes_flipped); ++i) {
  23. if (destination[i] != first_two_source_bytes_flipped[i]) {
  24. puts("copied bytes don't match expected values");
  25. return 1;
  26. }
  27. }
  28. // If nbytes is not even it's not specified what should happen to the
  29. // last byte so the third byte in destination is not checked.
  30. for (int i = sizeof(first_two_source_bytes_flipped) + 1; i < sizeof(destination); ++i) {
  31. if (destination[i] != 0) {
  32. puts("swab modified too many bytes in destination");
  33. return 1;
  34. }
  35. }
  36. swab(source, destination, /* nbytes */ sizeof(destination));
  37. for (int i = 0; i < sizeof(destination); ++i) {
  38. if (destination[i] != flipped_source[i]) {
  39. puts("copied bytes don't match expected values");
  40. return 1;
  41. }
  42. }
  43. return 0;
  44. }