Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. /**
  2. * This script implements a very simple string copy that is the same length
  3. * or less bytes. The copied string only contains printable characters.
  4. */
  5.  
  6. #include <assert.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <stdbool.h>
  11.  
  12. // Duplicate the string src without any non-printable characters.
  13. char* strcpy_pc(const char* src)
  14. {
  15. assert(src != NULL);
  16.  
  17. char* dst = NULL;
  18. int src_offset = 0;
  19. int dst_offset = 0;
  20.  
  21. // To clean the string, we'll first allocate all the required memory:
  22. dst = malloc(sizeof(char) * strlen(src) + 1);
  23. assert(dst != NULL);
  24.  
  25. // Next, loop over each character and if it's permitted, add it:
  26. while (true)
  27. {
  28. // If we run over a null byte - copy it and exit.
  29. if (src[src_offset] == 0)
  30. {
  31. dst[dst_offset] = 0;
  32.  
  33. // We can now resize to the memory that's needed.
  34. dst = realloc(dst, sizeof(char) * (strlen(dst) + 1));
  35. assert(dst != NULL);
  36.  
  37. return dst;
  38. }
  39.  
  40. // Skip DEL byte (0x7F) and anything below 31 (0x1F).
  41. if (src[src_offset] < 32 || src[src_offset] == 127)
  42. {
  43. src_offset++;
  44. continue;
  45. }
  46.  
  47. // For all remaining bytes, copy them.
  48. dst[dst_offset] = src[src_offset];
  49. dst_offset++;
  50. src_offset++;
  51. }
  52. }
  53.  
  54. //
  55. // Tests
  56. //
  57.  
  58. #include "../picotest/lib/framework.h"
  59.  
  60. IT_SHOULD(do_nothing_with_an_empty_string, {
  61. char* dst = strcpy_pc("");
  62.  
  63. ASSERT_STR_EQ("", dst);
  64. })
  65.  
  66. IT_SHOULD(return_identical_string_with_no_printable_characters, {
  67. char* src = "hello";
  68. char* dst = strcpy_pc(src);
  69.  
  70. ASSERT_STR_EQ(src, dst);
  71. })
  72.  
  73. IT_SHOULD(remove_non_printable_characters_at_the_end, {
  74. char* src = "hello\x01";
  75. char* dst = strcpy_pc(src);
  76.  
  77. ASSERT_STR_EQ("hello", dst);
  78. })
  79.  
  80. IT_SHOULD(remove_non_printable_characters_anywhere_in_the_string, {
  81. char* src = "h\ae\x01llo\x01";
  82. char* dst = strcpy_pc(src);
  83.  
  84. ASSERT_STR_EQ("hello", dst);
  85. })
  86.  
  87. int main()
  88. {
  89. BEGIN_TESTING;
  90.  
  91. RUN_TEST(do_nothing_with_an_empty_string);
  92. RUN_TEST(return_identical_string_with_no_printable_characters);
  93. RUN_TEST(remove_non_printable_characters_at_the_end);
  94. RUN_TEST(remove_non_printable_characters_anywhere_in_the_string);
  95.  
  96. CONCLUDE_TESTING;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement