ArrayWriter.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 "ArrayWriter.h"
  16. #include "util/Bits.h"
  17. #include "util/Identity.h"
  18. struct ArrayWriter_context {
  19. struct Writer generic;
  20. char* beginPointer;
  21. char* pointer;
  22. char* endPointer;
  23. int returnCode;
  24. Identity
  25. };
  26. /** @see Writer->write() */
  27. static int write(struct Writer* writer, const void* toWrite, unsigned long length)
  28. {
  29. struct ArrayWriter_context* context = Identity_cast((struct ArrayWriter_context*) writer);
  30. /* If there was a previous failure then don't allow any more writing. */
  31. if (context->returnCode != 0) {
  32. return context->returnCode;
  33. }
  34. /* Prove that it doesn't run off the end of the buffer or roll over. */
  35. if (context->pointer + length > context->endPointer
  36. || context->pointer + length < context->pointer)
  37. {
  38. context->returnCode = -1;
  39. return -1;
  40. }
  41. Bits_memcpy(context->pointer, toWrite, length);
  42. context->pointer += length;
  43. context->generic.bytesWritten += length;
  44. return 0;
  45. }
  46. /** @see ArrayWriter.h */
  47. struct Writer* ArrayWriter_new(void* writeToBuffer,
  48. unsigned long length,
  49. struct Allocator* alloc)
  50. {
  51. struct ArrayWriter_context* context = Allocator_clone(alloc, (&(struct ArrayWriter_context) {
  52. .generic = {
  53. .write = write
  54. },
  55. .beginPointer = writeToBuffer,
  56. .pointer = writeToBuffer,
  57. .endPointer = (char*) writeToBuffer + length
  58. }));
  59. Identity_set(context);
  60. return &context->generic;
  61. }