ArrayReader.c 2.3 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 <https://www.gnu.org/licenses/>.
  14. */
  15. #include "io/ArrayReader.h"
  16. #include "util/Bits.h"
  17. #include "util/Identity.h"
  18. struct ArrayReader_context {
  19. struct Reader generic;
  20. const char* pointer;
  21. const char* endPointer;
  22. Identity
  23. };
  24. /** @see Reader->read() */
  25. static int read(struct Reader* reader, void* readInto, unsigned long length)
  26. {
  27. struct ArrayReader_context* context = Identity_check((struct ArrayReader_context*) reader);
  28. // Prove that it doesn't run off the end of the buffer or roll over.
  29. if (context->pointer + length > context->endPointer
  30. || context->pointer + length < context->pointer)
  31. {
  32. return -1;
  33. }
  34. if (length == 0) {
  35. // Allow peaking.
  36. *((char*)readInto) = *context->pointer;
  37. return 0;
  38. }
  39. Bits_memcpy(readInto, context->pointer, length);
  40. context->pointer += length;
  41. reader->bytesRead += length;
  42. return 0;
  43. }
  44. /** @see Reader->skip() */
  45. static void skip(struct Reader* reader, unsigned long byteCount)
  46. {
  47. struct ArrayReader_context* context = Identity_check((struct ArrayReader_context*) reader);
  48. context->pointer += byteCount;
  49. reader->bytesRead += byteCount;
  50. }
  51. /** @see ArrayReader.h */
  52. struct Reader* ArrayReader_new(const void* bufferToRead,
  53. unsigned long length,
  54. struct Allocator* alloc)
  55. {
  56. struct ArrayReader_context* context = Allocator_clone(alloc, (&(struct ArrayReader_context) {
  57. .generic = {
  58. .read = read,
  59. .skip = skip
  60. },
  61. .pointer = bufferToRead,
  62. .endPointer = (char*) bufferToRead + length
  63. }));
  64. Identity_set(context);
  65. return &context->generic;
  66. }