diff --git a/.rustfmt.toml b/.rustfmt.toml index 2962d47aaec..dca5afd3510 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,7 +1,64 @@ max_width = 100 -fn_args_layout = "Block" -array_layout = "Block" -where_style = "Rfc" -generics_indent = "Block" -fn_call_style = "Block" -reorder_imported_names = true +hard_tabs = false +tab_spaces = 4 +newline_style = "Auto" +use_small_heuristics = "Default" +indent_style = "Block" +wrap_comments = false +format_doc_comments = false +comment_width = 80 +normalize_comments = false +normalize_doc_attributes = false +license_template_path = "" +format_strings = false +format_macro_matchers = false +format_macro_bodies = true +empty_item_single_line = true +struct_lit_single_line = true +fn_single_line = false +where_single_line = false +imports_indent = "Block" +imports_layout = "Mixed" +merge_imports = false +reorder_imports = true +reorder_modules = true +reorder_impl_items = false +type_punctuation_density = "Wide" +space_before_colon = false +space_after_colon = true +spaces_around_ranges = false +binop_separator = "Front" +remove_nested_parens = true +combine_control_expr = true +overflow_delimited_expr = false +struct_field_align_threshold = 0 +enum_discrim_align_threshold = 0 +match_arm_blocks = true +force_multiline_blocks = false +fn_args_density = "Tall" +brace_style = "SameLineWhere" +control_brace_style = "AlwaysSameLine" +trailing_semicolon = true +trailing_comma = "Vertical" +match_block_trailing_comma = false +blank_lines_upper_bound = 1 +blank_lines_lower_bound = 0 +edition = "2015" +merge_derives = true +use_try_shorthand = false +use_field_init_shorthand = false +force_explicit_abi = true +condense_wildcard_suffixes = false +color = "Auto" +required_version = "1.0.0" +unstable_features = false +disable_all_formatting = false +skip_children = false +hide_parse_errors = false +error_on_line_overflow = false +error_on_unformatted = false +report_todo = "Never" +report_fixme = "Never" +ignore = [] +emit_mode = "Files" +make_backup = false diff --git a/lib/rs/src/errors.rs b/lib/rs/src/errors.rs index cc0ac783ec4..16a25766a19 100644 --- a/lib/rs/src/errors.rs +++ b/lib/rs/src/errors.rs @@ -198,8 +198,9 @@ impl Error { /// Create an `ApplicationError` from its wire representation. /// /// Application code **should never** call this method directly. - pub fn read_application_error_from_in_protocol(i: &mut TInputProtocol,) - -> ::Result { + pub fn read_application_error_from_in_protocol( + i: &mut TInputProtocol, + ) -> ::Result { let mut message = "general remote error".to_owned(); let mut kind = ApplicationErrorKind::Unknown; @@ -224,9 +225,8 @@ impl Error { } 2 => { let remote_type_as_int = i.read_i32()?; - let remote_kind: ApplicationErrorKind = - TryFrom::try_from(remote_type_as_int) - .unwrap_or(ApplicationErrorKind::Unknown); + let remote_kind: ApplicationErrorKind = TryFrom::try_from(remote_type_as_int) + .unwrap_or(ApplicationErrorKind::Unknown); i.read_field_end()?; kind = remote_kind; } @@ -238,12 +238,10 @@ impl Error { i.read_struct_end()?; - Ok( - ApplicationError { - kind: kind, - message: message, - }, - ) + Ok(ApplicationError { + kind: kind, + message: message, + }) } /// Convert an `ApplicationError` into its wire representation and write @@ -254,7 +252,9 @@ impl Error { e: &ApplicationError, o: &mut TOutputProtocol, ) -> ::Result<()> { - o.write_struct_begin(&TStructIdentifier { name: "TApplicationException".to_owned() },)?; + o.write_struct_begin(&TStructIdentifier { + name: "TApplicationException".to_owned(), + })?; let message_field = TFieldIdentifier::new("message", TType::String, 1); let type_field = TFieldIdentifier::new("type", TType::I32, 2); @@ -309,23 +309,19 @@ impl Display for Error { impl From for Error { fn from(s: String) -> Self { - Error::Application( - ApplicationError { - kind: ApplicationErrorKind::Unknown, - message: s, - }, - ) + Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: s, + }) } } impl<'a> From<&'a str> for Error { fn from(s: &'a str) -> Self { - Error::Application( - ApplicationError { - kind: ApplicationErrorKind::Unknown, - message: String::from(s), - }, - ) + Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: String::from(s), + }) } } @@ -427,16 +423,10 @@ impl TryFrom for TransportErrorKind { 4 => Ok(TransportErrorKind::EndOfFile), 5 => Ok(TransportErrorKind::NegativeSize), 6 => Ok(TransportErrorKind::SizeLimit), - _ => { - Err( - Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::Unknown, - message: format!("cannot convert {} to TransportErrorKind", from), - }, - ), - ) - } + _ => Err(Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!("cannot convert {} to TransportErrorKind", from), + })), } } } @@ -444,47 +434,29 @@ impl TryFrom for TransportErrorKind { impl From for Error { fn from(err: io::Error) -> Self { match err.kind() { - io::ErrorKind::ConnectionReset | - io::ErrorKind::ConnectionRefused | - io::ErrorKind::NotConnected => { - Error::Transport( - TransportError { - kind: TransportErrorKind::NotOpen, - message: err.description().to_owned(), - }, - ) - } - io::ErrorKind::AlreadyExists => { - Error::Transport( - TransportError { - kind: TransportErrorKind::AlreadyOpen, - message: err.description().to_owned(), - }, - ) - } - io::ErrorKind::TimedOut => { - Error::Transport( - TransportError { - kind: TransportErrorKind::TimedOut, - message: err.description().to_owned(), - }, - ) - } - io::ErrorKind::UnexpectedEof => { - Error::Transport( - TransportError { - kind: TransportErrorKind::EndOfFile, - message: err.description().to_owned(), - }, - ) - } + io::ErrorKind::ConnectionReset + | io::ErrorKind::ConnectionRefused + | io::ErrorKind::NotConnected => Error::Transport(TransportError { + kind: TransportErrorKind::NotOpen, + message: err.description().to_owned(), + }), + io::ErrorKind::AlreadyExists => Error::Transport(TransportError { + kind: TransportErrorKind::AlreadyOpen, + message: err.description().to_owned(), + }), + io::ErrorKind::TimedOut => Error::Transport(TransportError { + kind: TransportErrorKind::TimedOut, + message: err.description().to_owned(), + }), + io::ErrorKind::UnexpectedEof => Error::Transport(TransportError { + kind: TransportErrorKind::EndOfFile, + message: err.description().to_owned(), + }), _ => { - Error::Transport( - TransportError { - kind: TransportErrorKind::Unknown, - message: err.description().to_owned(), // FIXME: use io error's debug string - }, - ) + Error::Transport(TransportError { + kind: TransportErrorKind::Unknown, + message: err.description().to_owned(), // FIXME: use io error's debug string + }) } } } @@ -492,12 +464,10 @@ impl From for Error { impl From for Error { fn from(err: string::FromUtf8Error) -> Self { - Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::InvalidData, - message: err.description().to_owned(), // FIXME: use fmt::Error's debug string - }, - ) + Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::InvalidData, + message: err.description().to_owned(), // FIXME: use fmt::Error's debug string + }) } } @@ -583,16 +553,10 @@ impl TryFrom for ProtocolErrorKind { 4 => Ok(ProtocolErrorKind::BadVersion), 5 => Ok(ProtocolErrorKind::NotImplemented), 6 => Ok(ProtocolErrorKind::DepthLimit), - _ => { - Err( - Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::Unknown, - message: format!("cannot convert {} to ProtocolErrorKind", from), - }, - ), - ) - } + _ => Err(Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!("cannot convert {} to ProtocolErrorKind", from), + })), } } } @@ -697,16 +661,10 @@ impl TryFrom for ApplicationErrorKind { 8 => Ok(ApplicationErrorKind::InvalidTransform), 9 => Ok(ApplicationErrorKind::InvalidProtocol), 10 => Ok(ApplicationErrorKind::UnsupportedClientType), - _ => { - Err( - Error::Application( - ApplicationError { - kind: ApplicationErrorKind::Unknown, - message: format!("cannot convert {} to ApplicationErrorKind", from), - }, - ), - ) - } + _ => Err(Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: format!("cannot convert {} to ApplicationErrorKind", from), + })), } } } diff --git a/lib/rs/src/lib.rs b/lib/rs/src/lib.rs index 7ebb10cc42d..ca5c7d649dc 100644 --- a/lib/rs/src/lib.rs +++ b/lib/rs/src/lib.rs @@ -63,13 +63,11 @@ extern crate log; /// return the value contained in the result, i.e. `expr.unwrap()`. #[cfg(test)] macro_rules! assert_success { - ($e: expr) => { - { - let res = $e; - assert!(res.is_ok()); - res.unwrap() - } - } + ($e: expr) => {{ + let res = $e; + assert!(res.is_ok()); + res.unwrap() + }}; } pub mod protocol; diff --git a/lib/rs/src/protocol/binary.rs b/lib/rs/src/protocol/binary.rs index 42c6c97511d..19aff3d6cf1 100644 --- a/lib/rs/src/protocol/binary.rs +++ b/lib/rs/src/protocol/binary.rs @@ -19,11 +19,13 @@ use byteorder::{BigEndian, ByteOrder, ReadBytesExt, WriteBytesExt}; use std::convert::From; use try_from::TryFrom; -use {ProtocolError, ProtocolErrorKind}; -use transport::{TReadTransport, TWriteTransport}; -use super::{TFieldIdentifier, TInputProtocol, TInputProtocolFactory, TListIdentifier, - TMapIdentifier, TMessageIdentifier, TMessageType}; +use super::{ + TFieldIdentifier, TInputProtocol, TInputProtocolFactory, TListIdentifier, TMapIdentifier, + TMessageIdentifier, TMessageType, +}; use super::{TOutputProtocol, TOutputProtocolFactory, TSetIdentifier, TStructIdentifier, TType}; +use transport::{TReadTransport, TWriteTransport}; +use {ProtocolError, ProtocolErrorKind}; const BINARY_PROTOCOL_VERSION_1: u32 = 0x80010000; @@ -90,14 +92,10 @@ where // apparently we got a protocol-version header - check // it, and if it matches, read the rest of the fields if first_bytes[0..2] != [0x80, 0x01] { - Err( - ::Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::BadVersion, - message: format!("received bad version: {:?}", &first_bytes[0..2]), - }, - ), - ) + Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::BadVersion, + message: format!("received bad version: {:?}", &first_bytes[0..2]), + })) } else { let message_type: TMessageType = TryFrom::try_from(first_bytes[3])?; let name = self.read_string()?; @@ -110,14 +108,10 @@ where if self.strict { // we're in strict mode however, and that always // requires the protocol-version header to be written first - Err( - ::Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::BadVersion, - message: format!("received bad version: {:?}", &first_bytes[0..2]), - }, - ), - ) + Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::BadVersion, + message: format!("received bad version: {:?}", &first_bytes[0..2]), + })) } else { // in the non-strict version the first message field // is the message name. strings (byte arrays) are length-prefixed, @@ -154,7 +148,9 @@ where TType::Stop => Ok(0), _ => self.read_i16(), }?; - Ok(TFieldIdentifier::new::, String, i16>(None, field_type, id),) + Ok(TFieldIdentifier::new::, String, i16>( + None, field_type, id, + )) } fn read_field_end(&mut self) -> ::Result<()> { @@ -183,27 +179,19 @@ where } fn read_i16(&mut self) -> ::Result { - self.transport - .read_i16::() - .map_err(From::from) + self.transport.read_i16::().map_err(From::from) } fn read_i32(&mut self) -> ::Result { - self.transport - .read_i32::() - .map_err(From::from) + self.transport.read_i32::().map_err(From::from) } fn read_i64(&mut self) -> ::Result { - self.transport - .read_i64::() - .map_err(From::from) + self.transport.read_i64::().map_err(From::from) } fn read_double(&mut self) -> ::Result { - self.transport - .read_f64::() - .map_err(From::from) + self.transport.read_f64::().map_err(From::from) } fn read_string(&mut self) -> ::Result { @@ -346,17 +334,13 @@ where fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> ::Result<()> { if identifier.id.is_none() && identifier.field_type != TType::Stop { - return Err( - ::Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::Unknown, - message: format!( - "cannot write identifier {:?} without sequence number", - &identifier - ), - }, + return Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!( + "cannot write identifier {:?} without sequence number", + &identifier ), - ); + })); } self.write_byte(field_type_to_u8(identifier.field_type))?; @@ -393,27 +377,19 @@ where } fn write_i16(&mut self, i: i16) -> ::Result<()> { - self.transport - .write_i16::(i) - .map_err(From::from) + self.transport.write_i16::(i).map_err(From::from) } fn write_i32(&mut self, i: i32) -> ::Result<()> { - self.transport - .write_i32::(i) - .map_err(From::from) + self.transport.write_i32::(i).map_err(From::from) } fn write_i64(&mut self, i: i64) -> ::Result<()> { - self.transport - .write_i64::(i) - .map_err(From::from) + self.transport.write_i64::(i).map_err(From::from) } fn write_double(&mut self, d: f64) -> ::Result<()> { - self.transport - .write_f64::(d) - .map_err(From::from) + self.transport.write_f64::(d).map_err(From::from) } fn write_string(&mut self, s: &str) -> ::Result<()> { @@ -520,25 +496,20 @@ fn field_type_from_u8(b: u8) -> ::Result { 0x0F => Ok(TType::List), 0x10 => Ok(TType::Utf8), 0x11 => Ok(TType::Utf16), - unkn => { - Err( - ::Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::InvalidData, - message: format!("cannot convert {} to TType", unkn), - }, - ), - ) - } + unkn => Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} to TType", unkn), + })), } } #[cfg(test)] mod tests { - use protocol::{TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, - TMessageIdentifier, TMessageType, TOutputProtocol, TSetIdentifier, - TStructIdentifier, TType}; + use protocol::{ + TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier, + TMessageType, TOutputProtocol, TSetIdentifier, TStructIdentifier, TType, + }; use transport::{ReadHalf, TBufferChannel, TIoChannel, WriteHalf}; use super::*; @@ -550,6 +521,7 @@ mod tests { let ident = TMessageIdentifier::new("test", TMessageType::Call, 1); assert!(o_prot.write_message_begin(&ident).is_ok()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 16] = [ 0x80, 0x01, @@ -579,6 +551,7 @@ mod tests { let ident = TMessageIdentifier::new("test", TMessageType::Call, 1); assert!(o_prot.write_message_begin(&ident).is_ok()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 13] = [ 0x00, 0x00, @@ -605,6 +578,7 @@ mod tests { let ident = TMessageIdentifier::new("test", TMessageType::Reply, 10); assert!(o_prot.write_message_begin(&ident).is_ok()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 16] = [ 0x80, 0x01, @@ -634,6 +608,7 @@ mod tests { let ident = TMessageIdentifier::new("test", TMessageType::Reply, 10); assert!(o_prot.write_message_begin(&ident).is_ok()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 13] = [ 0x00, 0x00, @@ -686,7 +661,10 @@ mod tests { #[test] fn must_write_struct_begin() { - assert_no_write(|o| o.write_struct_begin(&TStructIdentifier::new("foo")), true); + assert_no_write( + |o| o.write_struct_begin(&TStructIdentifier::new("foo")), + true, + ); } #[test] @@ -698,11 +676,9 @@ mod tests { fn must_write_field_begin() { let (_, mut o_prot) = test_objects(true); - assert!( - o_prot - .write_field_begin(&TFieldIdentifier::new("some_field", TType::String, 22)) - .is_ok() - ); + assert!(o_prot + .write_field_begin(&TFieldIdentifier::new("some_field", TType::String, 22)) + .is_ok()); let expected: [u8; 3] = [0x0B, 0x00, 0x16]; assert_eq_written_bytes!(o_prot, expected); @@ -763,11 +739,9 @@ mod tests { fn must_write_list_begin() { let (_, mut o_prot) = test_objects(true); - assert!( - o_prot - .write_list_begin(&TListIdentifier::new(TType::Bool, 5)) - .is_ok() - ); + assert!(o_prot + .write_list_begin(&TListIdentifier::new(TType::Bool, 5)) + .is_ok()); let expected: [u8; 5] = [0x02, 0x00, 0x00, 0x00, 0x05]; assert_eq_written_bytes!(o_prot, expected); @@ -795,11 +769,9 @@ mod tests { fn must_write_set_begin() { let (_, mut o_prot) = test_objects(true); - assert!( - o_prot - .write_set_begin(&TSetIdentifier::new(TType::I16, 7)) - .is_ok() - ); + assert!(o_prot + .write_set_begin(&TSetIdentifier::new(TType::I16, 7)) + .is_ok()); let expected: [u8; 5] = [0x06, 0x00, 0x00, 0x00, 0x07]; assert_eq_written_bytes!(o_prot, expected); @@ -828,11 +800,9 @@ mod tests { fn must_write_map_begin() { let (_, mut o_prot) = test_objects(true); - assert!( - o_prot - .write_map_begin(&TMapIdentifier::new(TType::I64, TType::Struct, 32)) - .is_ok() - ); + assert!(o_prot + .write_map_begin(&TMapIdentifier::new(TType::I64, TType::Struct, 32)) + .is_ok()); let expected: [u8; 6] = [0x0A, 0x0C, 0x00, 0x00, 0x00, 0x20]; assert_eq_written_bytes!(o_prot, expected); @@ -923,6 +893,7 @@ mod tests { fn must_round_trip_bytes() { let (mut i_prot, mut o_prot) = test_objects(true); + #[cfg_attr(rustfmt, rustfmt::skip)] let bytes: [u8; 25] = [ 0x20, 0xFD, @@ -959,10 +930,12 @@ mod tests { assert_eq!(&received_bytes, &bytes); } - fn test_objects(strict: bool) - -> (TBinaryInputProtocol>, - TBinaryOutputProtocol>) - { + fn test_objects( + strict: bool, + ) -> ( + TBinaryInputProtocol>, + TBinaryOutputProtocol>, + ) { let mem = TBufferChannel::with_capacity(40, 40); let (r_mem, w_mem) = mem.split().unwrap(); diff --git a/lib/rs/src/protocol/compact.rs b/lib/rs/src/protocol/compact.rs index 1e67f4931eb..df5edaa8278 100644 --- a/lib/rs/src/protocol/compact.rs +++ b/lib/rs/src/protocol/compact.rs @@ -18,13 +18,15 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use integer_encoding::{VarIntReader, VarIntWriter}; use std::convert::From; -use try_from::TryFrom; use std::io; +use try_from::TryFrom; -use transport::{TReadTransport, TWriteTransport}; -use super::{TFieldIdentifier, TInputProtocol, TInputProtocolFactory, TListIdentifier, - TMapIdentifier, TMessageIdentifier, TMessageType}; +use super::{ + TFieldIdentifier, TInputProtocol, TInputProtocolFactory, TListIdentifier, TMapIdentifier, + TMessageIdentifier, TMessageType, +}; use super::{TOutputProtocol, TOutputProtocolFactory, TSetIdentifier, TStructIdentifier, TType}; +use transport::{TReadTransport, TWriteTransport}; const COMPACT_PROTOCOL_ID: u8 = 0x82; const COMPACT_VERSION: u8 = 0x01; @@ -103,14 +105,10 @@ where fn read_message_begin(&mut self) -> ::Result { let compact_id = self.read_byte()?; if compact_id != COMPACT_PROTOCOL_ID { - Err( - ::Error::Protocol( - ::ProtocolError { - kind: ::ProtocolErrorKind::BadVersion, - message: format!("invalid compact protocol header {:?}", compact_id), - }, - ), - ) + Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::BadVersion, + message: format!("invalid compact protocol header {:?}", compact_id), + })) } else { Ok(()) }?; @@ -118,17 +116,13 @@ where let type_and_byte = self.read_byte()?; let received_version = type_and_byte & COMPACT_VERSION_MASK; if received_version != COMPACT_VERSION { - Err( - ::Error::Protocol( - ::ProtocolError { - kind: ::ProtocolErrorKind::BadVersion, - message: format!( - "cannot process compact protocol version {:?}", - received_version - ), - }, + Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::BadVersion, + message: format!( + "cannot process compact protocol version {:?}", + received_version ), - ) + })) } else { Ok(()) }?; @@ -140,7 +134,11 @@ where self.last_read_field_id = 0; - Ok(TMessageIdentifier::new(service_call_name, message_type, sequence_number),) + Ok(TMessageIdentifier::new( + service_call_name, + message_type, + sequence_number, + )) } fn read_message_end(&mut self) -> ::Result<()> { @@ -154,7 +152,8 @@ where } fn read_struct_end(&mut self) -> ::Result<()> { - self.last_read_field_id = self.read_field_id_stack + self.last_read_field_id = self + .read_field_id_stack .pop() .expect("should have previous field ids"); Ok(()) @@ -179,15 +178,13 @@ where }?; match field_type { - TType::Stop => { - Ok( - TFieldIdentifier::new::, String, Option>( - None, - TType::Stop, - None, - ), - ) - } + TType::Stop => Ok( + TFieldIdentifier::new::, String, Option>( + None, + TType::Stop, + None, + ), + ), _ => { if field_delta != 0 { self.last_read_field_id += field_delta as i16; @@ -195,13 +192,11 @@ where self.last_read_field_id = self.read_i16()?; }; - Ok( - TFieldIdentifier { - name: None, - field_type: field_type, - id: Some(self.last_read_field_id), - }, - ) + Ok(TFieldIdentifier { + name: None, + field_type: field_type, + id: Some(self.last_read_field_id), + }) } } } @@ -218,16 +213,10 @@ where match b { 0x01 => Ok(true), 0x02 => Ok(false), - unkn => { - Err( - ::Error::Protocol( - ::ProtocolError { - kind: ::ProtocolErrorKind::InvalidData, - message: format!("cannot convert {} into bool", unkn), - }, - ), - ) - } + unkn => Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} into bool", unkn), + })), } } } @@ -259,9 +248,7 @@ where } fn read_double(&mut self) -> ::Result { - self.transport - .read_f64::() - .map_err(From::from) + self.transport.read_f64::().map_err(From::from) } fn read_string(&mut self) -> ::Result { @@ -315,7 +302,6 @@ where } } - impl io::Seek for TCompactInputProtocol where T: io::Seek + TReadTransport, @@ -450,7 +436,8 @@ where fn write_struct_end(&mut self) -> ::Result<()> { self.assert_no_pending_bool_write(); - self.last_write_field_id = self.write_field_id_stack + self.last_write_field_id = self + .write_field_id_stack .pop() .expect("should have previous field ids"); Ok(()) @@ -462,7 +449,7 @@ where if self.pending_write_bool_field_identifier.is_some() { panic!( "should not have a pending bool while writing another bool with id: \ - {:?}", + {:?}", identifier ) } @@ -471,9 +458,7 @@ where } _ => { let field_type = type_to_u8(identifier.field_type); - let field_id = identifier - .id - .expect("non-stop field should have field id"); + let field_id = identifier.id.expect("non-stop field should have field id"); self.write_field_header(field_type, field_id) } } @@ -537,9 +522,7 @@ where } fn write_double(&mut self, d: f64) -> ::Result<()> { - self.transport - .write_f64::(d) - .map_err(From::from) + self.transport.write_f64::(d).map_err(From::from) } fn write_string(&mut self, s: &str) -> ::Result<()> { @@ -595,10 +578,7 @@ where // fn write_byte(&mut self, b: u8) -> ::Result<()> { - self.transport - .write(&[b]) - .map_err(From::from) - .map(|_| ()) + self.transport.write(&[b]).map_err(From::from).map(|_| ()) } } @@ -639,7 +619,10 @@ fn type_to_u8(field_type: TType) -> u8 { TType::Set => 0x0A, TType::Map => 0x0B, TType::Struct => 0x0C, - _ => panic!(format!("should not have attempted to convert {} to u8", field_type)), + _ => panic!(format!( + "should not have attempted to convert {} to u8", + field_type + )), } } @@ -663,25 +646,20 @@ fn u8_to_type(b: u8) -> ::Result { 0x0A => Ok(TType::Set), 0x0B => Ok(TType::Map), 0x0C => Ok(TType::Struct), - unkn => { - Err( - ::Error::Protocol( - ::ProtocolError { - kind: ::ProtocolErrorKind::InvalidData, - message: format!("cannot convert {} into TType", unkn), - }, - ), - ) - } + unkn => Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} into TType", unkn), + })), } } #[cfg(test)] mod tests { - use protocol::{TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, - TMessageIdentifier, TMessageType, TOutputProtocol, TSetIdentifier, - TStructIdentifier, TType}; + use protocol::{ + TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier, + TMessageType, TOutputProtocol, TSetIdentifier, TStructIdentifier, TType, + }; use transport::{ReadHalf, TBufferChannel, TIoChannel, WriteHalf}; use super::*; @@ -690,8 +668,13 @@ mod tests { fn must_write_message_begin_0() { let (_, mut o_prot) = test_objects(); - assert_success!(o_prot.write_message_begin(&TMessageIdentifier::new("foo", TMessageType::Call, 431))); + assert_success!(o_prot.write_message_begin(&TMessageIdentifier::new( + "foo", + TMessageType::Call, + 431 + ))); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 8] = [ 0x82, /* protocol ID */ 0x21, /* message type | protocol version */ @@ -710,10 +693,13 @@ mod tests { fn must_write_message_begin_1() { let (_, mut o_prot) = test_objects(); - assert_success!( - o_prot.write_message_begin(&TMessageIdentifier::new("bar", TMessageType::Reply, 991828)) - ); + assert_success!(o_prot.write_message_begin(&TMessageIdentifier::new( + "bar", + TMessageType::Reply, + 991828 + ))); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 9] = [ 0x82, /* protocol ID */ 0x41, /* message type | protocol version */ @@ -777,6 +763,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 5] = [ 0x03, /* field type */ 0x00, /* first field id */ @@ -891,6 +878,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 4] = [ 0x15, /* field delta (1) | field type */ 0x1A, /* field delta (1) | field type */ @@ -1003,6 +991,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 8] = [ 0x05, /* field type */ 0x00, /* first field id */ @@ -1126,6 +1115,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 10] = [ 0x16, /* field delta (1) | field type */ 0x85, /* field delta (8) | field type */ @@ -1290,6 +1280,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 7] = [ 0x16, /* field delta (1) | field type */ 0x85, /* field delta (8) | field type */ @@ -1462,6 +1453,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 7] = [ 0x16, /* field delta (1) | field type */ 0x85, /* field delta (8) | field type */ @@ -1634,6 +1626,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 7] = [ 0x16, /* field delta (1) | field type */ 0x08, /* field type */ @@ -1803,6 +1796,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 8] = [ 0x16, /* field delta (1) | field type */ 0x08, /* field type */ @@ -1968,6 +1962,7 @@ mod tests { assert_success!(o_prot.write_field_stop()); assert_success!(o_prot.write_struct_end()); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 7] = [ 0x11, /* field delta (1) | true */ 0x82, /* field delta (8) | false */ @@ -2158,8 +2153,7 @@ mod tests { let expected: [u8; 3] = [ 0xF9, /* 0xF0 | elem_type */ - 0x8F, - 0x4E /* size as varint */, + 0x8F, 0x4E, /* size as varint */ ]; assert_eq_written_bytes!(o_prot, expected); @@ -2217,9 +2211,7 @@ mod tests { let expected: [u8; 4] = [ 0xF7, /* 0xF0 | elem_type */ - 0xD3, - 0xBA, - 0x01 /* size as varint */, + 0xD3, 0xBA, 0x01, /* size as varint */ ]; assert_eq_written_bytes!(o_prot, expected); @@ -2267,10 +2259,10 @@ mod tests { assert_eq!( &res, &TMapIdentifier { - key_type: None, - value_type: None, - size: 0, - } + key_type: None, + value_type: None, + size: 0, + } ); } @@ -2278,12 +2270,15 @@ mod tests { fn must_write_map_begin() { let (_, mut o_prot) = test_objects(); - assert_success!(o_prot.write_map_begin(&TMapIdentifier::new(TType::Double, TType::String, 238))); + assert_success!(o_prot.write_map_begin(&TMapIdentifier::new( + TType::Double, + TType::String, + 238 + ))); let expected: [u8; 3] = [ - 0xEE, - 0x01, /* size as varint */ - 0x78 /* key type | val type */, + 0xEE, 0x01, /* size as varint */ + 0x78, /* key type | val type */ ]; assert_eq_written_bytes!(o_prot, expected); @@ -2321,7 +2316,7 @@ mod tests { 0x01, /* size as varint */ 0x11, /* key type | val type */ 0x01, /* key: true */ - 0x02 /* val: false */, + 0x02, /* val: false */ ]; assert_eq_written_bytes!(o_prot, expected); @@ -2366,10 +2361,10 @@ mod tests { assert!(i_prot.read_map_end().is_ok()); // will blow up if we try to read from empty buffer } - fn test_objects() - -> (TCompactInputProtocol>, - TCompactOutputProtocol>) - { + fn test_objects() -> ( + TCompactInputProtocol>, + TCompactOutputProtocol>, + ) { let mem = TBufferChannel::with_capacity(80, 80); let (r_mem, w_mem) = mem.split().unwrap(); diff --git a/lib/rs/src/protocol/mod.rs b/lib/rs/src/protocol/mod.rs index 4f139147c9e..11c0289f954 100644 --- a/lib/rs/src/protocol/mod.rs +++ b/lib/rs/src/protocol/mod.rs @@ -57,38 +57,34 @@ //! protocol.write_field_end().unwrap(); //! ``` +use std::convert::From; use std::fmt; use std::fmt::{Display, Formatter}; -use std::convert::From; use try_from::TryFrom; -use {ProtocolError, ProtocolErrorKind}; use transport::{TReadTransport, TWriteTransport}; +use {ProtocolError, ProtocolErrorKind}; #[cfg(test)] macro_rules! assert_eq_written_bytes { - ($o_prot:ident, $expected_bytes:ident) => { - { - assert_eq!($o_prot.transport.write_bytes(), &$expected_bytes); - } - }; + ($o_prot:ident, $expected_bytes:ident) => {{ + assert_eq!($o_prot.transport.write_bytes(), &$expected_bytes); + }}; } // FIXME: should take both read and write #[cfg(test)] macro_rules! copy_write_buffer_to_read_buffer { - ($o_prot:ident) => { - { - $o_prot.transport.copy_write_buffer_to_read_buffer(); - } - }; + ($o_prot:ident) => {{ + $o_prot.transport.copy_write_buffer_to_read_buffer(); + }}; } #[cfg(test)] macro_rules! set_readable_bytes { ($i_prot:ident, $bytes:expr) => { $i_prot.transport.set_readable_bytes($bytes); - } + }; } mod binary; @@ -96,10 +92,14 @@ mod compact; mod multiplexed; mod stored; -pub use self::binary::{TBinaryInputProtocol, TBinaryInputProtocolFactory, TBinaryOutputProtocol, - TBinaryOutputProtocolFactory}; -pub use self::compact::{TCompactInputProtocol, TCompactInputProtocolFactory, - TCompactOutputProtocol, TCompactOutputProtocolFactory}; +pub use self::binary::{ + TBinaryInputProtocol, TBinaryInputProtocolFactory, TBinaryOutputProtocol, + TBinaryOutputProtocolFactory, +}; +pub use self::compact::{ + TCompactInputProtocol, TCompactInputProtocolFactory, TCompactOutputProtocol, + TCompactOutputProtocolFactory, +}; pub use self::multiplexed::TMultiplexedOutputProtocol; pub use self::stored::TStoredInputProtocol; @@ -186,14 +186,10 @@ pub trait TInputProtocol { /// Skip a field with type `field_type` recursively up to `depth` levels. fn skip_till_depth(&mut self, field_type: TType, depth: i8) -> ::Result<()> { if depth == 0 { - return Err( - ::Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::DepthLimit, - message: format!("cannot parse past {:?}", field_type), - }, - ), - ); + return Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::DepthLimit, + message: format!("cannot parse past {:?}", field_type), + })); } match field_type { @@ -243,16 +239,10 @@ pub trait TInputProtocol { } self.read_map_end() } - u => { - Err( - ::Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::Unknown, - message: format!("cannot skip field type {:?}", &u), - }, - ), - ) - } + u => Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!("cannot skip field type {:?}", &u), + })), } } @@ -787,16 +777,10 @@ impl TryFrom for TMessageType { 0x02 => Ok(TMessageType::Reply), 0x03 => Ok(TMessageType::Exception), 0x04 => Ok(TMessageType::OneWay), - unkn => { - Err( - ::Error::Protocol( - ProtocolError { - kind: ProtocolErrorKind::InvalidData, - message: format!("cannot convert {} to TMessageType", unkn), - }, - ), - ) - } + unkn => Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} to TMessageType", unkn), + })), } } } @@ -869,14 +853,10 @@ pub fn verify_expected_sequence_number(expected: i32, actual: i32) -> ::Result<( if expected == actual { Ok(()) } else { - Err( - ::Error::Application( - ::ApplicationError { - kind: ::ApplicationErrorKind::BadSequenceId, - message: format!("expected {} got {}", expected, actual), - }, - ), - ) + Err(::Error::Application(::ApplicationError { + kind: ::ApplicationErrorKind::BadSequenceId, + message: format!("expected {} got {}", expected, actual), + })) } } @@ -888,14 +868,10 @@ pub fn verify_expected_service_call(expected: &str, actual: &str) -> ::Result<() if expected == actual { Ok(()) } else { - Err( - ::Error::Application( - ::ApplicationError { - kind: ::ApplicationErrorKind::WrongMethodName, - message: format!("expected {} got {}", expected, actual), - }, - ), - ) + Err(::Error::Application(::ApplicationError { + kind: ::ApplicationErrorKind::WrongMethodName, + message: format!("expected {} got {}", expected, actual), + })) } } @@ -907,14 +883,10 @@ pub fn verify_expected_message_type(expected: TMessageType, actual: TMessageType if expected == actual { Ok(()) } else { - Err( - ::Error::Application( - ::ApplicationError { - kind: ::ApplicationErrorKind::InvalidMessageType, - message: format!("expected {} got {}", expected, actual), - }, - ), - ) + Err(::Error::Application(::ApplicationError { + kind: ::ApplicationErrorKind::InvalidMessageType, + message: format!("expected {} got {}", expected, actual), + })) } } @@ -924,16 +896,10 @@ pub fn verify_expected_message_type(expected: TMessageType, actual: TMessageType pub fn verify_required_field_exists(field_name: &str, field: &Option) -> ::Result<()> { match *field { Some(_) => Ok(()), - None => { - Err( - ::Error::Protocol( - ::ProtocolError { - kind: ::ProtocolErrorKind::Unknown, - message: format!("missing required field {}", field_name), - }, - ), - ) - } + None => Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::Unknown, + message: format!("missing required field {}", field_name), + })), } } @@ -943,18 +909,12 @@ pub fn verify_required_field_exists(field_name: &str, field: &Option) -> : /// /// Return `TFieldIdentifier.id` if an id exists, `Err` otherwise. pub fn field_id(field_ident: &TFieldIdentifier) -> ::Result { - field_ident - .id - .ok_or_else( - || { - ::Error::Protocol( - ::ProtocolError { - kind: ::ProtocolErrorKind::Unknown, - message: format!("missing field in in {:?}", field_ident), - }, - ) - }, - ) + field_ident.id.ok_or_else(|| { + ::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::Unknown, + message: format!("missing field in in {:?}", field_ident), + }) + }) } #[cfg(test)] diff --git a/lib/rs/src/protocol/multiplexed.rs b/lib/rs/src/protocol/multiplexed.rs index db08027f2bd..aaee44f73eb 100644 --- a/lib/rs/src/protocol/multiplexed.rs +++ b/lib/rs/src/protocol/multiplexed.rs @@ -15,8 +15,10 @@ // specific language governing permissions and limitations // under the License. -use super::{TFieldIdentifier, TListIdentifier, TMapIdentifier, TMessageIdentifier, TMessageType, - TOutputProtocol, TSetIdentifier, TStructIdentifier}; +use super::{ + TFieldIdentifier, TListIdentifier, TMapIdentifier, TMessageIdentifier, TMessageType, + TOutputProtocol, TSetIdentifier, TStructIdentifier, +}; /// `TOutputProtocol` that prefixes the service name to all outgoing Thrift /// messages. @@ -81,7 +83,8 @@ where P: TOutputProtocol, { fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> ::Result<()> { - match identifier.message_type { // FIXME: is there a better way to override identifier here? + match identifier.message_type { + // FIXME: is there a better way to override identifier here? TMessageType::Call | TMessageType::OneWay => { let identifier = TMessageIdentifier { name: format!("{}:{}", self.service_name, identifier.name), @@ -200,6 +203,7 @@ mod tests { let ident = TMessageIdentifier::new("bar", TMessageType::Call, 2); assert_success!(o_prot.write_message_begin(&ident)); + #[cfg_attr(rustfmt, rustfmt::skip)] let expected: [u8; 19] = [ 0x80, 0x01, /* protocol identifier */ @@ -225,9 +229,7 @@ mod tests { assert_eq!(o_prot.inner.transport.write_bytes(), expected); } - fn test_objects - () - -> TMultiplexedOutputProtocol>> + fn test_objects() -> TMultiplexedOutputProtocol>> { let c = TBufferChannel::with_capacity(40, 40); let (_, w_chan) = c.split().unwrap(); diff --git a/lib/rs/src/protocol/stored.rs b/lib/rs/src/protocol/stored.rs index b3f305f031a..8c559788777 100644 --- a/lib/rs/src/protocol/stored.rs +++ b/lib/rs/src/protocol/stored.rs @@ -17,9 +17,11 @@ use std::convert::Into; +use super::{ + TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier, + TSetIdentifier, TStructIdentifier, +}; use ProtocolErrorKind; -use super::{TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier, - TSetIdentifier, TStructIdentifier}; /// `TInputProtocol` required to use a `TMultiplexedProcessor`. /// @@ -101,16 +103,12 @@ impl<'a> TStoredInputProtocol<'a> { impl<'a> TInputProtocol for TStoredInputProtocol<'a> { fn read_message_begin(&mut self) -> ::Result { - self.message_ident - .take() - .ok_or_else( - || { - ::errors::new_protocol_error( - ProtocolErrorKind::Unknown, - "message identifier already read", - ) - }, + self.message_ident.take().ok_or_else(|| { + ::errors::new_protocol_error( + ProtocolErrorKind::Unknown, + "message identifier already read", ) + }) } fn read_message_end(&mut self) -> ::Result<()> { diff --git a/lib/rs/src/server/mod.rs b/lib/rs/src/server/mod.rs index 3d8ccb2cc00..70b381ac928 100644 --- a/lib/rs/src/server/mod.rs +++ b/lib/rs/src/server/mod.rs @@ -17,8 +17,8 @@ //! Types used to implement a Thrift server. -use {ApplicationError, ApplicationErrorKind}; use protocol::{TInputProtocol, TMessageIdentifier, TMessageType, TOutputProtocol}; +use {ApplicationError, ApplicationErrorKind}; mod multiplexed; mod threaded; diff --git a/lib/rs/src/server/multiplexed.rs b/lib/rs/src/server/multiplexed.rs index a7f6d0474f8..e433794a552 100644 --- a/lib/rs/src/server/multiplexed.rs +++ b/lib/rs/src/server/multiplexed.rs @@ -16,16 +16,17 @@ // under the License. use std::collections::HashMap; +use std::convert::Into; use std::fmt; use std::fmt::{Debug, Formatter}; -use std::convert::Into; use std::sync::{Arc, Mutex}; use protocol::{TInputProtocol, TMessageIdentifier, TOutputProtocol, TStoredInputProtocol}; -use super::{TProcessor, handle_process_result}; +use super::{handle_process_result, TProcessor}; -const MISSING_SEPARATOR_AND_NO_DEFAULT: &'static str = "missing service separator and no default processor set"; +const MISSING_SEPARATOR_AND_NO_DEFAULT: &'static str = + "missing service separator and no default processor set"; type ThreadSafeProcessor = Box; /// A `TProcessor` that can demux service calls to multiple underlying @@ -54,12 +55,10 @@ impl TMultiplexedProcessor { /// processors. pub fn new() -> TMultiplexedProcessor { TMultiplexedProcessor { - stored: Mutex::new( - StoredProcessors { - processors: HashMap::new(), - default_processor: None, - }, - ), + stored: Mutex::new(StoredProcessors { + processors: HashMap::new(), + default_processor: None, + }), } } @@ -97,7 +96,7 @@ impl TMultiplexedProcessor { Ok(()) } } else { - Err(format!("cannot overwrite existing processor for service {}", name).into(),) + Err(format!("cannot overwrite existing processor for service {}", name).into()) } } @@ -160,13 +159,11 @@ impl Debug for TMultiplexedProcessor { fn split_ident_name(ident_name: &str) -> (Option<&str>, &str) { ident_name .find(':') - .map( - |pos| { - let (svc_name, svc_call) = ident_name.split_at(pos); - let (_, svc_call) = svc_call.split_at(1); // remove colon from service call name - (Some(svc_name), svc_call) - }, - ) + .map(|pos| { + let (svc_name, svc_call) = ident_name.split_at(pos); + let (_, svc_call) = svc_call.split_at(1); // remove colon from service call name + (Some(svc_name), svc_call) + }) .or_else(|| Some((None, ident_name))) .unwrap() } @@ -181,12 +178,12 @@ fn missing_processor_message(svc_name: Option<&str>) -> String { #[cfg(test)] mod tests { use std::convert::Into; - use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; - use {ApplicationError, ApplicationErrorKind}; use protocol::{TBinaryInputProtocol, TBinaryOutputProtocol, TMessageIdentifier, TMessageType}; use transport::{ReadHalf, TBufferChannel, TIoChannel, WriteHalf}; + use {ApplicationError, ApplicationErrorKind}; use super::*; @@ -219,8 +216,7 @@ mod tests { let p = TMultiplexedProcessor::new(); p.process(&mut i, &mut o).unwrap(); // at this point an error should be written out - i.transport - .set_readable_bytes(&o.transport.write_bytes()); + i.transport.set_readable_bytes(&o.transport.write_bytes()); let rcvd_ident = i.read_message_begin().unwrap(); let expected_ident = TMessageIdentifier::new("foo", TMessageType::Exception, 10); assert_eq!(rcvd_ident, expected_ident); @@ -245,8 +241,7 @@ mod tests { let p = TMultiplexedProcessor::new(); p.process(&mut i, &mut o).unwrap(); // at this point an error should be written out - i.transport - .set_readable_bytes(&o.transport.write_bytes()); + i.transport.set_readable_bytes(&o.transport.write_bytes()); let rcvd_ident = i.read_message_begin().unwrap(); let expected_ident = TMessageIdentifier::new("missing:call", TMessageType::Exception, 10); assert_eq!(rcvd_ident, expected_ident); @@ -265,7 +260,8 @@ mod tests { impl TProcessor for Service { fn process(&self, _: &mut TInputProtocol, _: &mut TOutputProtocol) -> ::Result<()> { - let res = self.invoked + let res = self + .invoked .compare_and_swap(false, true, Ordering::Relaxed); if res { Ok(()) @@ -280,9 +276,13 @@ mod tests { let (mut i, mut o) = build_objects(); // build the services - let svc_1 = Service { invoked: Arc::new(AtomicBool::new(false)) }; + let svc_1 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; let atm_1 = svc_1.invoked.clone(); - let svc_2 = Service { invoked: Arc::new(AtomicBool::new(false)) }; + let svc_2 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; let atm_2 = svc_2.invoked.clone(); // register them @@ -309,9 +309,13 @@ mod tests { let (mut i, mut o) = build_objects(); // build the services - let svc_1 = Service { invoked: Arc::new(AtomicBool::new(false)) }; + let svc_1 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; let atm_1 = svc_1.invoked.clone(); - let svc_2 = Service { invoked: Arc::new(AtomicBool::new(false)) }; + let svc_2 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; let atm_2 = svc_2.invoked.clone(); // register them @@ -333,12 +337,15 @@ mod tests { assert_eq!(atm_2.load(Ordering::Relaxed), true); } - fn build_objects() - -> (TBinaryInputProtocol>, - TBinaryOutputProtocol>) - { + fn build_objects() -> ( + TBinaryInputProtocol>, + TBinaryOutputProtocol>, + ) { let c = TBufferChannel::with_capacity(128, 128); let (r_c, w_c) = c.split().unwrap(); - (TBinaryInputProtocol::new(r_c, true), TBinaryOutputProtocol::new(w_c, true)) + ( + TBinaryInputProtocol::new(r_c, true), + TBinaryOutputProtocol::new(w_c, true), + ) } } diff --git a/lib/rs/src/server/threaded.rs b/lib/rs/src/server/threaded.rs index 515b20d757c..8139a4e2789 100644 --- a/lib/rs/src/server/threaded.rs +++ b/lib/rs/src/server/threaded.rs @@ -19,9 +19,9 @@ use std::net::{TcpListener, TcpStream}; use std::sync::Arc; use threadpool::ThreadPool; -use {ApplicationError, ApplicationErrorKind}; use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory}; use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory}; +use {ApplicationError, ApplicationErrorKind}; use super::TProcessor; @@ -129,11 +129,13 @@ where } impl TServer - where PRC: TProcessor + Send + Sync + 'static, - RTF: TReadTransportFactory + 'static, - IPF: TInputProtocolFactory + 'static, - WTF: TWriteTransportFactory + 'static, - OPF: TOutputProtocolFactory + 'static { +where + PRC: TProcessor + Send + Sync + 'static, + RTF: TReadTransportFactory + 'static, + IPF: TInputProtocolFactory + 'static, + WTF: TWriteTransportFactory + 'static, + OPF: TOutputProtocolFactory + 'static, +{ /// Create a `TServer`. /// /// Each accepted connection has an input and output half, each of which @@ -155,10 +157,7 @@ impl TServer w_trans_factory: write_transport_factory, o_proto_factory: output_protocol_factory, processor: Arc::new(processor), - worker_pool: ThreadPool::with_name( - "Thrift service processor".to_owned(), - num_workers, - ), + worker_pool: ThreadPool::with_name("Thrift service processor".to_owned(), num_workers), } } @@ -179,7 +178,7 @@ impl TServer let (i_prot, o_prot) = self.new_protocols_for_connection(s)?; let processor = self.processor.clone(); self.worker_pool - .execute(move || handle_incoming_connection(processor, i_prot, o_prot),); + .execute(move || handle_incoming_connection(processor, i_prot, o_prot)); } Err(e) => { warn!("failed to accept remote connection with error {:?}", e); @@ -187,17 +186,12 @@ impl TServer } } - Err( - ::Error::Application( - ApplicationError { - kind: ApplicationErrorKind::Unknown, - message: "aborted listen loop".into(), - }, - ), - ) + Err(::Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: "aborted listen loop".into(), + })) } - fn new_protocols_for_connection( &mut self, stream: TcpStream, diff --git a/lib/rs/src/transport/buffered.rs b/lib/rs/src/transport/buffered.rs index 41b941c3ec8..87cfeff960e 100644 --- a/lib/rs/src/transport/buffered.rs +++ b/lib/rs/src/transport/buffered.rs @@ -192,7 +192,10 @@ where /// `read_capacity` and an internal write buffer of size /// `write_capacity` that wraps the given `TIoChannel`. pub fn with_capacity(write_capacity: usize, channel: C) -> TBufferedWriteTransport { - assert!(write_capacity > 0, "write buffer size must be a positive integer"); + assert!( + write_capacity > 0, + "write buffer size must be a positive integer" + ); TBufferedWriteTransport { buf: Vec::with_capacity(write_capacity), diff --git a/lib/rs/src/transport/framed.rs b/lib/rs/src/transport/framed.rs index 7e0f8b6c3c3..a00930778c9 100644 --- a/lib/rs/src/transport/framed.rs +++ b/lib/rs/src/transport/framed.rs @@ -201,8 +201,7 @@ where if let 0 = message_size { return Ok(()); } else { - self.channel - .write_i32::(message_size as i32)?; + self.channel.write_i32::(message_size as i32)?; } // will spin if the underlying channel can't be written to @@ -240,7 +239,7 @@ impl TWriteTransportFactory for TFramedWriteTransportFactory { #[cfg(test)] mod tests { use super::*; - use ::transport::mem::TBufferChannel; + use transport::mem::TBufferChannel; // FIXME: test a forced reserve @@ -249,12 +248,10 @@ mod tests { let c = TBufferChannel::with_capacity(10, 10); let mut t = TFramedReadTransport::with_capacity(8, c); - t.chan.set_readable_bytes( - &[ - 0x00, 0x00, 0x00, 0x04, /* message size */ - 0x00, 0x01, 0x02, 0x03 /* message body */ - ] - ); + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x04, /* message size */ + 0x00, 0x01, 0x02, 0x03, /* message body */ + ]); let mut buf = vec![0; 8]; @@ -268,12 +265,10 @@ mod tests { let c = TBufferChannel::with_capacity(10, 10); let mut t = TFramedReadTransport::with_capacity(2, c); - t.chan.set_readable_bytes( - &[ - 0x00, 0x00, 0x00, 0x04, /* message size */ - 0x00, 0x01, 0x02, 0x03 /* message body */ - ] - ); + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x04, /* message size */ + 0x00, 0x01, 0x02, 0x03, /* message body */ + ]); let mut buf = vec![0; 8]; @@ -291,12 +286,10 @@ mod tests { // 1st message // - t.chan.set_readable_bytes( - &[ - 0x00, 0x00, 0x00, 0x04, /* message size */ - 0x00, 0x01, 0x02, 0x03 /* message body */ - ] - ); + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x04, /* message size */ + 0x00, 0x01, 0x02, 0x03, /* message body */ + ]); let mut buf = vec![0; 8]; @@ -308,12 +301,10 @@ mod tests { // 2nd message // - t.chan.set_readable_bytes( - &[ - 0x00, 0x00, 0x00, 0x01, /* message size */ - 0x04 /* message body */ - ] - ); + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x01, /* message size */ + 0x04, /* message body */ + ]); let mut buf = vec![0; 8]; @@ -356,8 +347,8 @@ mod tests { assert!(t.flush().is_ok()); let expected_bytes = [ - 0x00, 0x00, 0x00, 0x05, /* message size */ - 0x00, 0x01, 0x02, 0x03, 0x04 /* message body */ + 0x00, 0x00, 0x00, 0x05, /* message size */ + 0x00, 0x01, 0x02, 0x03, 0x04, /* message body */ ]; assert_eq_transport_written_bytes!(t, expected_bytes); @@ -382,8 +373,8 @@ mod tests { assert!(t.flush().is_ok()); let expected_bytes = [ - 0x00, 0x00, 0x00, 0x03, /* message size */ - 0x00, 0x01, 0x02 /* message body */ + 0x00, 0x00, 0x00, 0x03, /* message size */ + 0x00, 0x01, 0x02, /* message body */ ]; assert_eq_transport_written_bytes!(t, expected_bytes); @@ -408,8 +399,8 @@ mod tests { assert!(t.flush().is_ok()); let expected_bytes = [ - 0x00, 0x00, 0x00, 0x03, /* message size */ - 0x00, 0x01, 0x02 /* message body */ + 0x00, 0x00, 0x00, 0x03, /* message size */ + 0x00, 0x01, 0x02, /* message body */ ]; assert_eq_transport_written_bytes!(t, expected_bytes); diff --git a/lib/rs/src/transport/mem.rs b/lib/rs/src/transport/mem.rs index 86ac6bb25f2..82c4b579f60 100644 --- a/lib/rs/src/transport/mem.rs +++ b/lib/rs/src/transport/mem.rs @@ -57,25 +57,17 @@ impl TBufferChannel { /// read buffer capacity and write buffer capacity. pub fn with_capacity(read_capacity: usize, write_capacity: usize) -> TBufferChannel { TBufferChannel { - read: Arc::new( - Mutex::new( - ReadData { - buf: vec![0; read_capacity].into_boxed_slice(), - idx: 0, - pos: 0, - cap: read_capacity, - }, - ), - ), - write: Arc::new( - Mutex::new( - WriteData { - buf: vec![0; write_capacity].into_boxed_slice(), - pos: 0, - cap: write_capacity, - }, - ), - ), + read: Arc::new(Mutex::new(ReadData { + buf: vec![0; read_capacity].into_boxed_slice(), + idx: 0, + pos: 0, + cap: read_capacity, + })), + write: Arc::new(Mutex::new(WriteData { + buf: vec![0; write_capacity].into_boxed_slice(), + pos: 0, + cap: write_capacity, + })), } } @@ -151,20 +143,20 @@ impl TIoChannel for TBufferChannel { where Self: Sized, { - Ok( - (ReadHalf { - handle: TBufferChannel { - read: self.read.clone(), - write: self.write.clone(), - }, - }, - WriteHalf { - handle: TBufferChannel { - read: self.read.clone(), - write: self.write.clone(), - }, - }), - ) + Ok(( + ReadHalf { + handle: TBufferChannel { + read: self.read.clone(), + write: self.write.clone(), + }, + }, + WriteHalf { + handle: TBufferChannel { + read: self.read.clone(), + write: self.write.clone(), + }, + }, + )) } } diff --git a/lib/rs/src/transport/mod.rs b/lib/rs/src/transport/mod.rs index 6e84bfa492b..a623350103e 100644 --- a/lib/rs/src/transport/mod.rs +++ b/lib/rs/src/transport/mod.rs @@ -29,32 +29,31 @@ use std::ops::{Deref, DerefMut}; #[cfg(test)] macro_rules! assert_eq_transport_num_written_bytes { - ($transport:ident, $num_written_bytes:expr) => { - { - assert_eq!($transport.channel.write_bytes().len(), $num_written_bytes); - } - }; + ($transport:ident, $num_written_bytes:expr) => {{ + assert_eq!($transport.channel.write_bytes().len(), $num_written_bytes); + }}; } - #[cfg(test)] macro_rules! assert_eq_transport_written_bytes { - ($transport:ident, $expected_bytes:ident) => { - { - assert_eq!($transport.channel.write_bytes(), &$expected_bytes); - } - }; + ($transport:ident, $expected_bytes:ident) => {{ + assert_eq!($transport.channel.write_bytes(), &$expected_bytes); + }}; } mod buffered; mod framed; -mod socket; mod mem; +mod socket; -pub use self::buffered::{TBufferedReadTransport, TBufferedReadTransportFactory, - TBufferedWriteTransport, TBufferedWriteTransportFactory}; -pub use self::framed::{TFramedReadTransport, TFramedReadTransportFactory, TFramedWriteTransport, - TFramedWriteTransportFactory}; +pub use self::buffered::{ + TBufferedReadTransport, TBufferedReadTransportFactory, TBufferedWriteTransport, + TBufferedWriteTransportFactory, +}; +pub use self::framed::{ + TFramedReadTransport, TFramedReadTransportFactory, TFramedWriteTransport, + TFramedWriteTransportFactory, +}; pub use self::mem::TBufferChannel; pub use self::socket::TTcpChannel; @@ -78,17 +77,9 @@ pub trait TWriteTransportFactory { fn create(&self, channel: Box) -> Box; } -impl TReadTransport for T -where - T: Read, -{ -} +impl TReadTransport for T where T: Read {} -impl TWriteTransport for T -where - T: Write, -{ -} +impl TWriteTransport for T where T: Write {} // FIXME: implement the Debug trait for boxed transports diff --git a/lib/rs/src/transport/socket.rs b/lib/rs/src/transport/socket.rs index 954e2f58669..0bef67bed00 100644 --- a/lib/rs/src/transport/socket.rs +++ b/lib/rs/src/transport/socket.rs @@ -20,8 +20,8 @@ use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{Shutdown, TcpStream}; -use {TransportErrorKind, new_transport_error}; use super::{ReadHalf, TIoChannel, WriteHalf}; +use {new_transport_error, TransportErrorKind}; /// Bidirectional TCP/IP channel. /// @@ -76,18 +76,18 @@ impl TTcpChannel { /// The passed-in stream is assumed to have been opened before being wrapped /// by the created `TTcpChannel` instance. pub fn with_stream(stream: TcpStream) -> TTcpChannel { - TTcpChannel { stream: Some(stream) } + TTcpChannel { + stream: Some(stream), + } } /// Connect to `remote_address`, which should have the form `host:port`. pub fn open(&mut self, remote_address: &str) -> ::Result<()> { if self.stream.is_some() { - Err( - new_transport_error( - TransportErrorKind::AlreadyOpen, - "tcp connection previously opened", - ), - ) + Err(new_transport_error( + TransportErrorKind::AlreadyOpen, + "tcp connection previously opened", + )) } else { match TcpStream::connect(&remote_address) { Ok(s) => { @@ -112,11 +112,13 @@ impl TTcpChannel { where F: FnMut(&mut TcpStream) -> io::Result, { - if let Some(ref mut s) = self.stream { stream_operation(s) } else { - Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),) + Err(io::Error::new( + ErrorKind::NotConnected, + "tcp endpoint not connected", + )) } } } @@ -131,21 +133,21 @@ impl TIoChannel for TTcpChannel { s.stream .as_mut() .and_then(|s| s.try_clone().ok()) - .map( - |cloned| { - let read_half = ReadHalf::new( TTcpChannel { stream: s.stream.take() } ); - let write_half = WriteHalf::new( TTcpChannel { stream: Some(cloned) } ); - (read_half, write_half) - }, - ) - .ok_or_else( - || { - new_transport_error( - TransportErrorKind::Unknown, - "cannot clone underlying tcp stream", - ) - }, - ) + .map(|cloned| { + let read_half = ReadHalf::new(TTcpChannel { + stream: s.stream.take(), + }); + let write_half = WriteHalf::new(TTcpChannel { + stream: Some(cloned), + }); + (read_half, write_half) + }) + .ok_or_else(|| { + new_transport_error( + TransportErrorKind::Unknown, + "cannot clone underlying tcp stream", + ) + }) } } diff --git a/lib/rs/test/src/bin/kitchen_sink_client.rs b/lib/rs/test/src/bin/kitchen_sink_client.rs index fb6ea15cc10..d295c8870d6 100644 --- a/lib/rs/test/src/bin/kitchen_sink_client.rs +++ b/lib/rs/test/src/bin/kitchen_sink_client.rs @@ -28,10 +28,13 @@ use kitchen_sink::midlayer::{MealServiceSyncClient, TMealServiceSyncClient}; use kitchen_sink::recursive; use kitchen_sink::recursive::{CoRec, CoRec2, RecList, RecTree, TTestServiceSyncClient}; use kitchen_sink::ultimate::{FullMealServiceSyncClient, TFullMealServiceSyncClient}; -use thrift::transport::{ReadHalf, TFramedReadTransport, TFramedWriteTransport, TIoChannel, - TTcpChannel, WriteHalf}; -use thrift::protocol::{TBinaryInputProtocol, TBinaryOutputProtocol, TCompactInputProtocol, - TCompactOutputProtocol, TInputProtocol, TOutputProtocol}; +use thrift::protocol::{ + TBinaryInputProtocol, TBinaryOutputProtocol, TCompactInputProtocol, TCompactOutputProtocol, + TInputProtocol, TOutputProtocol, +}; +use thrift::transport::{ + ReadHalf, TFramedReadTransport, TFramedWriteTransport, TIoChannel, TTcpChannel, WriteHalf, +}; fn main() { match run() { @@ -61,17 +64,20 @@ fn run() -> thrift::Result<()> { let service = matches.value_of("service").unwrap_or("part"); let (i_chan, o_chan) = tcp_channel(host, port)?; - let (i_tran, o_tran) = (TFramedReadTransport::new(i_chan), TFramedWriteTransport::new(o_chan)); + let (i_tran, o_tran) = ( + TFramedReadTransport::new(i_chan), + TFramedWriteTransport::new(o_chan), + ); let (i_prot, o_prot): (Box, Box) = match protocol { - "binary" => { - (Box::new(TBinaryInputProtocol::new(i_tran, true)), - Box::new(TBinaryOutputProtocol::new(o_tran, true))) - } - "compact" => { - (Box::new(TCompactInputProtocol::new(i_tran)), - Box::new(TCompactOutputProtocol::new(o_tran))) - } + "binary" => ( + Box::new(TBinaryInputProtocol::new(i_tran, true)), + Box::new(TBinaryOutputProtocol::new(o_tran, true)), + ), + "compact" => ( + Box::new(TCompactInputProtocol::new(i_tran)), + Box::new(TCompactOutputProtocol::new(o_tran)), + ), unmatched => return Err(format!("unsupported protocol {}", unmatched).into()), }; @@ -87,7 +93,10 @@ fn run_client( "full" => exec_full_meal_client(i_prot, o_prot), "part" => exec_meal_client(i_prot, o_prot), "recursive" => exec_recursive_client(i_prot, o_prot), - _ => Err(thrift::Error::from(format!("unknown service type {}", service)),), + _ => Err(thrift::Error::from(format!( + "unknown service type {}", + service + ))), } } @@ -110,12 +119,9 @@ fn exec_meal_client( // this is because the MealService struct does not contain the appropriate service marker // only the following three calls work - execute_call("part", "ramen", || client.ramen(50)) - .map(|_| ())?; - execute_call("part", "meal", || client.meal()) - .map(|_| ())?; - execute_call("part", "napkin", || client.napkin()) - .map(|_| ())?; + execute_call("part", "ramen", || client.ramen(50)).map(|_| ())?; + execute_call("part", "meal", || client.meal()).map(|_| ())?; + execute_call("part", "napkin", || client.napkin()).map(|_| ())?; Ok(()) } @@ -126,14 +132,10 @@ fn exec_full_meal_client( ) -> thrift::Result<()> { let mut client = FullMealServiceSyncClient::new(i_prot, o_prot); - execute_call("full", "ramen", || client.ramen(100)) - .map(|_| ())?; - execute_call("full", "meal", || client.meal()) - .map(|_| ())?; - execute_call("full", "napkin", || client.napkin()) - .map(|_| ())?; - execute_call("full", "full meal", || client.full_meal()) - .map(|_| ())?; + execute_call("full", "ramen", || client.ramen(100)).map(|_| ())?; + execute_call("full", "meal", || client.meal()).map(|_| ())?; + execute_call("full", "napkin", || client.napkin()).map(|_| ())?; + execute_call("full", "full meal", || client.full_meal()).map(|_| ())?; Ok(()) } @@ -145,114 +147,75 @@ fn exec_recursive_client( let mut client = recursive::TestServiceSyncClient::new(i_prot, o_prot); let tree = RecTree { - children: Some( - vec![ - Box::new( - RecTree { - children: Some( - vec![ - Box::new( - RecTree { - children: None, - item: Some(3), - }, - ), - Box::new( - RecTree { - children: None, - item: Some(4), - }, - ), - ], - ), - item: Some(2), - }, - ), - ], - ), + children: Some(vec![Box::new(RecTree { + children: Some(vec![ + Box::new(RecTree { + children: None, + item: Some(3), + }), + Box::new(RecTree { + children: None, + item: Some(4), + }), + ]), + item: Some(2), + })]), item: Some(1), }; let expected_tree = RecTree { - children: Some( - vec![ - Box::new( - RecTree { - children: Some( - vec![ - Box::new( - RecTree { - children: Some(Vec::new()), // remote returns an empty list - item: Some(3), - }, - ), - Box::new( - RecTree { - children: Some(Vec::new()), // remote returns an empty list - item: Some(4), - }, - ), - ], - ), - item: Some(2), - }, - ), - ], - ), + children: Some(vec![Box::new(RecTree { + children: Some(vec![ + Box::new(RecTree { + children: Some(Vec::new()), // remote returns an empty list + item: Some(3), + }), + Box::new(RecTree { + children: Some(Vec::new()), // remote returns an empty list + item: Some(4), + }), + ]), + item: Some(2), + })]), item: Some(1), }; let returned_tree = execute_call("recursive", "echo_tree", || client.echo_tree(tree.clone()))?; if returned_tree != expected_tree { - return Err( - format!( - "mismatched recursive tree {:?} {:?}", - expected_tree, - returned_tree - ) - .into(), - ); + return Err(format!( + "mismatched recursive tree {:?} {:?}", + expected_tree, returned_tree + ) + .into()); } let list = RecList { - nextitem: Some( - Box::new( - RecList { - nextitem: Some( - Box::new( - RecList { - nextitem: None, - item: Some(3), - }, - ), - ), - item: Some(2), - }, - ), - ), + nextitem: Some(Box::new(RecList { + nextitem: Some(Box::new(RecList { + nextitem: None, + item: Some(3), + })), + item: Some(2), + })), item: Some(1), }; let returned_list = execute_call("recursive", "echo_list", || client.echo_list(list.clone()))?; if returned_list != list { - return Err(format!("mismatched recursive list {:?} {:?}", list, returned_list).into(),); + return Err(format!("mismatched recursive list {:?} {:?}", list, returned_list).into()); } let co_rec = CoRec { - other: Some( - Box::new( - CoRec2 { - other: Some(CoRec { other: Some(Box::new(CoRec2 { other: None })) }), - }, - ), - ), + other: Some(Box::new(CoRec2 { + other: Some(CoRec { + other: Some(Box::new(CoRec2 { other: None })), + }), + })), }; - let returned_co_rec = execute_call( - "recursive", - "echo_co_rec", - || client.echo_co_rec(co_rec.clone()), - )?; + let returned_co_rec = execute_call("recursive", "echo_co_rec", || { + client.echo_co_rec(co_rec.clone()) + })?; if returned_co_rec != co_rec { - return Err(format!("mismatched co_rec {:?} {:?}", co_rec, returned_co_rec).into(),); + return Err(format!("mismatched co_rec {:?} {:?}", co_rec, returned_co_rec).into()); } Ok(()) @@ -266,14 +229,10 @@ where match res { Ok(_) => println!("{}: completed {} call", service_type, call_name), - Err(ref e) => { - println!( - "{}: failed {} call with error {:?}", - service_type, - call_name, - e - ) - } + Err(ref e) => println!( + "{}: failed {} call with error {:?}", + service_type, call_name, e + ), } res diff --git a/lib/rs/test/src/bin/kitchen_sink_server.rs b/lib/rs/test/src/bin/kitchen_sink_server.rs index e2c4a271f21..73801eaf892 100644 --- a/lib/rs/test/src/bin/kitchen_sink_server.rs +++ b/lib/rs/test/src/bin/kitchen_sink_server.rs @@ -20,20 +20,29 @@ extern crate clap; extern crate kitchen_sink; extern crate thrift; -use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory, - TCompactInputProtocolFactory, TCompactOutputProtocolFactory, - TInputProtocolFactory, TOutputProtocolFactory}; +use thrift::protocol::{ + TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory, TCompactInputProtocolFactory, + TCompactOutputProtocolFactory, TInputProtocolFactory, TOutputProtocolFactory, +}; use thrift::server::TServer; -use thrift::transport::{TFramedReadTransportFactory, TFramedWriteTransportFactory, - TReadTransportFactory, TWriteTransportFactory}; +use thrift::transport::{ + TFramedReadTransportFactory, TFramedWriteTransportFactory, TReadTransportFactory, + TWriteTransportFactory, +}; use kitchen_sink::base_one::Noodle; -use kitchen_sink::base_two::{BrothType, Napkin, NapkinServiceSyncHandler, Ramen, RamenServiceSyncHandler}; -use kitchen_sink::midlayer::{Dessert, Meal, MealServiceSyncHandler, MealServiceSyncProcessor, Pie}; +use kitchen_sink::base_two::{ + BrothType, Napkin, NapkinServiceSyncHandler, Ramen, RamenServiceSyncHandler, +}; +use kitchen_sink::midlayer::{ + Dessert, Meal, MealServiceSyncHandler, MealServiceSyncProcessor, Pie, +}; use kitchen_sink::recursive; -use kitchen_sink::ultimate::{Drink, FullMeal, FullMealAndDrinks, - FullMealAndDrinksServiceSyncProcessor, FullMealServiceSyncHandler}; use kitchen_sink::ultimate::FullMealAndDrinksServiceSyncHandler; +use kitchen_sink::ultimate::{ + Drink, FullMeal, FullMealAndDrinks, FullMealAndDrinksServiceSyncProcessor, + FullMealServiceSyncHandler, +}; fn main() { match run() { @@ -46,7 +55,6 @@ fn main() { } fn run() -> thrift::Result<()> { - let matches = clap_app!(rust_kitchen_sink_server => (version: "0.1.0") (author: "Apache Thrift Developers ") @@ -67,21 +75,22 @@ fn run() -> thrift::Result<()> { let r_transport_factory = TFramedReadTransportFactory::new(); let w_transport_factory = TFramedWriteTransportFactory::new(); - let (i_protocol_factory, o_protocol_factory): (Box, - Box) = - match &*protocol { - "binary" => { - (Box::new(TBinaryInputProtocolFactory::new()), - Box::new(TBinaryOutputProtocolFactory::new())) - } - "compact" => { - (Box::new(TCompactInputProtocolFactory::new()), - Box::new(TCompactOutputProtocolFactory::new())) - } - unknown => { - return Err(format!("unsupported transport type {}", unknown).into()); - } - }; + let (i_protocol_factory, o_protocol_factory): ( + Box, + Box, + ) = match &*protocol { + "binary" => ( + Box::new(TBinaryInputProtocolFactory::new()), + Box::new(TBinaryOutputProtocolFactory::new()), + ), + "compact" => ( + Box::new(TCompactInputProtocolFactory::new()), + Box::new(TCompactOutputProtocolFactory::new()), + ), + unknown => { + return Err(format!("unsupported transport type {}", unknown).into()); + } + }; // FIXME: should processor be boxed as well? // @@ -94,33 +103,27 @@ fn run() -> thrift::Result<()> { // // Since what I'm doing is uncommon I'm just going to duplicate the code match &*service { - "part" => { - run_meal_server( - &listen_address, - r_transport_factory, - i_protocol_factory, - w_transport_factory, - o_protocol_factory, - ) - } - "full" => { - run_full_meal_server( - &listen_address, - r_transport_factory, - i_protocol_factory, - w_transport_factory, - o_protocol_factory, - ) - } - "recursive" => { - run_recursive_server( - &listen_address, - r_transport_factory, - i_protocol_factory, - w_transport_factory, - o_protocol_factory, - ) - } + "part" => run_meal_server( + &listen_address, + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + ), + "full" => run_full_meal_server( + &listen_address, + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + ), + "recursive" => run_recursive_server( + &listen_address, + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + ), unknown => Err(format!("unsupported service type {}", unknown).into()), } } diff --git a/tutorial/rs/src/bin/tutorial_client.rs b/tutorial/rs/src/bin/tutorial_client.rs index e7192b6164f..c80fafc2f10 100644 --- a/tutorial/rs/src/bin/tutorial_client.rs +++ b/tutorial/rs/src/bin/tutorial_client.rs @@ -22,8 +22,9 @@ extern crate thrift; extern crate thrift_tutorial; use thrift::protocol::{TCompactInputProtocol, TCompactOutputProtocol}; -use thrift::transport::{ReadHalf, TFramedReadTransport, TFramedWriteTransport, TIoChannel, - TTcpChannel, WriteHalf}; +use thrift::transport::{ + ReadHalf, TFramedReadTransport, TFramedWriteTransport, TIoChannel, TTcpChannel, WriteHalf, +}; use thrift_tutorial::shared::TSharedServiceSyncClient; use thrift_tutorial::tutorial::{CalculatorSyncClient, Operation, TCalculatorSyncClient, Work}; @@ -70,8 +71,7 @@ fn run() -> thrift::Result<()> { let logid = 32; // let's do...a multiply! - let res = client - .calculate(logid, Work::new(7, 8, Operation::Multiply, None))?; + let res = client.calculate(logid, Work::new(7, 8, Operation::Multiply, None))?; println!("multiplied 7 and 8 and got {}", res); // let's get the log for it @@ -103,8 +103,7 @@ fn run() -> thrift::Result<()> { type ClientInputProtocol = TCompactInputProtocol>>; type ClientOutputProtocol = TCompactOutputProtocol>>; -fn new_client - ( +fn new_client( host: &str, port: u16, ) -> thrift::Result> { diff --git a/tutorial/rs/src/bin/tutorial_server.rs b/tutorial/rs/src/bin/tutorial_server.rs index 171c4ce3147..95b1a2b6eab 100644 --- a/tutorial/rs/src/bin/tutorial_server.rs +++ b/tutorial/rs/src/bin/tutorial_server.rs @@ -65,7 +65,9 @@ fn run() -> thrift::Result<()> { let o_prot_fact = TCompactOutputProtocolFactory::new(); // demux incoming messages - let processor = CalculatorSyncProcessor::new(CalculatorServer { ..Default::default() }); + let processor = CalculatorSyncProcessor::new(CalculatorServer { + ..Default::default() + }); // create the server and start listening let mut server = TServer::new( @@ -87,7 +89,9 @@ struct CalculatorServer { impl Default for CalculatorServer { fn default() -> CalculatorServer { - CalculatorServer { log: Mutex::new(HashMap::new()) } + CalculatorServer { + log: Mutex::new(HashMap::new()), + } } } @@ -122,12 +126,10 @@ impl CalculatorSyncHandler for CalculatorServer { let res = if let Some(ref op) = w.op { if w.num1.is_none() || w.num2.is_none() { - Err( - InvalidOperation { - what_op: Some(*op as i32), - why: Some("no operands specified".to_owned()), - }, - ) + Err(InvalidOperation { + what_op: Some(*op as i32), + why: Some("no operands specified".to_owned()), + }) } else { // so that I don't have to call unwrap() multiple times below let num1 = w.num1.as_ref().expect("operands checked"); @@ -139,12 +141,10 @@ impl CalculatorSyncHandler for CalculatorServer { Operation::Multiply => Ok(num1 * num2), Operation::Divide => { if *num2 == 0 { - Err( - InvalidOperation { - what_op: Some(*op as i32), - why: Some("divide by 0".to_owned()), - }, - ) + Err(InvalidOperation { + what_op: Some(*op as i32), + why: Some("divide by 0".to_owned()), + }) } else { Ok(num1 / num2) } @@ -152,7 +152,10 @@ impl CalculatorSyncHandler for CalculatorServer { } } } else { - Err(InvalidOperation::new(None, "no operation specified".to_owned()),) + Err(InvalidOperation::new( + None, + "no operation specified".to_owned(), + )) }; // if the operation was successful log it