/libnpk/tests/libnpk_streamable.cpp

http://npk.googlecode.com/ · C++ · 82 lines · 64 code · 15 blank · 3 comment · 17 complexity · 7688768ee32d45ea92f754832486a5e6 MD5 · raw file

  1. #include "testutil.h"
  2. #include <sys/stat.h>
  3. #include <npk.h>
  4. #include <npk_dev.h>
  5. int libnpk_streamable( int argc, char * argv [] )
  6. {
  7. int teakey[4] = {1,2,3,4};
  8. NPK_PACKAGE pack;
  9. NPK_ENTITY entity;
  10. // create a pack
  11. CHECK( NPK_SUCCESS == npk_package_alloc( &pack, teakey ) );
  12. CHECK( NPK_SUCCESS == npk_package_add_file( pack, "sample.txt", "sample.txt", &entity ) );
  13. CHECK( NPK_SUCCESS == npk_package_add_file( pack, "sample.txt", "tea.txt", &entity ) );
  14. CHECK( NPK_SUCCESS == npk_entity_set_flag( entity, NPK_ENTITY_ENCRYPT_TEA ) );
  15. CHECK( NPK_SUCCESS == npk_package_add_file( pack, "sample.txt", "xxtea.txt", &entity ) );
  16. CHECK( NPK_SUCCESS == npk_entity_set_flag( entity, NPK_ENTITY_ENCRYPT_XXTEA ) );
  17. CHECK( NPK_SUCCESS == npk_package_add_file( pack, "sample.txt", "zip.txt", &entity ) );
  18. CHECK( NPK_SUCCESS == npk_entity_set_flag( entity, NPK_ENTITY_COMPRESS_ZLIB ) );
  19. CHECK( NPK_SUCCESS == npk_package_save( pack, "foo.npk", true ) );
  20. npk_package_close( pack );
  21. // simulate download
  22. int rh = open( "foo.npk", O_RDONLY | O_BINARY );
  23. size_t filesize = npk_seek( rh, 0, SEEK_END );
  24. npk_seek( rh, 0, SEEK_SET );
  25. int wh = open( "foo_2.npk", O_CREAT | O_RDWR | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE );
  26. // validation
  27. std::string entityNames[4] = { "sample.txt", "tea.txt", "xxtea.txt", "zip.txt" };
  28. pack = 0;
  29. int i = 0;
  30. size_t offset = 0;
  31. char buf[255];
  32. while( offset < filesize )
  33. {
  34. size_t r = rand()%16;
  35. if( r + offset > filesize )
  36. r = filesize - offset;
  37. read( rh, &buf, sizeof(char)*r );
  38. write( wh, buf, sizeof(char)*r );
  39. printf( "offset %ld, reading %ld byte(s).\n", offset, r );
  40. offset += r;
  41. if( pack == 0 )
  42. {
  43. pack = npk_package_open( "foo_2.npk", teakey );
  44. if( pack != 0 )
  45. printf( " package loaded.\n" );
  46. }
  47. else
  48. {
  49. NPK_ENTITY entity = npk_package_get_entity( pack, entityNames[i].c_str() );
  50. CHECK( entity != NULL );
  51. NPK_SIZE size = npk_entity_get_size( entity );
  52. if( npk_entity_is_ready( entity ) )
  53. {
  54. printf( " entity %s ready.\n", entityNames[i].c_str() );
  55. void* buf = malloc( size );
  56. CHECK( npk_entity_read( entity, buf ) );
  57. CHECK_EQUAL_STR_WITH_FILE( (const char*)buf, "sample.txt" );
  58. free( buf );
  59. ++i;
  60. }
  61. }
  62. }
  63. npk_package_close( pack );
  64. close( wh );
  65. close( rh );
  66. return 0;
  67. }