swab.c 1.7 KB

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