blob: d78d2f7a195c7461cbfafe47a31eff581fb8fb17 [file] [log] [blame]
Allen George8b96bfb2016-11-02 08:01:08 -04001// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
Allen George8b96bfb2016-11-02 08:01:08 -040019use std::cmp;
20use std::io;
21use std::io::{ErrorKind, Read, Write};
Allen George8b96bfb2016-11-02 08:01:08 -040022
Allen George0e22c362017-01-30 07:15:00 -050023use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory};
Allen George8b96bfb2016-11-02 08:01:08 -040024
25/// Default capacity of the read buffer in bytes.
Allen George0e22c362017-01-30 07:15:00 -050026const READ_CAPACITY: usize = 4096;
Allen George8b96bfb2016-11-02 08:01:08 -040027
Allen George0e22c362017-01-30 07:15:00 -050028/// Default capacity of the write buffer in bytes.
29const WRITE_CAPACITY: usize = 4096;
Allen George8b96bfb2016-11-02 08:01:08 -040030
Allen George0e22c362017-01-30 07:15:00 -050031/// Transport that reads framed messages.
Allen George8b96bfb2016-11-02 08:01:08 -040032///
Allen George0e22c362017-01-30 07:15:00 -050033/// A `TFramedReadTransport` maintains a fixed-size internal read buffer.
34/// On a call to `TFramedReadTransport::read(...)` one full message - both
35/// fixed-length header and bytes - is read from the wrapped channel and
36/// buffered. Subsequent read calls are serviced from the internal buffer
37/// until it is exhausted, at which point the next full message is read
38/// from the wrapped channel.
Allen George8b96bfb2016-11-02 08:01:08 -040039///
40/// # Examples
41///
Allen George0e22c362017-01-30 07:15:00 -050042/// Create and use a `TFramedReadTransport`.
Allen George8b96bfb2016-11-02 08:01:08 -040043///
44/// ```no_run
Allen George0e22c362017-01-30 07:15:00 -050045/// use std::io::Read;
46/// use thrift::transport::{TFramedReadTransport, TTcpChannel};
Allen George8b96bfb2016-11-02 08:01:08 -040047///
Allen George0e22c362017-01-30 07:15:00 -050048/// let mut c = TTcpChannel::new();
49/// c.open("localhost:9090").unwrap();
Allen George8b96bfb2016-11-02 08:01:08 -040050///
Allen George0e22c362017-01-30 07:15:00 -050051/// let mut t = TFramedReadTransport::new(c);
Allen George8b96bfb2016-11-02 08:01:08 -040052///
Allen George8b96bfb2016-11-02 08:01:08 -040053/// t.read(&mut vec![0u8; 1]).unwrap();
Allen George8b96bfb2016-11-02 08:01:08 -040054/// ```
Allen George0e22c362017-01-30 07:15:00 -050055#[derive(Debug)]
56pub struct TFramedReadTransport<C>
57where
58 C: Read,
59{
60 buf: Box<[u8]>,
61 pos: usize,
62 cap: usize,
63 chan: C,
Allen George8b96bfb2016-11-02 08:01:08 -040064}
65
Allen George0e22c362017-01-30 07:15:00 -050066impl<C> TFramedReadTransport<C>
67where
68 C: Read,
69{
Allen George8b96bfb2016-11-02 08:01:08 -040070 /// Create a `TFramedTransport` with default-sized internal read and
Allen George0e22c362017-01-30 07:15:00 -050071 /// write buffers that wraps the given `TIoChannel`.
72 pub fn new(channel: C) -> TFramedReadTransport<C> {
73 TFramedReadTransport::with_capacity(READ_CAPACITY, channel)
Allen George8b96bfb2016-11-02 08:01:08 -040074 }
75
76 /// Create a `TFramedTransport` with an internal read buffer of size
Allen George0e22c362017-01-30 07:15:00 -050077 /// `read_capacity` and an internal write buffer of size
78 /// `write_capacity` that wraps the given `TIoChannel`.
79 pub fn with_capacity(read_capacity: usize, channel: C) -> TFramedReadTransport<C> {
80 TFramedReadTransport {
81 buf: vec![0; read_capacity].into_boxed_slice(),
82 pos: 0,
83 cap: 0,
84 chan: channel,
Allen George8b96bfb2016-11-02 08:01:08 -040085 }
86 }
87}
88
Allen George0e22c362017-01-30 07:15:00 -050089impl<C> Read for TFramedReadTransport<C>
90where
91 C: Read,
92{
Allen George8b96bfb2016-11-02 08:01:08 -040093 fn read(&mut self, b: &mut [u8]) -> io::Result<usize> {
Allen George0e22c362017-01-30 07:15:00 -050094 if self.cap - self.pos == 0 {
95 let message_size = self.chan.read_i32::<BigEndian>()? as usize;
96 if message_size > self.buf.len() {
97 return Err(
98 io::Error::new(
99 ErrorKind::Other,
100 format!(
101 "bytes to be read ({}) exceeds buffer \
Allen George8b96bfb2016-11-02 08:01:08 -0400102 capacity ({})",
Allen George0e22c362017-01-30 07:15:00 -0500103 message_size,
104 self.buf.len()
105 ),
106 ),
107 );
Allen George8b96bfb2016-11-02 08:01:08 -0400108 }
Allen George0e22c362017-01-30 07:15:00 -0500109 self.chan.read_exact(&mut self.buf[..message_size])?;
110 self.pos = 0;
111 self.cap = message_size as usize;
Allen George8b96bfb2016-11-02 08:01:08 -0400112 }
113
Allen George0e22c362017-01-30 07:15:00 -0500114 let nread = cmp::min(b.len(), self.cap - self.pos);
115 b[..nread].clone_from_slice(&self.buf[self.pos..self.pos + nread]);
116 self.pos += nread;
Allen George8b96bfb2016-11-02 08:01:08 -0400117
118 Ok(nread)
119 }
120}
121
Allen George0e22c362017-01-30 07:15:00 -0500122/// Factory for creating instances of `TFramedReadTransport`.
123#[derive(Default)]
124pub struct TFramedReadTransportFactory;
125
126impl TFramedReadTransportFactory {
127 pub fn new() -> TFramedReadTransportFactory {
128 TFramedReadTransportFactory {}
129 }
130}
131
132impl TReadTransportFactory for TFramedReadTransportFactory {
133 /// Create a `TFramedReadTransport`.
134 fn create(&self, channel: Box<Read + Send>) -> Box<TReadTransport + Send> {
135 Box::new(TFramedReadTransport::new(channel))
136 }
137}
138
139/// Transport that writes framed messages.
140///
141/// A `TFramedWriteTransport` maintains a fixed-size internal write buffer. All
142/// writes are made to this buffer and are sent to the wrapped channel only
143/// when `TFramedWriteTransport::flush()` is called. On a flush a fixed-length
144/// header with a count of the buffered bytes is written, followed by the bytes
145/// themselves.
146///
147/// # Examples
148///
149/// Create and use a `TFramedWriteTransport`.
150///
151/// ```no_run
152/// use std::io::Write;
153/// use thrift::transport::{TFramedWriteTransport, TTcpChannel};
154///
155/// let mut c = TTcpChannel::new();
156/// c.open("localhost:9090").unwrap();
157///
158/// let mut t = TFramedWriteTransport::new(c);
159///
160/// t.write(&[0x00]).unwrap();
161/// t.flush().unwrap();
162/// ```
163#[derive(Debug)]
164pub struct TFramedWriteTransport<C>
165where
166 C: Write,
167{
168 buf: Box<[u8]>,
169 pos: usize,
170 channel: C,
171}
172
173impl<C> TFramedWriteTransport<C>
174where
175 C: Write,
176{
177 /// Create a `TFramedTransport` with default-sized internal read and
178 /// write buffers that wraps the given `TIoChannel`.
179 pub fn new(channel: C) -> TFramedWriteTransport<C> {
180 TFramedWriteTransport::with_capacity(WRITE_CAPACITY, channel)
181 }
182
183 /// Create a `TFramedTransport` with an internal read buffer of size
184 /// `read_capacity` and an internal write buffer of size
185 /// `write_capacity` that wraps the given `TIoChannel`.
186 pub fn with_capacity(write_capacity: usize, channel: C) -> TFramedWriteTransport<C> {
187 TFramedWriteTransport {
188 buf: vec![0; write_capacity].into_boxed_slice(),
189 pos: 0,
190 channel: channel,
191 }
192 }
193}
194
195impl<C> Write for TFramedWriteTransport<C>
196where
197 C: Write,
198{
Allen George8b96bfb2016-11-02 08:01:08 -0400199 fn write(&mut self, b: &[u8]) -> io::Result<usize> {
Allen George0e22c362017-01-30 07:15:00 -0500200 if b.len() > (self.buf.len() - self.pos) {
201 return Err(
202 io::Error::new(
203 ErrorKind::Other,
204 format!(
205 "bytes to be written ({}) exceeds buffer \
Allen George8b96bfb2016-11-02 08:01:08 -0400206 capacity ({})",
Allen George0e22c362017-01-30 07:15:00 -0500207 b.len(),
208 self.buf.len() - self.pos
209 ),
210 ),
211 );
Allen George8b96bfb2016-11-02 08:01:08 -0400212 }
213
214 let nwrite = b.len(); // always less than available write buffer capacity
Allen George0e22c362017-01-30 07:15:00 -0500215 self.buf[self.pos..(self.pos + nwrite)].clone_from_slice(b);
216 self.pos += nwrite;
Allen George8b96bfb2016-11-02 08:01:08 -0400217 Ok(nwrite)
218 }
219
220 fn flush(&mut self) -> io::Result<()> {
Allen George0e22c362017-01-30 07:15:00 -0500221 let message_size = self.pos;
Allen George8b96bfb2016-11-02 08:01:08 -0400222
223 if let 0 = message_size {
224 return Ok(());
225 } else {
Allen George0e22c362017-01-30 07:15:00 -0500226 self.channel
227 .write_i32::<BigEndian>(message_size as i32)?;
Allen George8b96bfb2016-11-02 08:01:08 -0400228 }
229
230 let mut byte_index = 0;
Allen George0e22c362017-01-30 07:15:00 -0500231 while byte_index < self.pos {
232 let nwrite = self.channel.write(&self.buf[byte_index..self.pos])?;
233 byte_index = cmp::min(byte_index + nwrite, self.pos);
Allen George8b96bfb2016-11-02 08:01:08 -0400234 }
235
Allen George0e22c362017-01-30 07:15:00 -0500236 self.pos = 0;
237 self.channel.flush()
Allen George8b96bfb2016-11-02 08:01:08 -0400238 }
239}
240
Allen George0e22c362017-01-30 07:15:00 -0500241/// Factory for creating instances of `TFramedWriteTransport`.
Allen George8b96bfb2016-11-02 08:01:08 -0400242#[derive(Default)]
Allen George0e22c362017-01-30 07:15:00 -0500243pub struct TFramedWriteTransportFactory;
Allen George8b96bfb2016-11-02 08:01:08 -0400244
Allen George0e22c362017-01-30 07:15:00 -0500245impl TFramedWriteTransportFactory {
246 pub fn new() -> TFramedWriteTransportFactory {
247 TFramedWriteTransportFactory {}
Allen George8b96bfb2016-11-02 08:01:08 -0400248 }
249}
250
Allen George0e22c362017-01-30 07:15:00 -0500251impl TWriteTransportFactory for TFramedWriteTransportFactory {
252 /// Create a `TFramedWriteTransport`.
253 fn create(&self, channel: Box<Write + Send>) -> Box<TWriteTransport + Send> {
254 Box::new(TFramedWriteTransport::new(channel))
Allen George8b96bfb2016-11-02 08:01:08 -0400255 }
256}
257
258#[cfg(test)]
259mod tests {
260 // use std::io::{Read, Write};
261 //
262 // use super::*;
Allen George0e22c362017-01-30 07:15:00 -0500263 // use ::transport::mem::TBufferChannel;
Allen George8b96bfb2016-11-02 08:01:08 -0400264}