LexMemoryBufferInput.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * @file LexMemoryBufferInput.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Object that can be used by a lexer to read input from a memory buffer.
  25. */
  26. #ifndef BADVPN_PREDICATE_LEXMEMORYBUFFERINPUT_H
  27. #define BADVPN_PREDICATE_LEXMEMORYBUFFERINPUT_H
  28. #include <string.h>
  29. #include <misc/debug.h>
  30. typedef struct {
  31. char *buf;
  32. int len;
  33. int pos;
  34. int error;
  35. } LexMemoryBufferInput;
  36. static void LexMemoryBufferInput_Init (LexMemoryBufferInput *input, char *buf, int len)
  37. {
  38. input->buf = buf;
  39. input->len = len;
  40. input->pos = 0;
  41. input->error = 0;
  42. }
  43. static int LexMemoryBufferInput_Read (LexMemoryBufferInput *input, char *dest, int len)
  44. {
  45. ASSERT(dest)
  46. ASSERT(len > 0)
  47. if (input->pos >= input->len) {
  48. return 0;
  49. }
  50. int to_read = input->len - input->pos;
  51. if (to_read > len) {
  52. to_read = len;
  53. }
  54. memcpy(dest, input->buf + input->pos, to_read);
  55. input->pos += to_read;
  56. return to_read;
  57. }
  58. static void LexMemoryBufferInput_SetError (LexMemoryBufferInput *input)
  59. {
  60. input->error = 1;
  61. }
  62. static int LexMemoryBufferInput_HasError (LexMemoryBufferInput *input)
  63. {
  64. return input->error;
  65. }
  66. #endif