Mark Slee | 8d7e1f6 | 2006-06-07 06:48:56 +0000 | [diff] [blame] | 1 | #include "TBufferedTransport.h" |
| 2 | using std::string; |
| 3 | |
| 4 | uint32_t TBufferedTransport::read(uint8_t* buf, uint32_t len) { |
| 5 | uint32_t need = len; |
| 6 | |
| 7 | // We don't have enough data yet |
| 8 | if (rLen_-rPos_ < need) { |
| 9 | // Copy out whatever we have |
| 10 | if (rLen_ > 0) { |
| 11 | memcpy(buf, rBuf_+rPos_, rLen_-rPos_); |
| 12 | need -= rLen_-rPos_; |
| 13 | buf += rLen_-rPos_; |
| 14 | } |
| 15 | // Get more from underlying transport up to buffer size |
| 16 | rLen_ = transport_->read(rBuf_, rBufSize_); |
| 17 | rPos_ = 0; |
| 18 | } |
| 19 | |
| 20 | // Hand over whatever we have |
| 21 | uint32_t give = need; |
| 22 | if (rLen_-rPos_ < give) { |
| 23 | give = rLen_-rPos_; |
| 24 | } |
| 25 | memcpy(buf, rBuf_+rPos_, give); |
| 26 | rPos_ += give; |
| 27 | need -= give; |
| 28 | return (len - need); |
| 29 | } |
| 30 | |
| 31 | void TBufferedTransport::write(const uint8_t* buf, uint32_t len) { |
| 32 | if (len == 0) { |
| 33 | return; |
| 34 | } |
| 35 | |
| 36 | if (len + wLen_ >= wBufSize_) { |
| 37 | uint32_t copy = wBufSize_ - wLen_; |
| 38 | memcpy(wBuf_ + wLen_, buf, copy); |
| 39 | transport_->write(wBuf_, wBufSize_); |
| 40 | |
| 41 | wLen_ = len - copy; |
| 42 | if (wLen_ > 0) { |
| 43 | memcpy(wBuf_, buf+copy, wLen_); |
| 44 | } |
| 45 | } else { |
| 46 | memcpy(wBuf_+wLen_, buf, len); |
| 47 | wLen_ += len; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | void TBufferedTransport::flush() { |
| 52 | // Write out any data waiting in the write buffer |
| 53 | if (wLen_ > 0) { |
| 54 | transport_->write(wBuf_, wLen_); |
| 55 | wLen_ = 0; |
| 56 | } |
| 57 | |
| 58 | // Flush the underlying transport |
| 59 | transport_->flush(); |
| 60 | } |