1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::cell::RefCell;
use std::cmp;
use std::io;
use std::io::{ErrorKind, Read, Write};
use std::rc::Rc;

use super::{TTransport, TTransportFactory};

/// Default capacity of the read buffer in bytes.
const WRITE_BUFFER_CAPACITY: usize = 4096;

/// Default capacity of the write buffer in bytes..
const DEFAULT_WBUFFER_CAPACITY: usize = 4096;

pub struct TFramedTransport {
    rbuf: Box<[u8]>,
    rpos: usize,
    rcap: usize,
    wbuf: Box<[u8]>,
    wpos: usize,
    inner: Rc<RefCell<Box<TTransport>>>,
}

impl TFramedTransport {
    pub fn new(inner: Rc<RefCell<Box<TTransport>>>) -> TFramedTransport {
        TFramedTransport::with_capacity(WRITE_BUFFER_CAPACITY, DEFAULT_WBUFFER_CAPACITY, inner)
    }

    pub fn with_capacity(read_buffer_capacity: usize, write_buffer_capacity: usize, inner: Rc<RefCell<Box<TTransport>>>) -> TFramedTransport {
        TFramedTransport {
            rbuf: vec![0; read_buffer_capacity].into_boxed_slice(),
            rpos: 0,
            rcap: 0,
            wbuf: vec![0; write_buffer_capacity].into_boxed_slice(),
            wpos: 0,
            inner: inner,
        }
    }
}

impl Read for TFramedTransport {
    fn read(&mut self, b: &mut [u8]) -> io::Result<usize> {
        if self.rcap - self.rpos == 0 {
            let message_size = try!(self.inner.borrow_mut().read_i32::<BigEndian>()) as usize;
            if message_size > self.rbuf.len() {
                return Err(
                    io::Error::new(
                        ErrorKind::Other,
                        format!("bytes to be read ({}) exceeds buffer capacity ({})", message_size, self.rbuf.len())
                    )
                );
            }
            try!(self.inner.borrow_mut().read_exact(&mut self.rbuf[..message_size]));
            self.rpos = 0;
            self.rcap = message_size as usize;
        }

        let nread = cmp::min(b.len(), self.rcap - self.rpos);
        b[..nread].clone_from_slice(&self.rbuf[self.rpos..self.rpos + nread]);
        self.rpos += nread;

        Ok(nread)
    }
}

impl Write for TFramedTransport {
    fn write(&mut self, b: &[u8]) -> io::Result<usize> {
        if b.len() > (self.wbuf.len() - self.wpos) {
            return Err(
                io::Error::new(
                    ErrorKind::Other,
                    format!("bytes to be written ({}) exceeds buffer capacity ({})", b.len(), self.wbuf.len() - self.wpos)
                )
            );
        }

        let nwrite = b.len(); // always less than available write buffer capacity
        self.wbuf[self.wpos..(self.wpos + nwrite)].clone_from_slice(&b);
        self.wpos += nwrite;
        Ok(nwrite)
    }

    fn flush(&mut self) -> io::Result<()> {
        let message_size = self.wpos;

        if let 0 = message_size {
            return Ok(())
        } else {
            try!(self.inner.borrow_mut().write_i32::<BigEndian>(message_size as i32));
        }

        let mut byte_index = 0;
        while byte_index < self.wpos {
            let nwrite = try!(self.inner.borrow_mut().write(&self.wbuf[byte_index..self.wpos]));
            byte_index = cmp::min(byte_index + nwrite, self.wpos);
        }

        self.wpos = 0;
        self.inner.borrow_mut().flush()
    }
}

/// Convenience object that can be used to create an instance of `TFramedTransport`.
pub struct TFramedTransportFactory;
impl TTransportFactory for TFramedTransportFactory {
    fn create(&self, inner: Rc<RefCell<Box<TTransport>>>) -> Box<TTransport> {
        Box::new(TFramedTransport::new(inner)) as Box<TTransport>
    }
}

#[cfg(test)]
mod tests {
//    use std::io::{Read, Write};
//
//    use super::*;
//    use ::transport::mem::TBufferTransport;

    #[test]
    fn foo() {

    }
}