benc_serializeString_test.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "memory/Allocator.h"
  16. #include "memory/MallocAllocator.h"
  17. #include "io/Reader.h"
  18. #include "io/ArrayReader.h"
  19. #include "io/Writer.h"
  20. #include "io/ArrayWriter.h"
  21. #include "benc/String.h"
  22. #include "benc/serialization/BencSerializer.h"
  23. #include "benc/serialization/standard/StandardBencSerializer.h"
  24. #include "util/Assert.h"
  25. #include <stdio.h>
  26. static int expect(char* str, struct Writer* writer, struct Reader* reader)
  27. {
  28. int ret = 0;
  29. char buffer[32];
  30. Writer_write(writer, "\0", 1);
  31. Reader_read(reader, buffer, CString_strlen(str) + 1);
  32. if (CString_strcmp(str, buffer) != 0) {
  33. printf("Expected %s\n Got %s\n", str, buffer);
  34. return -1;
  35. }
  36. return ret;
  37. }
  38. static void testSerialize(struct Writer* writer, struct Reader* reader)
  39. {
  40. Assert_true(!StandardBencSerializer_get()->serializeString(writer, String_CONST("hello")));
  41. Assert_true(!expect("5:hello", writer, reader));
  42. Assert_true(!StandardBencSerializer_get()->serializeString(writer, String_CONST("")));
  43. Assert_true(!expect("0:", writer, reader));
  44. }
  45. static void testParse(struct Writer* w, struct Reader* r, struct Allocator* alloc)
  46. {
  47. char* badBenc = "d2:aq21:RouterModule_pingNode4:argsd4:path39:fcd9:6a75:6c9c7:timeouti4000ee"
  48. "6:cookie0:4:hash64:09c6bcd1482df339757c99bbc5e796192968a28562f701fb53a57ed6"
  49. "e26b15511:q4:auth4:txid19:43866780dc455e15619e";
  50. Writer_write(w, badBenc, CString_strlen(badBenc)+1);
  51. Dict dict;
  52. Assert_true(StandardBencSerializer_get()->parseDictionary(r, alloc, &dict));
  53. }
  54. int main()
  55. {
  56. char out[512];
  57. struct Allocator* alloc = MallocAllocator_new(1<<20);
  58. struct Writer* writer = ArrayWriter_new(out, 512, alloc);
  59. struct Reader* reader = ArrayReader_new(out, 512, alloc);
  60. testSerialize(writer, reader);
  61. testParse(writer, reader, alloc);
  62. Allocator_free(alloc);
  63. return 0;
  64. }