Writer.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. #ifndef Writer_H
  16. #define Writer_H
  17. #include <stdint.h>
  18. /**
  19. * Writer interface which writes data to a destination and fails safe rather than overflowing.
  20. */
  21. struct Writer {
  22. /**
  23. * Write some content from a buffer or other source.
  24. *
  25. * @param w the Writer which is being called.
  26. * @param toWrite a pointer to a memory location where content will be sourced from.
  27. * @param length the number of bytes to write.
  28. * @return 0 if write went well, -1 if there is no more space to write.
  29. * if a write fails then all subsequent writes will fail with the same error
  30. * so writing a large piece of content then a small footer does not require
  31. * checking if the content wrote correctly before writing the footer.
  32. */
  33. int (* const write)(struct Writer* w, const void* toWrite, unsigned long length);
  34. uint64_t bytesWritten;
  35. };
  36. #define Writer_writeGeneric(bytes) \
  37. static inline int Writer_write##bytes (struct Writer* writer, uint##bytes##_t number) \
  38. { \
  39. uint##bytes##_t num = number; \
  40. return writer->write(writer, &num, bytes/8); \
  41. }
  42. Writer_writeGeneric(8)
  43. Writer_writeGeneric(16)
  44. Writer_writeGeneric(32)
  45. Writer_writeGeneric(64)
  46. #define Writer_write(writer, bytes, amount) \
  47. ((writer)->write((writer), (bytes), (amount)))
  48. #define Writer_bytesWritten(writer) \
  49. ((writer)->bytesWritten + 0)
  50. #endif