MGStreamAdapter.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // MGStreamAdapter.cpp
  2. #include "MGStreamAdapter.h"
  3. mg_buf::mg_buf(struct mg_connection* _conn) : conn(_conn) {
  4. setp(buffer, buffer + BUF_SIZE - 1); // -1 to leave space for overflow '\0'
  5. }
  6. mg_buf::int_type mg_buf::overflow(int_type c) {
  7. if (c != EOF) {
  8. *pptr() = c;
  9. pbump(1);
  10. }
  11. if (flush_buffer() == EOF) {
  12. return EOF;
  13. }
  14. return c;
  15. }
  16. int mg_buf::flush_buffer() {
  17. int len = int(pptr() - pbase());
  18. if (mg_write(conn, buffer, len) != len) {
  19. return EOF;
  20. }
  21. pbump(-len); // reset put pointer accordingly
  22. return len;
  23. }
  24. int mg_buf::sync() {
  25. if (flush_buffer() == EOF) {
  26. return -1; // return -1 on error
  27. }
  28. return 0;
  29. }
  30. MGStreamAdapter::MGStreamAdapter(struct mg_connection* _conn)
  31. : std::ostream(&buf), buf(_conn) {
  32. rdbuf(&buf); // set the custom streambuf
  33. }
  34. mg_read_buf::mg_read_buf(struct mg_connection* _conn) : conn(_conn) {
  35. setg(buffer + BUF_SIZE, // beginning of putback area
  36. buffer + BUF_SIZE, // read position
  37. buffer + BUF_SIZE); // end position
  38. }
  39. mg_read_buf::int_type mg_read_buf::underflow() {
  40. if (gptr() < egptr()) { // buffer not exhausted
  41. return traits_type::to_int_type(*gptr());
  42. }
  43. char* base = buffer;
  44. char* start = base;
  45. if (eback() == base) { // true when this isn't the first fill
  46. // Make arrangements for putback characters
  47. std::memmove(base, egptr() - 2, 2);
  48. start += 2;
  49. }
  50. // Read new characters
  51. int n = mg_read(conn, start, buffer + BUF_SIZE - start);
  52. if (n == 0) {
  53. return traits_type::eof();
  54. }
  55. // Set buffer pointers
  56. setg(base, start, start + n);
  57. // Return next character
  58. return traits_type::to_int_type(*gptr());
  59. }
  60. MGInputStreamAdapter::MGInputStreamAdapter(struct mg_connection* _conn)
  61. : std::istream(&buf), buf(_conn) {
  62. rdbuf(&buf); // set the custom streambuf
  63. }