From f4588df86a5ce99ee628dda731f7fa172e8eb8ae Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Mon, 6 Feb 2017 22:36:21 -0500 Subject: [PATCH 01/19] used rust fmt --- .travis.yml | 10 +- src/authenticators.rs | 8 +- src/client.rs | 123 ++++---- src/compression.rs | 22 +- src/connection_manager.rs | 16 +- src/consistency.rs | 47 +-- src/error.rs | 4 +- src/events.rs | 17 +- src/frame/events.rs | 62 ++-- src/frame/frame_auth_challenge.rs | 6 +- src/frame/frame_auth_response.rs | 4 +- src/frame/frame_auth_success.rs | 2 +- src/frame/frame_authenticate.rs | 6 +- src/frame/frame_batch.rs | 23 +- src/frame/frame_error.rs | 87 +++--- src/frame/frame_event.rs | 2 +- src/frame/frame_execute.rs | 11 +- src/frame/frame_options.rs | 4 +- src/frame/frame_prepare.rs | 8 +- src/frame/frame_query.rs | 111 +++---- src/frame/frame_ready.rs | 10 +- src/frame/frame_register.rs | 6 +- src/frame/frame_response.rs | 55 ++-- src/frame/frame_result.rs | 171 ++++++----- src/frame/frame_startup.rs | 10 +- src/frame/frame_supported.rs | 35 +-- src/frame/mod.rs | 38 +-- src/frame/parser.rs | 16 +- src/query.rs | 62 ++-- src/transport.rs | 75 +++-- src/types/data_serialization_types.rs | 24 +- src/types/list.rs | 419 ++++++++++++-------------- src/types/map.rs | 288 +++++++++--------- src/types/mod.rs | 23 +- src/types/rows.rs | 108 ++++--- src/types/udt.rs | 52 ++-- src/types/value.rs | 18 +- 37 files changed, 1006 insertions(+), 977 deletions(-) diff --git a/.travis.yml b/.travis.yml index d993f8f..1786558 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,15 @@ rust: matrix: allow_failures: - rust: nightly - +cache: cargo +before_script: (cargo install rustfmt || true) +script: +- | + export PATH=$PATH:~/.cargo/bin && + cargo fmt -- --write-mode=diff && + cargo build && + cargo test + after_success: sudo apt-get install libcurl4-openssl-dev libelf-dev libdw-dev && wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && diff --git a/src/authenticators.rs b/src/authenticators.rs index cab50ba..b9c43b0 100644 --- a/src/authenticators.rs +++ b/src/authenticators.rs @@ -8,14 +8,14 @@ pub trait Authenticator: Clone { #[derive(Debug, Clone)] pub struct PasswordAuthenticator<'a> { username: &'a str, - password: &'a str + password: &'a str, } impl<'a> PasswordAuthenticator<'a> { pub fn new<'b>(username: &'b str, password: &'b str) -> PasswordAuthenticator<'b> { return PasswordAuthenticator { username: username, - password: password + password: password, }; } } @@ -47,7 +47,6 @@ impl Authenticator for NoneAuthenticator { fn get_cassandra_name(&self) -> Option<&str> { return None; } - } @@ -69,7 +68,8 @@ mod tests { #[test] fn test_password_authenticator_get_cassandra_name() { let auth = PasswordAuthenticator::new("foo", "bar"); - assert_eq!(auth.get_cassandra_name(), Some("org.apache.cassandra.auth.PasswordAuthenticator")); + assert_eq!(auth.get_cassandra_name(), + Some("org.apache.cassandra.auth.PasswordAuthenticator")); } #[test] diff --git a/src/client.rs b/src/client.rs index 216fbae..208d0e2 100644 --- a/src/client.rs +++ b/src/client.rs @@ -20,26 +20,26 @@ use events::{Listener, EventStream, new_listener}; /// CDRS driver structure that provides a basic functionality to work with DB including /// establishing new connection, getting supported options, preparing and executing CQL /// queries, using compression and other. -pub struct CDRS { +pub struct CDRS { compressor: Compression, authenticator: T, - transport: X + transport: X, } /// Map of options supported by Cassandra server. pub type CassandraOptions = HashMap>; -impl<'a, T: Authenticator + 'a, X: CDRSTransport + 'a> CDRS { +impl<'a, T: Authenticator + 'a, X: CDRSTransport + 'a> CDRS { /// The method creates new instance of CDRS driver. At this step an instance doesn't /// connected to DB Server. To create new instance two parameters are needed to be /// provided - `addr` is IP address of DB Server, `authenticator` is a selected authenticator /// that is supported by particular DB Server. There are few authenticators already /// provided by this trait. - pub fn new(transport: X, authenticator: T) -> CDRS { + pub fn new(transport: X, authenticator: T) -> CDRS { return CDRS { compressor: Compression::None, authenticator: authenticator, - transport: transport + transport: transport, }; } @@ -54,8 +54,8 @@ impl<'a, T: Authenticator + 'a, X: CDRSTransport + 'a> CDRS { .map(|frame| match frame.get_body() { ResponseBody::Supported(ref supported_body) => { return supported_body.data.clone(); - }, - _ => unreachable!() + } + _ => unreachable!(), }); } @@ -66,7 +66,7 @@ impl<'a, T: Authenticator + 'a, X: CDRSTransport + 'a> CDRS { /// method provided by CRDR driver, it's `Compression::None` that tells drivers that it /// should work without compression. If compression is provided then incomming frames /// will be decompressed automatically. - pub fn start(mut self, compressor: Compression) -> error::Result> { + pub fn start(mut self, compressor: Compression) -> error::Result> { self.compressor = compressor; let startup_frame = Frame::new_req_startup(compressor.as_str()).into_cbytes(); @@ -83,23 +83,24 @@ impl<'a, T: Authenticator + 'a, X: CDRSTransport + 'a> CDRS { .expect("Cassandra Server did communicate that it needed password authentication but the auth schema was missing in the body response"); - //This creates a new scope; avoiding a clone + // This creates a new scope; avoiding a clone // and we check whether // 1. any authenticators has been passed in by client and if not send error back - // 2. authenticator is provided by the client and `auth_scheme` presented by the server and client are same - // if not send error back + // 2. authenticator is provided by the client and `auth_scheme` presented by + // the server and client are same if not send error back // 3. if it falls through it means the preliminary conditions are true - let auth_check = self.authenticator.get_cassandra_name() + let auth_check = self.authenticator + .get_cassandra_name() .ok_or(error::Error::General("No authenticator was provided ".to_string())) .map(|auth| { if authenticator.as_str() != auth { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of authenticator. {:?} got, + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of authenticator. {:?} got, but {} is supported.", - authenticator, - authenticator.as_str())); + authenticator, + authenticator.as_str())); return Err(error::Error::Io(io_err)); } return Ok(()); @@ -110,7 +111,8 @@ impl<'a, T: Authenticator + 'a, X: CDRSTransport + 'a> CDRS { } let auth_token_bytes = self.authenticator.get_auth_token().into_cbytes(); - try!(self.transport.write(Frame::new_req_auth_response(auth_token_bytes).into_cbytes().as_slice())); + try!(self.transport + .write(Frame::new_req_auth_response(auth_token_bytes).into_cbytes().as_slice())); try!(parse_frame(&mut self.transport, &compressor)); return Ok(Session::start(self)); @@ -122,26 +124,27 @@ impl<'a, T: Authenticator + 'a, X: CDRSTransport + 'a> CDRS { } fn drop_connection(&mut self) -> error::Result<()> { - return self.transport.close(net::Shutdown::Both) + return self.transport + .close(net::Shutdown::Both) .map_err(|err| error::Error::Io(err)); } } /// The object that provides functionality for communication with Cassandra server. -pub struct Session { +pub struct Session { started: bool, - cdrs: CDRS, - compressor: Compression + cdrs: CDRS, + compressor: Compression, } -impl Session { +impl Session { /// Creates new session basing on CDRS instance. - pub fn start(cdrs: CDRS) -> Session { + pub fn start(cdrs: CDRS) -> Session { let compressor = cdrs.compressor.clone(); return Session { cdrs: cdrs, started: true, - compressor: compressor + compressor: compressor, }; } @@ -166,12 +169,11 @@ impl Session { } /// The method makes a request to DB Server to prepare provided query. - pub fn prepare( - &mut self, - query: String, - with_tracing: bool, - with_warnings: bool - ) -> error::Result { + pub fn prepare(&mut self, + query: String, + with_tracing: bool, + with_warnings: bool) + -> error::Result { let mut flags = vec![]; if with_tracing { flags.push(Flag::Tracing); @@ -190,13 +192,12 @@ impl Session { /// The method makes a request to DB Server to execute a query with provided id /// using provided query parameters. `id` is an ID of a query which Server /// returns back to a driver as a response to `prepare` request. - pub fn execute( - &mut self, - id: CBytesShort, - query_parameters: QueryParams, - with_tracing: bool, - with_warnings: bool - ) -> error::Result { + pub fn execute(&mut self, + id: CBytesShort, + query_parameters: QueryParams, + with_tracing: bool, + with_warnings: bool) + -> error::Result { let mut flags = vec![]; if with_tracing { @@ -214,15 +215,15 @@ impl Session { /// The method makes a request to DB Server to execute a query provided in `query` argument. /// you can build the query with QueryBuilder /// ``` - /// let qb = QueryBuilder::new().query("select * from emp").consistency(Consistency::One).page_size(Some(4)); + /// let qb = QueryBuilder::new().query("select * from emp") + /// .consistency(Consistency::One).page_size(Some(4)); /// session.query_with_builder(qb); /// ``` - pub fn query( - &mut self, - query: Query, - with_tracing: bool, - with_warnings: bool - ) -> error::Result { + pub fn query(&mut self, + query: Query, + with_tracing: bool, + with_warnings: bool) + -> error::Result { let mut flags = vec![]; if with_tracing { @@ -234,25 +235,25 @@ impl Session { } let query_frame = Frame::new_req_query(query.query, - query.consistency, - query.values, - query.with_names, - query.page_size, - query.paging_state, - query.serial_consistency, - query.timestamp, - flags).into_cbytes(); + query.consistency, + query.values, + query.with_names, + query.page_size, + query.paging_state, + query.serial_consistency, + query.timestamp, + flags) + .into_cbytes(); try!(self.cdrs.transport.write(query_frame.as_slice())); return parse_frame(&mut self.cdrs.transport, &self.compressor); } - pub fn batch( - &mut self, - batch_query: QueryBatch, - with_tracing: bool, - with_warnings: bool - ) -> error::Result { + pub fn batch(&mut self, + batch_query: QueryBatch, + with_tracing: bool, + with_warnings: bool) + -> error::Result { let mut flags = vec![]; if with_tracing { @@ -270,7 +271,9 @@ impl Session { } /// It consumes CDRS - pub fn listen_for<'a>(mut self, events: Vec) -> error::Result<(Listener, EventStream)> { + pub fn listen_for<'a>(mut self, + events: Vec) + -> error::Result<(Listener, EventStream)> { let query_frame = Frame::new_req_register(events).into_cbytes(); try!(self.cdrs.transport.write(query_frame.as_slice())); try!(parse_frame(&mut self.cdrs.transport, &self.compressor)); diff --git a/src/compression.rs b/src/compression.rs index 5097578..92deb4c 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -19,14 +19,14 @@ pub enum CompressionError { /// Snappy error. Snappy(Box), /// Lz4 error. - Lz4(String) + Lz4(String), } impl fmt::Display for CompressionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &CompressionError::Snappy(ref err) => write!(f, "Snappy Error: {:?}", err), - &CompressionError::Lz4(ref s) => write!(f, "Lz4 Error: {:?}", s) + &CompressionError::Lz4(ref s) => write!(f, "Lz4 Error: {:?}", s), } } } @@ -35,7 +35,7 @@ impl Error for CompressionError { fn description(&self) -> &str { let desc = match self { &CompressionError::Snappy(ref err) => err.description(), - &CompressionError::Lz4(ref s) => s.as_str() + &CompressionError::Lz4(ref s) => s.as_str(), }; return desc; @@ -65,7 +65,7 @@ pub enum Compression { /// [snappy](https://code.google.com/p/snappy/) compression Snappy, /// Non compression - None + None, } impl Compression { @@ -74,7 +74,7 @@ impl Compression { return match self { &Compression::Lz4 => Compression::encode_lz4(bytes), &Compression::Snappy => Compression::encode_snappy(bytes), - &Compression::None => Ok(bytes) + &Compression::None => Ok(bytes), }; } @@ -83,7 +83,7 @@ impl Compression { return match self { &Compression::Lz4 => Compression::decode_lz4(bytes), &Compression::Snappy => Compression::decode_snappy(bytes), - &Compression::None => Ok(bytes) + &Compression::None => Ok(bytes), }; } @@ -92,21 +92,19 @@ impl Compression { return match self { &Compression::Lz4 => Some(LZ4), &Compression::Snappy => Some(SNAPPY), - &Compression::None => None + &Compression::None => None, }; } fn encode_snappy(bytes: Vec) -> Result> { let mut encoder = snap::Encoder::new(); - return encoder - .compress_vec(bytes.as_slice()) + return encoder.compress_vec(bytes.as_slice()) .map_err(|err| CompressionError::Snappy(Box::new(err))); } fn decode_snappy(bytes: Vec) -> Result> { let mut decoder = snap::Decoder::new(); - return decoder - .decompress_vec(bytes.as_slice()) + return decoder.decompress_vec(bytes.as_slice()) .map_err(|err| CompressionError::Snappy(Box::new(err))); } @@ -137,7 +135,7 @@ impl<'a> From<&'a str> for Compression { return match compression_str { LZ4 => Compression::Lz4, SNAPPY => Compression::Snappy, - _ => Compression::None + _ => Compression::None, }; } } diff --git a/src/connection_manager.rs b/src/connection_manager.rs index fa3d726..ac9d4a8 100644 --- a/src/connection_manager.rs +++ b/src/connection_manager.rs @@ -3,22 +3,23 @@ //! please refer to original documentation. use query::QueryBuilder; use client::{CDRS, Session}; -use error::{Error as CError}; +use error::Error as CError; use authenticators::Authenticator; use compression::Compression; use r2d2; use transport::CDRSTransport; /// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`. -pub struct ConnectionManager { +pub struct ConnectionManager { transport: X, authenticator: T, - compression: Compression + compression: Compression, } -impl ConnectionManager { - /// Creates a new instance of `ConnectionManager`. - /// It requires transport, authenticator and compression as inputs. +impl +ConnectionManager { +/// Creates a new instance of `ConnectionManager`. +/// It requires transport, authenticator and compression as inputs. pub fn new(transport: X, authenticator: T, compression: Compression) -> ConnectionManager { ConnectionManager { @@ -29,7 +30,8 @@ impl r2d2::ManageConnection for ConnectionManager { +impl +r2d2::ManageConnection for ConnectionManager { type Connection = Session; type Error = CError; diff --git a/src/consistency.rs b/src/consistency.rs index b2afa68..cab52ca 100644 --- a/src/consistency.rs +++ b/src/consistency.rs @@ -32,7 +32,7 @@ pub enum Consistency { #[allow(missing_docs)] LocalSerial, #[allow(missing_docs)] - LocalOne + LocalOne, } impl Default for Consistency { @@ -54,7 +54,7 @@ impl IntoBytes for Consistency { &Consistency::EachQuorum => to_short(0x0007), &Consistency::Serial => to_short(0x0008), &Consistency::LocalSerial => to_short(0x0009), - &Consistency::LocalOne => to_short(0x000A) + &Consistency::LocalOne => to_short(0x000A), }; } } @@ -73,7 +73,7 @@ impl From for Consistency { 0x0008 => Consistency::Serial, 0x0009 => Consistency::LocalSerial, 0x000A => Consistency::LocalOne, - _ => unreachable!() + _ => unreachable!(), }; } } @@ -92,7 +92,7 @@ impl FromBytes for Consistency { 0x0008 => Consistency::Serial, 0x0009 => Consistency::LocalSerial, 0x000A => Consistency::LocalOne, - _ => unreachable!() + _ => unreachable!(), }; } } @@ -150,26 +150,39 @@ mod tests { assert_eq!(Consistency::from_bytes(vec![0, 3]), Consistency::Three); assert_eq!(Consistency::from_bytes(vec![0, 4]), Consistency::Quorum); assert_eq!(Consistency::from_bytes(vec![0, 5]), Consistency::All); - assert_eq!(Consistency::from_bytes(vec![0, 6]), Consistency::LocalQuorum); + assert_eq!(Consistency::from_bytes(vec![0, 6]), + Consistency::LocalQuorum); assert_eq!(Consistency::from_bytes(vec![0, 7]), Consistency::EachQuorum); assert_eq!(Consistency::from_bytes(vec![0, 8]), Consistency::Serial); - assert_eq!(Consistency::from_bytes(vec![0, 9]), Consistency::LocalSerial); + assert_eq!(Consistency::from_bytes(vec![0, 9]), + Consistency::LocalSerial); assert_eq!(Consistency::from_bytes(vec![0, 10]), Consistency::LocalOne); } #[test] fn test_consistency_from_cursor() { - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 0])), Consistency::Any); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 1])), Consistency::One); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 2])), Consistency::Two); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 3])), Consistency::Three); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 4])), Consistency::Quorum); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 5])), Consistency::All); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 6])), Consistency::LocalQuorum); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 7])), Consistency::EachQuorum); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 8])), Consistency::Serial); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 9])), Consistency::LocalSerial); - assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 10])), Consistency::LocalOne); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 0])), + Consistency::Any); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 1])), + Consistency::One); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 2])), + Consistency::Two); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 3])), + Consistency::Three); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 4])), + Consistency::Quorum); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 5])), + Consistency::All); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 6])), + Consistency::LocalQuorum); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 7])), + Consistency::EachQuorum); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 8])), + Consistency::Serial); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 9])), + Consistency::LocalSerial); + assert_eq!(Consistency::from_cursor(&mut Cursor::new(vec![0, 10])), + Consistency::LocalOne); } } diff --git a/src/error.rs b/src/error.rs index 1bfd020..fe48965 100644 --- a/src/error.rs +++ b/src/error.rs @@ -27,7 +27,7 @@ pub enum Error { /// Internal Compression/Decompression error Compression(CompressionError), /// Server error. - Server(CDRSError) + Server(CDRSError), } impl fmt::Display for Error { @@ -52,7 +52,7 @@ impl error::Error for Error { Error::FromUtf8(ref err) => err.description(), // FIXME: err.description not found in current scope, std::error::Error not satisfied Error::UUIDParse(_) => "UUID Parse Error", - Error::General(ref err) => err.as_str() + Error::General(ref err) => err.as_str(), } } } diff --git a/src/events.rs b/src/events.rs index 7b49d4c..8a58c4b 100644 --- a/src/events.rs +++ b/src/events.rs @@ -3,11 +3,8 @@ use std::iter::Iterator; use std::error::Error; use error; -use frame::events::{ - ServerEvent as FrameServerEvent, - SimpleServerEvent as FrameSimpleServerEvent, - SchemaChange as FrameSchemaChange -}; +use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent, + SchemaChange as FrameSchemaChange}; use frame::parser::parse_frame; use compression::Compression; use transport::CDRSTransport; @@ -34,7 +31,7 @@ pub fn new_listener(transport: X) -> (Listener, EventStream) { let (tx, rx) = channel(); let listener = Listener { transport: transport, - tx: tx + tx: tx, }; let stream = EventStream { rx: rx }; (listener, stream) @@ -46,10 +43,10 @@ pub fn new_listener(transport: X) -> (Listener, EventStream) { pub struct Listener { transport: X, - tx: Sender + tx: Sender, } -impl Listener { +impl Listener { /// It starts a process of listening to new events. Locks a frame. pub fn start(&mut self, compressor: &Compression) -> error::Result<()> { loop { @@ -64,7 +61,7 @@ impl Listener { }; match self.tx.send(event) { Err(err) => return Err(error::Error::General(err.description().to_string())), - _ => continue + _ => continue, } } } @@ -73,7 +70,7 @@ impl Listener { /// `EventStream` is an iterator which returns new events once they come. /// It is similar to `Receiver::iter`. pub struct EventStream { - rx: Receiver + rx: Receiver, } impl Iterator for EventStream { diff --git a/src/frame/events.rs b/src/frame/events.rs index 3f7cdf5..60bf116 100644 --- a/src/frame/events.rs +++ b/src/frame/events.rs @@ -37,7 +37,7 @@ const AGGREGATE: &'static str = "AGGREGATE"; pub enum SimpleServerEvent { TopologyChange, StatusChange, - SchemaChange + SchemaChange, } impl SimpleServerEvent { @@ -45,7 +45,7 @@ impl SimpleServerEvent { match self { &SimpleServerEvent::TopologyChange => String::from(TOPOLOGY_CHANGE), &SimpleServerEvent::StatusChange => String::from(STATUS_CHANGE), - &SimpleServerEvent::SchemaChange => String::from(SCHEMA_CHANGE) + &SimpleServerEvent::SchemaChange => String::from(SCHEMA_CHANGE), } } } @@ -84,7 +84,7 @@ pub enum ServerEvent { /// Events related to change of node status. StatusChange(StatusChange), /// Events related to schema change. - SchemaChange(SchemaChange) + SchemaChange(SchemaChange), } impl PartialEq for ServerEvent { @@ -97,16 +97,12 @@ impl FromCursor for ServerEvent { fn from_cursor(mut cursor: &mut Cursor>) -> ServerEvent { let event_type = CString::from_cursor(&mut cursor); match event_type.as_str() { - TOPOLOGY_CHANGE => ServerEvent::TopologyChange( - TopologyChange::from_cursor(&mut cursor) - ), - STATUS_CHANGE => ServerEvent::StatusChange( - StatusChange::from_cursor(&mut cursor) - ), - SCHEMA_CHANGE => ServerEvent::SchemaChange( - SchemaChange::from_cursor(&mut cursor) - ), - _ => unreachable!() + TOPOLOGY_CHANGE => { + ServerEvent::TopologyChange(TopologyChange::from_cursor(&mut cursor)) + } + STATUS_CHANGE => ServerEvent::StatusChange(StatusChange::from_cursor(&mut cursor)), + SCHEMA_CHANGE => ServerEvent::SchemaChange(SchemaChange::from_cursor(&mut cursor)), + _ => unreachable!(), } } } @@ -115,7 +111,7 @@ impl FromCursor for ServerEvent { #[derive(Debug)] pub struct TopologyChange { pub change_type: TopologyChangeType, - pub addr: CInet + pub addr: CInet, } impl FromCursor for TopologyChange { @@ -125,7 +121,7 @@ impl FromCursor for TopologyChange { TopologyChange { change_type: change_type, - addr: addr + addr: addr, } } } @@ -133,7 +129,7 @@ impl FromCursor for TopologyChange { #[derive(Debug, PartialEq)] pub enum TopologyChangeType { NewNode, - RemovedNode + RemovedNode, } impl FromCursor for TopologyChangeType { @@ -141,7 +137,7 @@ impl FromCursor for TopologyChangeType { match CString::from_cursor(&mut cursor).as_str() { NEW_NODE => TopologyChangeType::NewNode, REMOVED_NODE => TopologyChangeType::RemovedNode, - _ => unreachable!() + _ => unreachable!(), } } } @@ -150,7 +146,7 @@ impl FromCursor for TopologyChangeType { #[derive(Debug)] pub struct StatusChange { pub change_type: StatusChangeType, - pub addr: CInet + pub addr: CInet, } impl FromCursor for StatusChange { @@ -160,7 +156,7 @@ impl FromCursor for StatusChange { StatusChange { change_type: change_type, - addr: addr + addr: addr, } } } @@ -168,7 +164,7 @@ impl FromCursor for StatusChange { #[derive(Debug, PartialEq)] pub enum StatusChangeType { Up, - Down + Down, } impl FromCursor for StatusChangeType { @@ -176,7 +172,7 @@ impl FromCursor for StatusChangeType { match CString::from_cursor(&mut cursor).as_str() { UP => StatusChangeType::Up, DOWN => StatusChangeType::Down, - _ => unreachable!() + _ => unreachable!(), } } } @@ -186,7 +182,7 @@ impl FromCursor for StatusChangeType { pub struct SchemaChange { pub change_type: ChangeType, pub target: Target, - pub options: ChangeSchemeOptions + pub options: ChangeSchemeOptions, } impl FromCursor for SchemaChange { @@ -198,7 +194,7 @@ impl FromCursor for SchemaChange { SchemaChange { change_type: change_type, target: target, - options: options + options: options, } } } @@ -208,7 +204,7 @@ impl FromCursor for SchemaChange { pub enum ChangeType { Created, Updated, - Dropped + Dropped, } impl FromCursor for ChangeType { @@ -217,7 +213,7 @@ impl FromCursor for ChangeType { CREATED => ChangeType::Created, UPDATED => ChangeType::Updated, DROPPED => ChangeType::Dropped, - _ => unreachable!() + _ => unreachable!(), } } } @@ -229,7 +225,7 @@ pub enum Target { Table, Type, Function, - Aggregate + Aggregate, } impl FromCursor for Target { @@ -240,7 +236,7 @@ impl FromCursor for Target { TYPE => Target::Type, FUNCTION => Target::Function, AGGREGATE => Target::Aggregate, - _ => unreachable!() + _ => unreachable!(), } } } @@ -256,21 +252,23 @@ pub enum ChangeSchemeOptions { /// * keyspace containing the user defined function / aggregate /// * the function/aggregate name /// * list of strings, one string for each argument type (as CQL type) - Function((String, String, Vec)) + Function((String, String, Vec)), } impl ChangeSchemeOptions { - fn from_cursor_and_target(mut cursor: &mut Cursor>, target: &Target) - -> ChangeSchemeOptions { + fn from_cursor_and_target(mut cursor: &mut Cursor>, + target: &Target) + -> ChangeSchemeOptions { match target { &Target::Keyspace => ChangeSchemeOptions::from_cursor_keyspace(&mut cursor), &Target::Table | &Target::Type => ChangeSchemeOptions::from_cursor_table(&mut cursor), - &Target::Function | &Target::Aggregate => ChangeSchemeOptions::from_cursor_function(&mut cursor) + &Target::Function | + &Target::Aggregate => ChangeSchemeOptions::from_cursor_function(&mut cursor), } } fn from_cursor_keyspace(mut cursor: &mut Cursor>) -> ChangeSchemeOptions { - ChangeSchemeOptions::Keyspace(CString::from_cursor(&mut cursor).into_plain()) + ChangeSchemeOptions::Keyspace(CString::from_cursor(&mut cursor).into_plain()) } fn from_cursor_table(mut cursor: &mut Cursor>) -> ChangeSchemeOptions { diff --git a/src/frame/frame_auth_challenge.rs b/src/frame/frame_auth_challenge.rs index dfaebf8..1037558 100644 --- a/src/frame/frame_auth_challenge.rs +++ b/src/frame/frame_auth_challenge.rs @@ -5,14 +5,12 @@ use types::CBytes; /// Server authentication challenge. #[derive(Debug)] pub struct BodyResAuthChallenge { - pub data: CBytes + pub data: CBytes, } impl FromCursor for BodyResAuthChallenge { fn from_cursor(mut cursor: &mut Cursor>) -> BodyResAuthChallenge { - BodyResAuthChallenge { - data: CBytes::from_cursor(&mut cursor) - } + BodyResAuthChallenge { data: CBytes::from_cursor(&mut cursor) } } } diff --git a/src/frame/frame_auth_response.rs b/src/frame/frame_auth_response.rs index 8f6c0e2..d1def92 100644 --- a/src/frame/frame_auth_response.rs +++ b/src/frame/frame_auth_response.rs @@ -4,7 +4,7 @@ use frame::*; #[derive(Debug)] pub struct BodyReqAuthResponse { - data: CBytes + data: CBytes, } impl BodyReqAuthResponse { @@ -39,7 +39,7 @@ impl Frame { body: body.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_auth_success.rs b/src/frame/frame_auth_success.rs index e04b6d2..82732c6 100644 --- a/src/frame/frame_auth_success.rs +++ b/src/frame/frame_auth_success.rs @@ -22,6 +22,6 @@ mod tests { let rnd_bytes: Vec = vec![4, 5, 3, 8, 4, 6, 5, 0, 3, 7, 2]; let mut cursor = Cursor::new(rnd_bytes); let body = BodyReqAuthSuccess::from_cursor(&mut cursor); - assert_eq!(body, BodyReqAuthSuccess{}); + assert_eq!(body, BodyReqAuthSuccess {}); } } diff --git a/src/frame/frame_authenticate.rs b/src/frame/frame_authenticate.rs index 7b80ade..577d5f0 100644 --- a/src/frame/frame_authenticate.rs +++ b/src/frame/frame_authenticate.rs @@ -5,13 +5,11 @@ use types::CString; /// A server authentication challenge. #[derive(Debug)] pub struct BodyResAuthenticate { - pub data: CString + pub data: CString, } impl FromCursor for BodyResAuthenticate { fn from_cursor(mut cursor: &mut Cursor>) -> BodyResAuthenticate { - BodyResAuthenticate { - data: CString::from_cursor(&mut cursor) - } + BodyResAuthenticate { data: CString::from_cursor(&mut cursor) } } } diff --git a/src/frame/frame_batch.rs b/src/frame/frame_batch.rs index 67b266e..067f28d 100644 --- a/src/frame/frame_batch.rs +++ b/src/frame/frame_batch.rs @@ -15,7 +15,7 @@ pub struct BodyReqBatch { /// https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L409 pub query_flags: Vec, pub serial_consistency: Option, - pub timestamp: Option + pub timestamp: Option, } impl IntoBytes for BodyReqBatch { @@ -37,7 +37,7 @@ impl IntoBytes for BodyReqBatch { let flag_byte = self.query_flags .iter() - .fold(0, |mut _bytes, f| _bytes | f.as_byte()); + .fold(0, |mut _bytes, f| _bytes | f.as_byte()); bytes.push(flag_byte); if let Some(ref serial_consistency) = self.serial_consistency { @@ -62,7 +62,7 @@ pub enum BatchType { Unlogged, /// The batch will be a "counter" batch (and non-counter /// statements will be rejected). - Counter + Counter, } impl FromSingleByte for BatchType { @@ -71,7 +71,7 @@ impl FromSingleByte for BatchType { 0 => BatchType::Logged, 1 => BatchType::Unlogged, 2 => BatchType::Counter, - _ => unreachable!() + _ => unreachable!(), } } } @@ -81,7 +81,7 @@ impl AsByte for BatchType { match self { &BatchType::Logged => 0, &BatchType::Unlogged => 1, - &BatchType::Counter => 2 + &BatchType::Counter => 2, } } } @@ -100,14 +100,14 @@ pub struct BatchQuery { /// to implement. This will be fixed in a future version of the native /// protocol. See https://issues.apache.org/jira/browse/CASSANDRA-10246 for /// more details - pub values: Vec<(Option, Value)> + pub values: Vec<(Option, Value)>, } /// It contains either an id of prepared query or CQL string. #[derive(Debug, Clone)] pub enum BatchQuerySubj { PreparedId(CBytesShort), - QueryString(CStringLong) + QueryString(CStringLong), } impl IntoBytes for BatchQuery { @@ -124,7 +124,7 @@ impl IntoBytes for BatchQuery { match self.subject { BatchQuerySubj::PreparedId(ref s) => { bytes.extend_from_slice(s.into_cbytes().as_slice()); - }, + } BatchQuerySubj::QueryString(ref s) => { bytes.extend_from_slice(s.into_cbytes().as_slice()); } @@ -150,10 +150,7 @@ impl IntoBytes for BatchQuery { impl Frame { /// **Note:** This function should be used internally for building query request frames. - pub fn new_req_batch( - query: BodyReqBatch, - flags: Vec - ) -> Frame { + pub fn new_req_batch(query: BodyReqBatch, flags: Vec) -> Frame { let version = Version::Request; // sync client let stream: u64 = 0; @@ -167,7 +164,7 @@ impl Frame { body: query.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_error.rs b/src/frame/frame_error.rs index f3fe328..b51789d 100644 --- a/src/frame/frame_error.rs +++ b/src/frame/frame_error.rs @@ -1,4 +1,5 @@ -//! This modules contains [Cassandra's errors](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1011) +//! This modules contains [Cassandra's errors] +//! (https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1011) //! which server could respond to client. use std::io; @@ -24,7 +25,7 @@ pub struct CDRSError { /// Error message string. pub message: CString, /// Additional information. - pub additional_info: AdditionalErrorInfo + pub additional_info: AdditionalErrorInfo, } impl FromCursor for CDRSError { @@ -35,12 +36,14 @@ impl FromCursor for CDRSError { CDRSError { error_code: error_code, message: message, - additional_info: additional_info + additional_info: additional_info, } } } -/// Additional error info in accordance to [Cassandra protocol v4](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1011). +/// Additional error info in accordance to +/// [Cassandra protocol v4] +/// (https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1011). #[derive(Debug)] pub enum AdditionalErrorInfo { Server(SimpleError), @@ -60,12 +63,13 @@ pub enum AdditionalErrorInfo { Invalid(SimpleError), Config(SimpleError), AlreadyExists(AlreadyExistsError), - Unprepared(UnpreparedError) + Unprepared(UnpreparedError), } impl AdditionalErrorInfo { - pub fn from_cursor_with_code(mut cursor: &mut io::Cursor>, error_code: CInt) - -> AdditionalErrorInfo { + pub fn from_cursor_with_code(mut cursor: &mut io::Cursor>, + error_code: CInt) + -> AdditionalErrorInfo { match error_code { 0x0000 => AdditionalErrorInfo::Server(SimpleError::from_cursor(&mut cursor)), 0x000A => AdditionalErrorInfo::Protocol(SimpleError::from_cursor(&mut cursor)), @@ -74,18 +78,26 @@ impl AdditionalErrorInfo { 0x1001 => AdditionalErrorInfo::Overloaded(SimpleError::from_cursor(&mut cursor)), 0x1002 => AdditionalErrorInfo::IsBootstrapping(SimpleError::from_cursor(&mut cursor)), 0x1003 => AdditionalErrorInfo::Truncate(SimpleError::from_cursor(&mut cursor)), - 0x1100 => AdditionalErrorInfo::WriteTimeout(WriteTimeoutError::from_cursor(&mut cursor)), + 0x1100 => { + AdditionalErrorInfo::WriteTimeout(WriteTimeoutError::from_cursor(&mut cursor)) + } 0x1200 => AdditionalErrorInfo::ReadTimeout(ReadTimeoutError::from_cursor(&mut cursor)), 0x1300 => AdditionalErrorInfo::ReadFailure(ReadFailureError::from_cursor(&mut cursor)), - 0x1400 => AdditionalErrorInfo::FunctionFailure(FunctionFailureError::from_cursor(&mut cursor)), - 0x1500 => AdditionalErrorInfo::WriteFailure(WriteFailureError::from_cursor(&mut cursor)), + 0x1400 => { + AdditionalErrorInfo::FunctionFailure(FunctionFailureError::from_cursor(&mut cursor)) + } + 0x1500 => { + AdditionalErrorInfo::WriteFailure(WriteFailureError::from_cursor(&mut cursor)) + } 0x2000 => AdditionalErrorInfo::Syntax(SimpleError::from_cursor(&mut cursor)), 0x2100 => AdditionalErrorInfo::Unauthorized(SimpleError::from_cursor(&mut cursor)), 0x2200 => AdditionalErrorInfo::Invalid(SimpleError::from_cursor(&mut cursor)), 0x2300 => AdditionalErrorInfo::Config(SimpleError::from_cursor(&mut cursor)), - 0x2400 => AdditionalErrorInfo::AlreadyExists(AlreadyExistsError::from_cursor(&mut cursor)), + 0x2400 => { + AdditionalErrorInfo::AlreadyExists(AlreadyExistsError::from_cursor(&mut cursor)) + } 0x2500 => AdditionalErrorInfo::Unprepared(UnpreparedError::from_cursor(&mut cursor)), - _ => unreachable!() + _ => unreachable!(), } } } @@ -100,7 +112,9 @@ impl FromCursor for SimpleError { } } -/// Additional info about [unavailable exception](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1025) +/// Additional info about +/// [unavailable exception] +/// (https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1025) #[derive(Debug)] pub struct UnavailableError { /// Consistency level of query. @@ -108,7 +122,7 @@ pub struct UnavailableError { /// Number of nodes that should be available to respect `cl`. pub required: CInt, /// Number of replicas that we were know to be alive. - pub alive: CInt + pub alive: CInt, } impl FromCursor for UnavailableError { @@ -120,7 +134,7 @@ impl FromCursor for UnavailableError { UnavailableError { cl: cl, required: required, - alive: alive + alive: alive, } } } @@ -135,7 +149,7 @@ pub struct WriteTimeoutError { /// `i32` representing the number of replicas whose acknowledgement is required to achieve `cl`. pub blockfor: CInt, /// Describes the type of the write that timed out - pub write_type: WriteType + pub write_type: WriteType, } impl FromCursor for WriteTimeoutError { @@ -149,7 +163,7 @@ impl FromCursor for WriteTimeoutError { cl: cl, received: received, blockfor: blockfor, - write_type: write_type + write_type: write_type, }; } } @@ -163,7 +177,7 @@ pub struct ReadTimeoutError { pub received: CInt, /// `i32` representing the number of replicas whose acknowledgement is required to achieve `cl`. pub blockfor: CInt, - data_present: u8 + data_present: u8, } impl ReadTimeoutError { @@ -183,7 +197,7 @@ impl FromCursor for ReadTimeoutError { cl: cl, received: received, blockfor: blockfor, - data_present: data_present + data_present: data_present, } } } @@ -199,7 +213,7 @@ pub struct ReadFailureError { pub blockfor: CInt, /// Represents the number of nodes that experience a failure while executing the request. pub num_failures: CInt, - data_present: u8 + data_present: u8, } impl ReadFailureError { @@ -221,7 +235,7 @@ impl FromCursor for ReadFailureError { received: received, blockfor: blockfor, num_failures: num_failures, - data_present: data_present + data_present: data_present, } } } @@ -234,7 +248,7 @@ pub struct FunctionFailureError { /// The name of the failed function pub function: CString, /// `Vec` one string for each argument type (as CQL type) of the failed function. - pub arg_types: CStringList + pub arg_types: CStringList, } impl FromCursor for FunctionFailureError { @@ -245,12 +259,13 @@ impl FromCursor for FunctionFailureError { FunctionFailureError { keyspace: keyspace, function: function, - arg_types: arg_types + arg_types: arg_types, } } } -/// A non-timeout exception during a write request. [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1106) +/// A non-timeout exception during a write request. +/// [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1106) #[derive(Debug)] pub struct WriteFailureError { /// Consistency of the query having triggered the exception. @@ -262,7 +277,7 @@ pub struct WriteFailureError { /// Represents the number of nodes that experience a failure while executing the request. pub num_failures: CInt, /// describes the type of the write that failed. - pub write_type: WriteType + pub write_type: WriteType, } impl FromCursor for WriteFailureError { @@ -277,12 +292,13 @@ impl FromCursor for WriteFailureError { received: received, blockfor: blockfor, num_failures: num_failures, - write_type: write_type + write_type: write_type, } } } -/// Describes the type of the write that failed. [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1118) +/// Describes the type of the write that failed. +/// [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1118) #[derive(Debug)] pub enum WriteType { /// The write was a non-batched non-counter write @@ -297,7 +313,7 @@ pub enum WriteType { Counter, /// The failure occured during the write to the batch log when a (logged) batch /// write was requested. - BatchLog + BatchLog, } impl FromCursor for WriteType { @@ -308,7 +324,7 @@ impl FromCursor for WriteType { "UNLOGGED_BATCH" => WriteType::UnloggedBatch, "COUNTER" => WriteType::Counter, "BATCH_LOG" => WriteType::BatchLog, - _ => unreachable!() + _ => unreachable!(), } } } @@ -321,7 +337,7 @@ pub struct AlreadyExistsError { /// or the keyspace in which the table that already exists is. pub ks: CString, /// Represents the name of the table that already exists. - pub table: CString + pub table: CString, } impl FromCursor for AlreadyExistsError { @@ -331,26 +347,25 @@ impl FromCursor for AlreadyExistsError { AlreadyExistsError { ks: ks, - table: table + table: table, } } } /// Can be thrown while a prepared statement tries to be /// executed if the provided prepared statement ID is not known by -/// this host. [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1150) +/// this host. [Read more...] +/// (https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L1150) #[derive(Debug)] pub struct UnpreparedError { /// Unknown ID. - pub id: CBytes + pub id: CBytes, } impl FromCursor for UnpreparedError { fn from_cursor(mut cursor: &mut io::Cursor>) -> UnpreparedError { let id = CBytes::from_cursor(&mut cursor); - UnpreparedError { - id: id - } + UnpreparedError { id: id } } } diff --git a/src/frame/frame_event.rs b/src/frame/frame_event.rs index c7722d5..443a1b2 100644 --- a/src/frame/frame_event.rs +++ b/src/frame/frame_event.rs @@ -4,7 +4,7 @@ use frame::events::ServerEvent; #[derive(Debug)] pub struct BodyResEvent { - pub event: ServerEvent + pub event: ServerEvent, } impl FromCursor for BodyResEvent { diff --git a/src/frame/frame_execute.rs b/src/frame/frame_execute.rs index 3b1a591..ed0d707 100644 --- a/src/frame/frame_execute.rs +++ b/src/frame/frame_execute.rs @@ -9,7 +9,7 @@ pub struct BodyReqExecute { /// Id of prepared query id: CBytesShort, /// Query paramaters which have the same meaning as one for `query` - query_parameters: ParamsReqQuery + query_parameters: ParamsReqQuery, } impl BodyReqExecute { @@ -17,7 +17,7 @@ impl BodyReqExecute { pub fn new(id: CBytesShort, query_parameters: ParamsReqQuery) -> BodyReqExecute { BodyReqExecute { id: id, - query_parameters: query_parameters + query_parameters: query_parameters, } } } @@ -33,7 +33,10 @@ impl IntoBytes for BodyReqExecute { impl Frame { /// **Note:** This function should be used internally for building query request frames. - pub fn new_req_execute(id: CBytesShort, query_parameters: ParamsReqQuery, flags: Vec) -> Frame { + pub fn new_req_execute(id: CBytesShort, + query_parameters: ParamsReqQuery, + flags: Vec) + -> Frame { let version = Version::Request; // sync client let stream: u64 = 0; @@ -48,7 +51,7 @@ impl Frame { body: body.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_options.rs b/src/frame/frame_options.rs index 0ea129f..d6a157e 100644 --- a/src/frame/frame_options.rs +++ b/src/frame/frame_options.rs @@ -8,7 +8,7 @@ pub struct BodyReqOptions; impl BodyReqOptions { /// Creates new body of a frame of type `options` pub fn new() -> BodyReqOptions { - BodyReqOptions{} + BodyReqOptions {} } } @@ -38,7 +38,7 @@ impl Frame { body: body.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_prepare.rs b/src/frame/frame_prepare.rs index 78b0cf4..9d91716 100644 --- a/src/frame/frame_prepare.rs +++ b/src/frame/frame_prepare.rs @@ -5,15 +5,13 @@ use IntoBytes; /// Struct that represents a body of a frame of type `prepare` #[derive(Debug)] pub struct BodyReqPrepare { - query: CStringLong + query: CStringLong, } impl BodyReqPrepare { /// Creates new body of a frame of type `prepare` that prepares query `query`. pub fn new(query: String) -> BodyReqPrepare { - BodyReqPrepare { - query: CStringLong::new(query) - } + BodyReqPrepare { query: CStringLong::new(query) } } } @@ -40,7 +38,7 @@ impl Frame { body: body.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_query.rs b/src/frame/frame_query.rs index 699ec86..3c895a2 100644 --- a/src/frame/frame_query.rs +++ b/src/frame/frame_query.rs @@ -1,6 +1,6 @@ #![warn(missing_docs)] //! Contains Query Frame related functionality. -// use self::frame::*; +//! use self::frame::*; use super::*; use consistency::Consistency; use {AsByte, IntoBytes}; @@ -13,51 +13,52 @@ pub struct BodyReqQuery { /// Query string. pub query: CStringLong, /// Query parameters. - pub query_params: ParamsReqQuery + pub query_params: ParamsReqQuery, } impl BodyReqQuery { // Fabric function that produces Query request body. fn new(query: String, - consistency: Consistency, - values: Option>, - with_names: Option, - page_size: Option, - paging_state: Option, - serial_consistency: Option, - timestamp: Option) -> BodyReqQuery { - - // query flags - let mut flags: Vec = vec![]; - if values.is_some() { - flags.push(QueryFlags::Value); - } - if with_names.unwrap_or(false) { - flags.push(QueryFlags::WithNamesForValues); - } - if page_size.is_some() { - flags.push(QueryFlags::PageSize); - } - if serial_consistency.is_some() { - flags.push(QueryFlags::WithSerialConsistency); - } - if timestamp.is_some() { - flags.push(QueryFlags::WithDefaultTimestamp); - } + consistency: Consistency, + values: Option>, + with_names: Option, + page_size: Option, + paging_state: Option, + serial_consistency: Option, + timestamp: Option) + -> BodyReqQuery { + + // query flags + let mut flags: Vec = vec![]; + if values.is_some() { + flags.push(QueryFlags::Value); + } + if with_names.unwrap_or(false) { + flags.push(QueryFlags::WithNamesForValues); + } + if page_size.is_some() { + flags.push(QueryFlags::PageSize); + } + if serial_consistency.is_some() { + flags.push(QueryFlags::WithSerialConsistency); + } + if timestamp.is_some() { + flags.push(QueryFlags::WithDefaultTimestamp); + } - BodyReqQuery { - query: CStringLong::new(query), - query_params: ParamsReqQuery { - consistency: consistency, - flags: flags, - values: values, - page_size: page_size, - paging_state: paging_state, - serial_consistency: serial_consistency, - timestamp: timestamp - } - } + BodyReqQuery { + query: CStringLong::new(query), + query_params: ParamsReqQuery { + consistency: consistency, + flags: flags, + values: values, + page_size: page_size, + paging_state: paging_state, + serial_consistency: serial_consistency, + timestamp: timestamp, + }, } + } } impl IntoBytes for BodyReqQuery { @@ -85,7 +86,7 @@ pub struct ParamsReqQuery { /// Serial `Consistency`. pub serial_consistency: Option, /// Timestamp. - pub timestamp: Option + pub timestamp: Option, } impl ParamsReqQuery { @@ -181,7 +182,7 @@ pub enum QueryFlags { /// If set indicates that Query Params contains default timestamp. WithDefaultTimestamp, /// If set indicates that Query Params values are named ones. - WithNamesForValues + WithNamesForValues, } impl QueryFlags { @@ -275,19 +276,27 @@ impl AsByte for QueryFlags { impl Frame { /// **Note:** This function should be used internally for building query request frames. pub fn new_req_query<'a>(query: String, - consistency: Consistency, - values: Option>, - with_names: Option, - page_size: Option, - paging_state: Option, - serial_consistency: Option, - timestamp: Option, - flags: Vec) -> Frame { + consistency: Consistency, + values: Option>, + with_names: Option, + page_size: Option, + paging_state: Option, + serial_consistency: Option, + timestamp: Option, + flags: Vec) + -> Frame { let version = Version::Request; // sync client let stream: u64 = 0; let opcode = Opcode::Query; - let body = BodyReqQuery::new(query, consistency, values, with_names, page_size, paging_state, serial_consistency, timestamp); + let body = BodyReqQuery::new(query, + consistency, + values, + with_names, + page_size, + paging_state, + serial_consistency, + timestamp); Frame { version: version, @@ -297,7 +306,7 @@ impl Frame { body: body.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_ready.rs b/src/frame/frame_ready.rs index d86026d..f0b09b5 100644 --- a/src/frame/frame_ready.rs +++ b/src/frame/frame_ready.rs @@ -6,13 +6,13 @@ pub struct BodyResReady; impl BodyResReady { pub fn new() -> BodyResReady { - BodyResReady{} + BodyResReady {} } } impl From> for BodyResReady { fn from(_vec: Vec) -> BodyResReady { - BodyResReady{} + BodyResReady {} } } @@ -29,18 +29,18 @@ mod tests { #[test] fn body_res_ready_new() { - assert_eq!(BodyResReady::new(), BodyResReady{}); + assert_eq!(BodyResReady::new(), BodyResReady {}); } #[test] fn body_res_ready_into_cbytes() { - let body = BodyResReady{}; + let body = BodyResReady {}; assert_eq!(body.into_cbytes(), vec![] as Vec); } #[test] fn body_res_ready_from() { let body = BodyResReady::from(vec![]); - assert_eq!(body, BodyResReady{}); + assert_eq!(body, BodyResReady {}); } } diff --git a/src/frame/frame_register.rs b/src/frame/frame_register.rs index 0a58a1f..17d66d2 100644 --- a/src/frame/frame_register.rs +++ b/src/frame/frame_register.rs @@ -5,7 +5,7 @@ use types::{CStringList, CString}; /// The structure which represents a body of a frame of type `options`. pub struct BodyReqRegister { - pub events: Vec + pub events: Vec, } impl IntoBytes for BodyReqRegister { @@ -14,7 +14,7 @@ impl IntoBytes for BodyReqRegister { list: self.events .iter() .map(|event| CString::new(event.as_string())) - .collect() + .collect(), }; events_string_list.into_cbytes() } @@ -40,7 +40,7 @@ impl Frame { body: register_body.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_response.rs b/src/frame/frame_response.rs index 6e7b728..87a8f42 100644 --- a/src/frame/frame_response.rs +++ b/src/frame/frame_response.rs @@ -2,13 +2,8 @@ use std::io::Cursor; use FromCursor; use frame::Opcode; -use frame::frame_result::{ - BodyResResultVoid, - BodyResResultPrepared, - BodyResResultRows, - BodyResResultSetKeyspace, - ResResultBody -}; +use frame::frame_result::{BodyResResultVoid, BodyResResultPrepared, BodyResResultRows, + BodyResResultSetKeyspace, ResResultBody}; use frame::frame_event::BodyResEvent; use frame::frame_error::CDRSError; use frame::frame_supported::*; @@ -34,7 +29,7 @@ pub enum ResponseBody { Batch, AuthChallenge(BodyResAuthChallenge), AuthResponse, - AuthSuccess(BodyReqAuthSuccess) + AuthSuccess(BodyReqAuthSuccess), } impl ResponseBody { @@ -54,27 +49,27 @@ impl ResponseBody { // response frames &Opcode::Error => ResponseBody::Error(CDRSError::from_cursor(&mut cursor)), &Opcode::Ready => ResponseBody::Ready(BodyResResultVoid::from_cursor(&mut cursor)), - &Opcode::Authenticate => ResponseBody::Authenticate( - BodyResAuthenticate::from_cursor(&mut cursor) - ), - &Opcode::Supported => ResponseBody::Supported( - BodyResSupported::from_cursor(&mut cursor) - ), + &Opcode::Authenticate => { + ResponseBody::Authenticate(BodyResAuthenticate::from_cursor(&mut cursor)) + } + &Opcode::Supported => { + ResponseBody::Supported(BodyResSupported::from_cursor(&mut cursor)) + } &Opcode::Result => ResponseBody::Result(ResResultBody::from_cursor(&mut cursor)), &Opcode::Event => ResponseBody::Event(BodyResEvent::from_cursor(&mut cursor)), - &Opcode::AuthChallenge => ResponseBody::AuthChallenge( - BodyResAuthChallenge::from_cursor(&mut cursor) - ), - &Opcode::AuthSuccess => ResponseBody::AuthSuccess( - BodyReqAuthSuccess::from_cursor(&mut cursor) - ) + &Opcode::AuthChallenge => { + ResponseBody::AuthChallenge(BodyResAuthChallenge::from_cursor(&mut cursor)) + } + &Opcode::AuthSuccess => { + ResponseBody::AuthSuccess(BodyReqAuthSuccess::from_cursor(&mut cursor)) + } } } pub fn into_rows(self) -> Option> { match self { ResponseBody::Result(res) => res.into_rows(), - _ => None + _ => None, } } @@ -83,10 +78,10 @@ impl ResponseBody { &ResponseBody::Result(ref res) => { match res { &ResResultBody::Rows(ref rows) => Some(rows), - _ => None + _ => None, } - }, - _ => None + } + _ => None, } } @@ -95,7 +90,7 @@ impl ResponseBody { pub fn into_prepared(self) -> Option { match self { ResponseBody::Result(res) => res.into_prepared(), - _ => None + _ => None, } } @@ -104,7 +99,7 @@ impl ResponseBody { pub fn into_set_keyspace(self) -> Option { match self { ResponseBody::Result(res) => res.into_set_keyspace(), - _ => None + _ => None, } } @@ -113,16 +108,14 @@ impl ResponseBody { pub fn into_server_event(self) -> Option { match self { ResponseBody::Event(event) => Some(event), - _ => None + _ => None, } } pub fn get_authenticator(&self) -> Option { match self { - &ResponseBody::Authenticate(ref auth) => { - Some(auth.data.clone().into_plain()) - }, - _ => None + &ResponseBody::Authenticate(ref auth) => Some(auth.data.clone().into_plain()), + _ => None, } } } diff --git a/src/frame/frame_result.rs b/src/frame/frame_result.rs index daf6425..09a31c7 100644 --- a/src/frame/frame_result.rs +++ b/src/frame/frame_result.rs @@ -17,7 +17,7 @@ pub enum ResultKind { /// Prepeared result. Prepared, /// Schema change result. - SchemaChange + SchemaChange, } impl IntoBytes for ResultKind { @@ -27,7 +27,7 @@ impl IntoBytes for ResultKind { ResultKind::Rows => to_int(0x0002), ResultKind::SetKeyspace => to_int(0x0003), ResultKind::Prepared => to_int(0x0004), - ResultKind::SchemaChange => to_int(0x0005) + ResultKind::SchemaChange => to_int(0x0005), } } } @@ -40,7 +40,7 @@ impl FromBytes for ResultKind { 0x0003 => ResultKind::SetKeyspace, 0x0004 => ResultKind::Prepared, 0x0005 => ResultKind::SchemaChange, - _ => unreachable!() + _ => unreachable!(), } } } @@ -65,18 +65,25 @@ pub enum ResResultBody { /// Prepared response body. Prepared(BodyResResultPrepared), /// Schema change body - SchemaChange(SchemaChange) + SchemaChange(SchemaChange), } impl ResResultBody { - /// It retrieves `ResResultBody` from `io::Cursor` having knowledge about expected kind of result. - fn parse_body_from_cursor(mut cursor: &mut Cursor>, result_kind: ResultKind) -> ResResultBody { + /// It retrieves`ResResultBody` from `io::Cursor` + /// having knowledge about expected kind of result. + fn parse_body_from_cursor(mut cursor: &mut Cursor>, + result_kind: ResultKind) + -> ResResultBody { match result_kind { ResultKind::Void => ResResultBody::Void(BodyResResultVoid::from_cursor(&mut cursor)), ResultKind::Rows => ResResultBody::Rows(BodyResResultRows::from_cursor(&mut cursor)), - ResultKind::SetKeyspace => ResResultBody::SetKeyspace(BodyResResultSetKeyspace::from_cursor(&mut cursor)), - ResultKind::Prepared => ResResultBody::Prepared(BodyResResultPrepared::from_cursor(&mut cursor)), - _ => unimplemented!() + ResultKind::SetKeyspace => { + ResResultBody::SetKeyspace(BodyResResultSetKeyspace::from_cursor(&mut cursor)) + } + ResultKind::Prepared => { + ResResultBody::Prepared(BodyResResultPrepared::from_cursor(&mut cursor)) + } + _ => unimplemented!(), } } @@ -84,7 +91,7 @@ impl ResResultBody { pub fn into_rows(self) -> Option> { match self { ResResultBody::Rows(rows_body) => Some(Row::from_frame_body(rows_body)), - _ => None + _ => None, } } @@ -93,7 +100,7 @@ impl ResResultBody { pub fn into_prepared(self) -> Option { match self { ResResultBody::Prepared(p) => Some(p), - _ => None + _ => None, } } @@ -102,7 +109,7 @@ impl ResResultBody { pub fn into_set_keyspace(self) -> Option { match self { ResResultBody::SetKeyspace(p) => Some(p), - _ => None + _ => None, } } } @@ -142,15 +149,14 @@ impl FromCursor for BodyResResultVoid { #[derive(Debug)] pub struct BodyResResultSetKeyspace { /// It contains name of keyspace that was set. - pub body: CString + pub body: CString, } impl BodyResResultSetKeyspace { - /// Factory function that takes body value and returns new instance of `BodyResResultSetKeyspace`. + /// Factory function that takes body value and + /// returns new instance of `BodyResResultSetKeyspace`. pub fn new(body: CString) -> BodyResResultSetKeyspace { - BodyResResultSetKeyspace { - body: body - } + BodyResResultSetKeyspace { body: body } } } @@ -161,7 +167,8 @@ impl FromCursor for BodyResResultSetKeyspace { } -/// Structure that represents result of type [rows](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L533). +/// Structure that represents result of type +/// [rows](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L533). #[derive(Debug)] pub struct BodyResResultRows { /// Rows metadata @@ -169,26 +176,33 @@ pub struct BodyResResultRows { /// Number of rows. pub rows_count: CInt, /// From spec: it is composed of `rows_count` of rows. - pub rows_content: Vec> + pub rows_content: Vec>, } impl BodyResResultRows { /// It retrieves rows content having knowledge about number of rows and columns. fn get_rows_content(mut cursor: &mut Cursor>, - rows_count: i32, - columns_count: i32) -> Vec> { - (0..rows_count).map(|_| { - return (0..columns_count).map(|_| CBytes::from_cursor(&mut cursor) as CBytes).collect(); - }).collect() + rows_count: i32, + columns_count: i32) + -> Vec> { + (0..rows_count) + .map(|_| { + return (0..columns_count) + .map(|_| CBytes::from_cursor(&mut cursor) as CBytes) + .collect(); + }) + .collect() } /// Returns a list of tuples `(CBytes, ColType)` with value and type of values respectively. /// `n` is a number of row. pub fn nth_row_val_types(&self, n: usize) -> Vec<(CBytes, ColType)> { - let col_types = self.metadata.col_specs + let col_types = self.metadata + .col_specs .iter() .map(|col_spec| col_spec.col_type.id.clone()); - self.rows_content[n].iter() + self.rows_content[n] + .iter() .map(|cbyte| cbyte.clone()) .zip(col_types) .collect() @@ -196,14 +210,15 @@ impl BodyResResultRows { } impl FromCursor for BodyResResultRows { - fn from_cursor(mut cursor: &mut Cursor>) -> BodyResResultRows{ + fn from_cursor(mut cursor: &mut Cursor>) -> BodyResResultRows { let metadata = RowsMetadata::from_cursor(&mut cursor); let rows_count = CInt::from_cursor(&mut cursor); - let rows_content: Vec> = BodyResResultRows::get_rows_content(&mut cursor, rows_count, metadata.columns_count); + let rows_content: Vec> = + BodyResResultRows::get_rows_content(&mut cursor, rows_count, metadata.columns_count); BodyResResultRows { metadata: metadata, rows_count: rows_count, - rows_content: rows_content + rows_content: rows_content, } } } @@ -211,7 +226,9 @@ impl FromCursor for BodyResResultRows { /// Rows metadata. #[derive(Debug, Clone)] pub struct RowsMetadata { - /// Flags. [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L541) + /// Flags. + /// [Read more...] + /// (https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L541) pub flags: i32, /// Number of columns. pub columns_count: i32, @@ -250,7 +267,7 @@ impl FromCursor for RowsMetadata { columns_count: columns_count, paging_state: paging_state, global_table_space: global_table_space, - col_specs: col_specs + col_specs: col_specs, } } } @@ -263,18 +280,18 @@ const NO_METADATA: i32 = 0x0004; pub enum RowsMetadataFlag { GlobalTableSpace, HasMorePages, - NoMetadata + NoMetadata, } impl RowsMetadataFlag { /// Shows if provided flag contains GlobalTableSpace rows metadata flag pub fn has_global_table_space(flag: i32) -> bool { - (flag & GLOBAL_TABLE_SPACE) != 0 + (flag & GLOBAL_TABLE_SPACE) != 0 } /// Sets GlobalTableSpace rows metadata flag pub fn set_global_table_space(flag: i32) -> i32 { - flag | GLOBAL_TABLE_SPACE + flag | GLOBAL_TABLE_SPACE } /// Shows if provided flag contains HasMorePages rows metadata flag @@ -284,17 +301,17 @@ impl RowsMetadataFlag { /// Sets HasMorePages rows metadata flag pub fn set_has_more_pages(flag: i32) -> i32 { - flag | HAS_MORE_PAGES + flag | HAS_MORE_PAGES } /// Shows if provided flag contains NoMetadata rows metadata flag pub fn has_no_metadata(flag: i32) -> bool { - (flag & NO_METADATA) != 0 + (flag & NO_METADATA) != 0 } /// Sets NoMetadata rows metadata flag pub fn set_no_metadata(flag: i32) -> i32 { - flag | NO_METADATA + flag | NO_METADATA } } @@ -303,7 +320,7 @@ impl IntoBytes for RowsMetadataFlag { match *self { RowsMetadataFlag::GlobalTableSpace => to_int(GLOBAL_TABLE_SPACE as i64), RowsMetadataFlag::HasMorePages => to_int(HAS_MORE_PAGES as i64), - RowsMetadataFlag::NoMetadata => to_int(NO_METADATA as i64) + RowsMetadataFlag::NoMetadata => to_int(NO_METADATA as i64), } } } @@ -334,16 +351,19 @@ pub struct ColSpec { /// Column name pub name: CString, /// Column type defined in spec in 4.2.5.2 - pub col_type: ColTypeOption + pub col_type: ColTypeOption, } impl ColSpec { - /// parse_colspecs tables mutable cursor, number of columns (column_count) and flags that indicates + /// parse_colspecs tables mutable cursor, + /// number of columns (column_count) and flags that indicates /// if Global_tables_spec is specified. It returns column_count of ColSpecs. pub fn parse_colspecs(mut cursor: &mut Cursor>, - column_count: i32, - with_globale_table_spec: bool) -> Vec { - (0..column_count).map(|_| { + column_count: i32, + with_globale_table_spec: bool) + -> Vec { + (0..column_count) + .map(|_| { let mut ksname: Option = None; let mut tablename: Option = None; if !with_globale_table_spec { @@ -357,10 +377,11 @@ impl ColSpec { ksname: ksname, tablename: tablename, name: name, - col_type: col_type + col_type: col_type, }; - }).collect() - } + }) + .collect() + } } /// Cassandra data types which clould be returned by a server. @@ -391,7 +412,7 @@ pub enum ColType { Set, Udt, Tuple, - Null + Null, } impl FromBytes for ColType { @@ -422,7 +443,7 @@ impl FromBytes for ColType { 0x0022 => ColType::Set, 0x0030 => ColType::Udt, 0x0031 => ColType::Tuple, - _ => unreachable!() + _ => unreachable!(), } } } @@ -440,8 +461,10 @@ impl FromCursor for ColType { pub struct ColTypeOption { /// Id refers to `ColType`. pub id: ColType, - /// Values depending on column type. [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L569) - pub value: Option + /// Values depending on column type. + /// [Read more...] + /// (https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L569) + pub value: Option, } impl FromCursor for ColTypeOption { @@ -452,23 +475,23 @@ impl FromCursor for ColTypeOption { ColType::Set => { let col_type = ColTypeOption::from_cursor(&mut cursor); Some(ColTypeOptionValue::CSet(Box::new(col_type))) - }, + } ColType::List => { let col_type = ColTypeOption::from_cursor(&mut cursor); Some(ColTypeOptionValue::CList(Box::new(col_type))) - }, + } ColType::Udt => Some(ColTypeOptionValue::UdtType(CUdt::from_cursor(&mut cursor))), ColType::Map => { let name_type = ColTypeOption::from_cursor(&mut cursor); let value_type = ColTypeOption::from_cursor(&mut cursor); Some(ColTypeOptionValue::CMap((Box::new(name_type), Box::new(value_type)))) } - _ => None + _ => None, }; ColTypeOption { id: id, - value: value + value: value, } } } @@ -481,10 +504,11 @@ pub enum ColTypeOptionValue { CSet(Box), CList(Box), UdtType(CUdt), - CMap((Box, Box)) + CMap((Box, Box)), } -/// User defined type. [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L608) +/// User defined type. +/// [Read more...](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L608) #[derive(Debug, Clone)] pub struct CUdt { /// Keyspace name. @@ -492,7 +516,7 @@ pub struct CUdt { /// UDT name pub udt_name: CString, /// List of pairs `(name, type)` where name is field name and type is type of field. - pub descriptions: Vec<(CString, ColTypeOption)> + pub descriptions: Vec<(CString, ColTypeOption)>, } impl FromCursor for CUdt { @@ -500,16 +524,18 @@ impl FromCursor for CUdt { let ks = CString::from_cursor(&mut cursor); let udt_name = CString::from_cursor(&mut cursor); let n = from_bytes(cursor_next_value(&mut cursor, SHORT_LEN as u64)); - let descriptions: Vec<(CString, ColTypeOption)> = (0..n).map(|_| { - let name = CString::from_cursor(&mut cursor); - let col_type = ColTypeOption::from_cursor(&mut cursor); - return (name, col_type); - }).collect(); + let descriptions: Vec<(CString, ColTypeOption)> = (0..n) + .map(|_| { + let name = CString::from_cursor(&mut cursor); + let col_type = ColTypeOption::from_cursor(&mut cursor); + return (name, col_type); + }) + .collect(); CUdt { ks: ks, udt_name: udt_name, - descriptions: descriptions + descriptions: descriptions, } } } @@ -523,7 +549,7 @@ pub struct BodyResResultPrepared { pub metadata: PreparedMetadata, /// It is defined exactly the same as in the Rows /// documentation. - pub result_metadata: RowsMetadata + pub result_metadata: RowsMetadata, } impl FromCursor for BodyResResultPrepared { @@ -535,7 +561,7 @@ impl FromCursor for BodyResResultPrepared { BodyResResultPrepared { id: id, metadata: metadata, - result_metadata: result_metadata + result_metadata: result_metadata, } } } @@ -548,7 +574,7 @@ pub struct PreparedMetadata { pub pk_count: i32, pub pk_indexes: Vec, pub global_table_spec: Option<(CString, CString)>, - pub col_specs: Vec + pub col_specs: Vec, } impl FromCursor for PreparedMetadata { @@ -556,12 +582,11 @@ impl FromCursor for PreparedMetadata { let flags = CInt::from_cursor(&mut cursor); let columns_count = CInt::from_cursor(&mut cursor); let pk_count = CInt::from_cursor(&mut cursor); - let pk_indexes: Vec = (0..pk_count) - .fold(vec![], |mut acc, _| { - let idx = from_bytes(cursor_next_value(&mut cursor, SHORT_LEN as u64)) as i16; - acc.push(idx); - acc - }); + let pk_indexes: Vec = (0..pk_count).fold(vec![], |mut acc, _| { + let idx = from_bytes(cursor_next_value(&mut cursor, SHORT_LEN as u64)) as i16; + acc.push(idx); + acc + }); let mut global_table_space: Option<(CString, CString)> = None; let has_global_table_space = RowsMetadataFlag::has_global_table_space(flags); if has_global_table_space { @@ -577,7 +602,7 @@ impl FromCursor for PreparedMetadata { pk_count: pk_count, pk_indexes: pk_indexes, global_table_spec: global_table_space, - col_specs: col_specs + col_specs: col_specs, } } } diff --git a/src/frame/frame_startup.rs b/src/frame/frame_startup.rs index 4a8c4a8..522a610 100644 --- a/src/frame/frame_startup.rs +++ b/src/frame/frame_startup.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use frame::*; -use types::{to_short}; +use types::to_short; use IntoBytes; const CQL_VERSION: &'static str = "CQL_VERSION"; @@ -10,7 +10,7 @@ const COMPRESSION: &'static str = "COMPRESSION"; #[derive(Debug)] pub struct BodyReqStartup<'a> { - pub map: HashMap<&'static str, &'a str> + pub map: HashMap<&'static str, &'a str>, } impl<'a> BodyReqStartup<'a> { @@ -20,9 +20,7 @@ impl<'a> BodyReqStartup<'a> { if let Some(c) = compression { map.insert(COMPRESSION, c); } - BodyReqStartup { - map: map - } + BodyReqStartup { map: map } } // should be [u8; 2] @@ -71,7 +69,7 @@ impl Frame { body: body.into_cbytes(), // for request frames it's always None tracing_id: None, - warnings: vec![] + warnings: vec![], } } } diff --git a/src/frame/frame_supported.rs b/src/frame/frame_supported.rs index 5074a8b..5dcb157 100644 --- a/src/frame/frame_supported.rs +++ b/src/frame/frame_supported.rs @@ -1,17 +1,11 @@ use std::collections::HashMap; use std::io::Cursor; use FromCursor; -use types::{ - SHORT_LEN, - cursor_next_value, - from_bytes, - CString, - CStringList -}; +use types::{SHORT_LEN, cursor_next_value, from_bytes, CString, CStringList}; #[derive(Debug)] pub struct BodyResSupported { - pub data: HashMap> + pub data: HashMap>, } impl FromCursor for BodyResSupported { @@ -25,9 +19,7 @@ impl FromCursor for BodyResSupported { return m; }); - BodyResSupported { - data: map - } + BodyResSupported { data: map } } } @@ -39,12 +31,21 @@ mod tests { #[test] fn test_name() { - let bytes = vec![ - 0, 1, // n options - // 1-st option - 0, 2, 97, 98, // key [string] "ab" - 0, 2, 0, 1, 97, 0, 1, 98 // value ["a", "b"] - ]; + let bytes = vec![0, + 1, // n options + // 1-st option + 0, + 2, + 97, + 98, // key [string] "ab" + 0, + 2, + 0, + 1, + 97, + 0, + 1, + 98 /* value ["a", "b"] */]; let mut cursor = Cursor::new(bytes); let options = BodyResSupported::from_cursor(&mut cursor).data; assert_eq!(options.len(), 1); diff --git a/src/frame/mod.rs b/src/frame/mod.rs index 318ccdf..57306f7 100644 --- a/src/frame/mod.rs +++ b/src/frame/mod.rs @@ -46,7 +46,7 @@ pub struct Frame { pub stream: u64, // we're going to use 0 here until async client is implemented pub body: Vec, pub tracing_id: Option, - pub warnings: Vec + pub warnings: Vec, } impl Frame { @@ -106,14 +106,14 @@ impl<'a> IntoBytes for Frame { #[derive(Debug, PartialEq)] pub enum Version { Request, - Response + Response, } impl AsByte for Version { fn as_byte(&self) -> u8 { match self { &Version::Request => 0x04, - &Version::Response => 0x84 + &Version::Response => 0x84, } } } @@ -121,8 +121,12 @@ impl AsByte for Version { impl From> for Version { fn from(v: Vec) -> Version { if v.len() != VERSION_LEN { - error!("Unexpected Cassandra verion. Should has {} byte(-s), got {:?}", VERSION_LEN, v); - panic!("Unexpected Cassandra verion. Should has {} byte(-s), got {:?}", VERSION_LEN, v); + error!("Unexpected Cassandra verion. Should has {} byte(-s), got {:?}", + VERSION_LEN, + v); + panic!("Unexpected Cassandra verion. Should has {} byte(-s), got {:?}", + VERSION_LEN, + v); } match v[0] { 0x04 => Version::Request, @@ -143,7 +147,7 @@ pub enum Flag { Tracing, CustomPayload, Warning, - Ignore + Ignore, } impl Flag { @@ -171,24 +175,23 @@ impl Flag { /// The method converts a serie of `Flag`-s into a single byte. pub fn many_to_cbytes(flags: &Vec) -> u8 { - flags - .iter() + flags.iter() .fold(Flag::Ignore.as_byte(), |acc, f| acc | f.as_byte()) } /// Indicates if flags contains `Flag::Compression` pub fn has_compression(flags: u8) -> bool { - (flags & Flag::Compression.as_byte()) > 0 + (flags & Flag::Compression.as_byte()) > 0 } /// Indicates if flags contains `Flag::Tracing` pub fn has_tracing(flags: u8) -> bool { - (flags & Flag::Tracing.as_byte()) > 0 + (flags & Flag::Tracing.as_byte()) > 0 } /// Indicates if flags contains `Flag::CustomPayload` pub fn has_custom_payload(flags: u8) -> bool { - (flags & Flag::CustomPayload.as_byte()) > 0 + (flags & Flag::CustomPayload.as_byte()) > 0 } /// Indicates if flags contains `Flag::Warning` @@ -204,8 +207,9 @@ impl AsByte for Flag { &Flag::Tracing => 0x02, &Flag::CustomPayload => 0x04, &Flag::Warning => 0x08, - &Flag::Ignore => 0x00 // assuming that ingoring value whould be other than [0x01, 0x02, 0x04, 0x08] - } + &Flag::Ignore => 0x00, + // assuming that ingoring value whould be other than [0x01, 0x02, 0x04, 0x08] + } } } @@ -216,7 +220,7 @@ impl From for Flag { 0x02 => Flag::Tracing, 0x04 => Flag::CustomPayload, 0x08 => Flag::Warning, - _ => Flag::Ignore // ignore by specification + _ => Flag::Ignore, // ignore by specification } } } @@ -238,7 +242,7 @@ pub enum Opcode { Batch, AuthChallenge, AuthResponse, - AuthSuccess + AuthSuccess, } impl AsByte for Opcode { @@ -259,7 +263,7 @@ impl AsByte for Opcode { &Opcode::Batch => 0x0D, &Opcode::AuthChallenge => 0x0E, &Opcode::AuthResponse => 0x0F, - &Opcode::AuthSuccess => 0x10 + &Opcode::AuthSuccess => 0x10, } } } @@ -283,7 +287,7 @@ impl From for Opcode { 0x0E => Opcode::AuthChallenge, 0x0F => Opcode::AuthResponse, 0x10 => Opcode::AuthSuccess, - _ => unreachable!() + _ => unreachable!(), } } } diff --git a/src/frame/parser.rs b/src/frame/parser.rs index 0c67b5a..1a03eeb 100644 --- a/src/frame/parser.rs +++ b/src/frame/parser.rs @@ -13,7 +13,7 @@ pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Re let mut flag_bytes = [0; FLAG_LEN]; let mut opcode_bytes = [0; OPCODE_LEN]; let mut stream_bytes = [0; STREAM_LEN]; - let mut length_bytes =[0; LENGTH_LEN]; + let mut length_bytes = [0; LENGTH_LEN]; // NOTE: order of reads matters try!(cursor.read(&mut version_bytes)); @@ -72,7 +72,7 @@ pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Re stream: stream, body: body, tracing_id: tracing_id, - warnings: warnings + warnings: warnings, }; return conver_frame_into_result(frame); @@ -80,10 +80,12 @@ pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Re fn conver_frame_into_result(frame: Frame) -> error::Result { match frame.opcode { - Opcode::Error => match frame.get_body() { - ResponseBody::Error(err) => Err(error::Error::Server(err)), - _ => unreachable!() - }, - _ => Ok(frame) + Opcode::Error => { + match frame.get_body() { + ResponseBody::Error(err) => Err(error::Error::Server(err)), + _ => unreachable!(), + } + } + _ => Ok(frame), } } diff --git a/src/query.rs b/src/query.rs index c80a0eb..448f3f3 100644 --- a/src/query.rs +++ b/src/query.rs @@ -12,8 +12,10 @@ use frame::frame_batch::{BatchType, BatchQuery, BodyReqBatch, BatchQuerySubj}; /// self /// } /// ``` -/// and repeating it for all the attributes; it is extracted out as a macro so that code is more concise -/// see @https://doc.rust-lang.org/book/method-syntax.html +/// and repeating it for all the attributes; it is extracted out as a macro so that code +/// is more concise see +/// @https://doc.rust-lang.org/book/method-syntax.html +/// /// /// macro_rules! builder_opt_field { @@ -38,7 +40,7 @@ pub struct Query { pub page_size: Option, pub paging_state: Option, pub serial_consistency: Option, - pub timestamp: Option + pub timestamp: Option, } /// QueryBuilder is a helper sturcture that helps to construct `Query`. `Query` itself @@ -54,17 +56,14 @@ pub struct QueryBuilder { page_size: Option, paging_state: Option, serial_consistency: Option, - timestamp: Option + timestamp: Option, } impl QueryBuilder { /// Factory function that takes CQL `&str` as an argument and returns new `QueryBuilder`. /// Default consistency level is `One` pub fn new(query: &str) -> QueryBuilder { - return QueryBuilder { - query: query.to_string(), - ..Default::default() - }; + return QueryBuilder { query: query.to_string(), ..Default::default() }; } /// Sets new query consistency @@ -113,7 +112,7 @@ impl QueryBuilder { page_size: self.page_size.clone(), paging_state: self.paging_state.clone(), serial_consistency: self.serial_consistency.clone(), - timestamp: self.timestamp.clone() + timestamp: self.timestamp.clone(), }; } } @@ -129,7 +128,7 @@ pub struct QueryParamsBuilder { page_size: Option, paging_state: Option, serial_consistency: Option, - timestamp: Option + timestamp: Option, } impl QueryParamsBuilder { @@ -141,8 +140,8 @@ impl QueryParamsBuilder { page_size: None, paging_state: None, serial_consistency: None, - timestamp: None - } + timestamp: None, + }; } pub fn values(&mut self, v: Vec) -> &mut Self { @@ -212,7 +211,7 @@ impl QueryParamsBuilder { page_size: self.page_size, paging_state: self.paging_state, serial_consistency: self.serial_consistency, - timestamp: self.timestamp + timestamp: self.timestamp, }; } } @@ -225,7 +224,7 @@ pub struct BatchQueryBuilder { queries: Vec, consistency: Consistency, serial_consistency: Option, - timestamp: Option + timestamp: Option, } impl BatchQueryBuilder { @@ -235,7 +234,7 @@ impl BatchQueryBuilder { queries: vec![], consistency: Consistency::One, serial_consistency: None, - timestamp: None + timestamp: None, } } @@ -245,29 +244,24 @@ impl BatchQueryBuilder { } /// Add a query (non-prepared one) - pub fn add_query( - &mut self, - query: String, - values: Vec - ) -> &mut Self { + pub fn add_query(&mut self, query: String, values: Vec) -> &mut Self { self.queries.push(BatchQuery { is_prepared: false, subject: BatchQuerySubj::QueryString(CStringLong::new(query)), - values: values + values: values, }); self } /// Add a query (prepared one) - pub fn add_query_prepared( - &mut self, - query_id: CBytesShort, - values: Vec - ) -> &mut Self { + pub fn add_query_prepared(&mut self, + query_id: CBytesShort, + values: Vec) + -> &mut Self { self.queries.push(BatchQuery { is_prepared: true, subject: BatchQuerySubj::PreparedId(query_id), - values: values + values: values, }); self } @@ -282,10 +276,7 @@ impl BatchQueryBuilder { self } - pub fn serial_consistency( - &mut self, - serial_consistency: Option - ) -> &mut Self { + pub fn serial_consistency(&mut self, serial_consistency: Option) -> &mut Self { self.serial_consistency = serial_consistency; self } @@ -316,11 +307,8 @@ impl BatchQueryBuilder { .any(|q| q.values.iter().any(|v| v.0.is_some())); if some_names_for_values { - return Err( - CError::General( - String::from("Inconsistent query values - mixed with and without names values") - ) - ); + return Err(CError::General(String::from("Inconsistent query values - mixed \ + with and without names values"))); } } @@ -334,7 +322,7 @@ impl BatchQueryBuilder { query_flags: flags.clone(), consistency: self.consistency.clone(), serial_consistency: self.serial_consistency.clone(), - timestamp: self.timestamp.clone() + timestamp: self.timestamp.clone(), }) } } diff --git a/src/transport.rs b/src/transport.rs index 495ff16..4943854 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -5,8 +5,7 @@ use std::net::TcpStream; #[cfg(feature = "ssl")] use openssl::ssl::{SslStream, SslConnector}; -pub trait CDRSTransport: Sized+Read+Write+Send+Sync{ - +pub trait CDRSTransport: Sized + Read + Write + Send + Sync { fn try_clone(&self) -> io::Result; fn close(&mut self, close: net::Shutdown) -> io::Result<()>; } @@ -14,14 +13,13 @@ pub trait CDRSTransport: Sized+Read+Write+Send+Sync{ #[derive(Debug)] pub struct Transport { - tcp: TcpStream + tcp: TcpStream, } impl Transport { pub fn new(addr: &str) -> io::Result { - TcpStream::connect(addr).map(|socket| Transport {tcp: socket}) + TcpStream::connect(addr).map(|socket| Transport { tcp: socket }) } - } impl Read for Transport { @@ -40,56 +38,48 @@ impl Write for Transport { } } -impl CDRSTransport for Transport { - +impl CDRSTransport for Transport { /// In opposite to `TcpStream`'s `try_clone` this method /// creates absolutely new connection - it gets an address /// of a peer from `Transport` and creates a new encrypted /// transport with new TCP stream under hood. fn try_clone(&self) -> io::Result { - let addr = try!( self.tcp.peer_addr()); - TcpStream::connect(addr).map( | socket | Transport {tcp: socket}) + let addr = try!(self.tcp.peer_addr()); + TcpStream::connect(addr).map(|socket| Transport { tcp: socket }) } fn close(&mut self, close: net::Shutdown) -> io::Result<()> { self.tcp.shutdown(close) } - - } -/*************************************/ +/// ********************************** /** TLS**/ -/**************************************/ - +/// *********************************** #[cfg(feature = "ssl")] pub struct TransportTls { ssl: SslStream, - connector: SslConnector + connector: SslConnector, } #[cfg(feature = "ssl")] impl TransportTls { - - pub fn new(addr: &str, connector: & SslConnector) -> io::Result { + pub fn new(addr: &str, connector: &SslConnector) -> io::Result { let a: Vec<&str> = addr.split(':').collect(); - let res = net::TcpStream::connect(addr) - .map(|socket| - connector.connect(a[0], socket) - .map(|sslsocket| - TransportTls { - ssl: sslsocket, - connector: connector.clone() - } - ) - ); + let res = net::TcpStream::connect(addr).map(|socket| { + connector.connect(a[0], socket) + .map(|sslsocket| { + TransportTls { + ssl: sslsocket, + connector: connector.clone(), + } + }) + }); res.and_then(|res| { - res.map(|n: TransportTls| n ).map_err(|e| io::Error::new(io::ErrorKind::Other,e)) + res.map(|n: TransportTls| n).map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) } - - } #[cfg(feature = "ssl")] impl Read for TransportTls { @@ -109,8 +99,7 @@ impl Write for TransportTls { } #[cfg(feature = "ssl")] -impl CDRSTransport for TransportTls{ - +impl CDRSTransport for TransportTls { /// In opposite to `TcpStream`'s `try_clone` this method /// creates absolutely new connection - it gets an address /// of a peer from `TransportTls` and creates a new encrypted @@ -119,18 +108,26 @@ impl CDRSTransport for TransportTls{ let addr = try!(self.ssl.get_ref().peer_addr()); let ip_string = format!("{}", addr.ip()); - let res = net::TcpStream::connect(addr) - .map(|socket| - self.connector.connect(ip_string.as_str(), socket) - .map(|sslsocket| TransportTls {ssl: sslsocket, connector: self.connector.clone()})); + let res = net::TcpStream::connect(addr).map(|socket| { + self.connector + .connect(ip_string.as_str(), socket) + .map(|sslsocket| { + TransportTls { + ssl: sslsocket, + connector: self.connector.clone(), + } + }) + }); res.and_then(|res| { - res.map(|n: TransportTls| n ).map_err(|e| io::Error::new(io::ErrorKind::Other,e)) + res.map(|n: TransportTls| n).map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) } fn close(&mut self, _close: net::Shutdown) -> io::Result<()> { - self.ssl.shutdown().map_err(|e| io::Error::new(io::ErrorKind::Other,e)).and_then(|_| Ok(())) + self.ssl + .shutdown() + .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) + .and_then(|_| Ok(())) } } - diff --git a/src/types/data_serialization_types.rs b/src/types/data_serialization_types.rs index a6e21bc..5d22fd5 100644 --- a/src/types/data_serialization_types.rs +++ b/src/types/data_serialization_types.rs @@ -11,7 +11,7 @@ use FromCursor; // Decodes Cassandra `ascii` data (bytes) into Rust's `Result`. pub fn decode_custom(bytes: Vec) -> Result { - String::from_utf8(bytes) + String::from_utf8(bytes) } // Decodes Cassandra `ascii` data (bytes) into Rust's `Result`. @@ -21,18 +21,18 @@ pub fn decode_ascii(bytes: Vec) -> Result { // Decodes Cassandra `varchar` data (bytes) into Rust's `Result`. pub fn decode_varchar(bytes: Vec) -> Result { - String::from_utf8(bytes) + String::from_utf8(bytes) } // Decodes Cassandra `bigint` data (bytes) into Rust's `Result` pub fn decode_bigint(bytes: Vec) -> Result { - try_from_bytes(bytes).map(|i| i as i64) + try_from_bytes(bytes).map(|i| i as i64) } // Decodes Cassandra `blob` data (bytes) into Rust's `Result, io::Error>` pub fn decode_blob(bytes: Vec) -> Result, io::Error> { // in fact we just pass it through. - Ok(bytes) + Ok(bytes) } // Decodes Cassandra `boolean` data (bytes) into Rust's `Result` @@ -90,9 +90,7 @@ pub fn decode_float(bytes: Vec) -> Result { pub fn decode_inet(bytes: Vec) -> Result { match bytes.len() { // v4 - 4 => { - Ok(net::IpAddr::V4(net::Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]))) - }, + 4 => Ok(net::IpAddr::V4(net::Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]))), // v6 16 => { let a = from_u16_bytes(bytes[0..2].to_vec()); @@ -104,8 +102,8 @@ pub fn decode_inet(bytes: Vec) -> Result { let g = from_u16_bytes(bytes[12..14].to_vec()); let h = from_u16_bytes(bytes[14..16].to_vec()); Ok(net::IpAddr::V6(net::Ipv6Addr::new(a, b, c, d, e, f, g, h))) - }, - _ => unreachable!() + } + _ => unreachable!(), } } @@ -137,9 +135,11 @@ pub fn decode_set(bytes: Vec) -> Result, io::Error> { pub fn decode_map(bytes: Vec) -> Result, io::Error> { let mut cursor: io::Cursor> = io::Cursor::new(bytes); let l = CInt::from_cursor(&mut cursor); - let list = (0..l).map(|_| { - return (CBytes::from_cursor(&mut cursor), CBytes::from_cursor(&mut cursor)); - }).collect(); + let list = (0..l) + .map(|_| { + return (CBytes::from_cursor(&mut cursor), CBytes::from_cursor(&mut cursor)); + }) + .collect(); Ok(list) } diff --git a/src/types/list.rs b/src/types/list.rs index 11a472c..5a775b0 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -13,18 +13,20 @@ pub struct List { /// column spec of the list, i.e. id should be List as it's a list and value should contain /// a type of list items. metadata: ColTypeOption, - data: Vec + data: Vec, } impl List { pub fn new(data: Vec, metadata: ColTypeOption) -> List { List { metadata: metadata, - data: data + data: data, } } - fn map(&self, f: F) -> Vec where F: FnMut(&CBytes) -> T { + fn map(&self, f: F) -> Vec + where F: FnMut(&CBytes) -> T + { self.data .iter() .map(f) @@ -38,21 +40,17 @@ impl AsRust>> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Blob => Ok( - self.map(|bytes| decode_blob(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Blob => Ok(self.map(|bytes| decode_blob(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Blob => Ok( - self.map(|bytes| decode_blob(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Blob => Ok(self.map(|bytes| decode_blob(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -63,33 +61,29 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Custom => Ok( - self.map(|bytes| decode_custom(bytes.as_plain()).unwrap()) - ), - ColType::Ascii => Ok( - self.map(|bytes| decode_ascii(bytes.as_plain()).unwrap()) - ), - ColType::Varchar => Ok( - self.map(|bytes| decode_varchar(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Custom => { + Ok(self.map(|bytes| decode_custom(bytes.as_plain()).unwrap())) + } + ColType::Ascii => Ok(self.map(|bytes| decode_ascii(bytes.as_plain()).unwrap())), + ColType::Varchar => { + Ok(self.map(|bytes| decode_varchar(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Custom => Ok( - self.map(|bytes| decode_custom(bytes.as_plain()).unwrap()) - ), - ColType::Ascii => Ok( - self.map(|bytes| decode_ascii(bytes.as_plain()).unwrap()) - ), - ColType::Varchar => Ok( - self.map(|bytes| decode_varchar(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Custom => { + Ok(self.map(|bytes| decode_custom(bytes.as_plain()).unwrap())) + } + ColType::Ascii => Ok(self.map(|bytes| decode_ascii(bytes.as_plain()).unwrap())), + ColType::Varchar => { + Ok(self.map(|bytes| decode_varchar(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -100,21 +94,21 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Boolean => Ok( - self.map(|bytes| decode_boolean(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Boolean => { + Ok(self.map(|bytes| decode_boolean(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Boolean => Ok( - self.map(|bytes| decode_boolean(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Boolean => { + Ok(self.map(|bytes| decode_boolean(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -125,39 +119,35 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Bigint => Ok( - self.map(|bytes| decode_bigint(bytes.as_plain()).unwrap()) - ), - ColType::Timestamp => Ok( - self.map(|bytes| decode_timestamp(bytes.as_plain()).unwrap()) - ), - ColType::Time => Ok( - self.map(|bytes| decode_time(bytes.as_plain()).unwrap()) - ), - ColType::Varint => Ok( - self.map(|bytes| decode_varint(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Bigint => { + Ok(self.map(|bytes| decode_bigint(bytes.as_plain()).unwrap())) + } + ColType::Timestamp => { + Ok(self.map(|bytes| decode_timestamp(bytes.as_plain()).unwrap())) + } + ColType::Time => Ok(self.map(|bytes| decode_time(bytes.as_plain()).unwrap())), + ColType::Varint => { + Ok(self.map(|bytes| decode_varint(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Bigint => Ok( - self.map(|bytes| decode_bigint(bytes.as_plain()).unwrap()) - ), - ColType::Timestamp => Ok( - self.map(|bytes| decode_timestamp(bytes.as_plain()).unwrap()) - ), - ColType::Time => Ok( - self.map(|bytes| decode_time(bytes.as_plain()).unwrap()) - ), - ColType::Varint => Ok( - self.map(|bytes| decode_varint(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Bigint => { + Ok(self.map(|bytes| decode_bigint(bytes.as_plain()).unwrap())) + } + ColType::Timestamp => { + Ok(self.map(|bytes| decode_timestamp(bytes.as_plain()).unwrap())) + } + ColType::Time => Ok(self.map(|bytes| decode_time(bytes.as_plain()).unwrap())), + ColType::Varint => { + Ok(self.map(|bytes| decode_varint(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -168,27 +158,19 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Int => Ok( - self.map(|bytes| decode_int(bytes.as_plain()).unwrap()) - ), - ColType::Date => Ok( - self.map(|bytes| decode_date(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Int => Ok(self.map(|bytes| decode_int(bytes.as_plain()).unwrap())), + ColType::Date => Ok(self.map(|bytes| decode_date(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Int => Ok( - self.map(|bytes| decode_int(bytes.as_plain()).unwrap()) - ), - ColType::Date => Ok( - self.map(|bytes| decode_date(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Int => Ok(self.map(|bytes| decode_int(bytes.as_plain()).unwrap())), + ColType::Date => Ok(self.map(|bytes| decode_date(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -199,21 +181,21 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Smallint => Ok( - self.map(|bytes| decode_smallint(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Smallint => { + Ok(self.map(|bytes| decode_smallint(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Smallint => Ok( - self.map(|bytes| decode_smallint(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Smallint => { + Ok(self.map(|bytes| decode_smallint(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -224,21 +206,21 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Double => Ok( - self.map(|bytes| decode_double(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Double => { + Ok(self.map(|bytes| decode_double(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Double => Ok( - self.map(|bytes| decode_double(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Double => { + Ok(self.map(|bytes| decode_double(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -249,27 +231,23 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Decimal => Ok( - self.map(|bytes| decode_decimal(bytes.as_plain()).unwrap()) - ), - ColType::Float => Ok( - self.map(|bytes| decode_float(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Decimal => { + Ok(self.map(|bytes| decode_decimal(bytes.as_plain()).unwrap())) + } + ColType::Float => Ok(self.map(|bytes| decode_float(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Decimal => Ok( - self.map(|bytes| decode_decimal(bytes.as_plain()).unwrap()) - ), - ColType::Float => Ok( - self.map(|bytes| decode_float(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Decimal => { + Ok(self.map(|bytes| decode_decimal(bytes.as_plain()).unwrap())) + } + ColType::Float => Ok(self.map(|bytes| decode_float(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -280,21 +258,17 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Inet => Ok( - self.map(|bytes| decode_inet(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Inet => Ok(self.map(|bytes| decode_inet(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Inet => Ok( - self.map(|bytes| decode_inet(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Inet => Ok(self.map(|bytes| decode_inet(bytes.as_plain()).unwrap())), + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -305,27 +279,27 @@ impl AsRust> for List { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CList(ref type_option) => { match type_option.id { - ColType::Uuid => Ok( - self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap()) - ), - ColType::Timeuuid => Ok( - self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Uuid => { + Ok(self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap())) + } + ColType::Timeuuid => { + Ok(self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, + } ColTypeOptionValue::CSet(ref type_option) => { match type_option.id { - ColType::Uuid => Ok( - self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap()) - ), - ColType::Timeuuid => Ok( - self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap()) - ), - _ => unreachable!() + ColType::Uuid => { + Ok(self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap())) + } + ColType::Timeuuid => { + Ok(self.map(|bytes| decode_timeuuid(bytes.as_plain()).unwrap())) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -341,21 +315,22 @@ impl AsRust> for List { let list_type_option: &ColTypeOption = list_type_option_box.as_ref(); match id { // T is another List - &ColType::List => Ok( - self.map(|bytes| List::new( - decode_list(bytes.as_plain()).unwrap(), - list_type_option.clone()) - ) - ), + &ColType::List => { + Ok(self.map(|bytes| { + List::new(decode_list(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } // T is another Set - &ColType::Set => Ok( - self.map(|bytes| List::new( - decode_list(bytes.as_plain()).unwrap(), - list_type_option.clone())) - ), - _ => unreachable!() + &ColType::Set => { + Ok(self.map(|bytes| { + List::new(decode_list(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } + _ => unreachable!(), } - }, + } // convert CSet of T-s into List of T-s ColTypeOptionValue::CSet(ref type_option) => { let ref id = type_option.id; @@ -363,23 +338,23 @@ impl AsRust> for List { let list_type_option: &ColTypeOption = list_type_option_box.as_ref(); match id { // T is another List - &ColType::List => Ok( - self.map(|bytes| List::new( - decode_list(bytes.as_plain()).unwrap(), - list_type_option.clone()) - ) - ), + &ColType::List => { + Ok(self.map(|bytes| { + List::new(decode_list(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } // T is another Set - &ColType::Set => Ok( - self.map(|bytes| List::new( - decode_list(bytes.as_plain()).unwrap(), - list_type_option.clone()) - ) - ), - _ => unreachable!() + &ColType::Set => { + Ok(self.map(|bytes| { + List::new(decode_list(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } + _ => unreachable!(), } } - _ => unreachable!() + _ => unreachable!(), } } } @@ -395,15 +370,15 @@ impl AsRust> for List { let list_type_option: &ColTypeOption = list_type_option_box.as_ref(); match id { // T is Map - &ColType::Map => Ok( - self.map(|bytes| Map::new( - decode_map(bytes.as_plain()).unwrap(), - list_type_option.clone()) - ) - ), - _ => unreachable!() + &ColType::Map => { + Ok(self.map(|bytes| { + Map::new(decode_map(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } + _ => unreachable!(), } - }, + } // convert CSet of T-s into List of T-s ColTypeOptionValue::CSet(ref type_option) => { let ref id = type_option.id; @@ -411,16 +386,16 @@ impl AsRust> for List { let list_type_option: &ColTypeOption = list_type_option_box.as_ref(); match id { // T is Map - &ColType::Map => Ok( - self.map(|bytes| Map::new( - decode_map(bytes.as_plain()).unwrap(), - list_type_option.clone()) - ) - ), - _ => unreachable!() + &ColType::Map => { + Ok(self.map(|bytes| { + Map::new(decode_map(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } + _ => unreachable!(), } } - _ => unreachable!() + _ => unreachable!(), } } } @@ -435,39 +410,39 @@ impl AsRust> for List { let list_type_option_box: Box = type_option.clone(); let list_type_option = match list_type_option_box.value { Some(ColTypeOptionValue::UdtType(t)) => t, - _ => unreachable!() + _ => unreachable!(), }; match id { // T is Udt - &ColType::Udt => Ok( - self.map(|bytes| UDT::new( - decode_udt(bytes.as_plain()).unwrap(), - list_type_option.clone()) - ) - ), - _ => unreachable!() + &ColType::Udt => { + Ok(self.map(|bytes| { + UDT::new(decode_udt(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } + _ => unreachable!(), } - }, + } // convert CSet of T-s into List of T-s ColTypeOptionValue::CSet(ref type_option) => { let ref id = type_option.id; let list_type_option_box: Box = type_option.clone(); let list_type_option = match list_type_option_box.value { Some(ColTypeOptionValue::UdtType(t)) => t, - _ => unreachable!() + _ => unreachable!(), }; match id { // T is Udt - &ColType::Udt => Ok( - self.map(|bytes| UDT::new( - decode_udt(bytes.as_plain()).unwrap(), - list_type_option.clone()) - ) - ), - _ => unreachable!() + &ColType::Udt => { + Ok(self.map(|bytes| { + UDT::new(decode_udt(bytes.as_plain()).unwrap(), + list_type_option.clone()) + })) + } + _ => unreachable!(), } } - _ => unreachable!() + _ => unreachable!(), } } } diff --git a/src/types/map.rs b/src/types/map.rs index b3f77ce..19206a7 100644 --- a/src/types/map.rs +++ b/src/types/map.rs @@ -12,7 +12,7 @@ use error::Result; #[derive(Debug)] pub struct Map { metadata: ColTypeOption, - data: HashMap + data: HashMap, } impl Map { @@ -28,19 +28,19 @@ impl Map { } // check that key could be converted into String - let serializer = if let ColTypeOptionValue::CMap((key_type, _)) = map_option_type.unwrap() { + let serializer = if let ColTypeOptionValue::CMap((key_type, _)) = + map_option_type.unwrap() { match key_type.id { ColType::Custom => decode_custom, ColType::Ascii => decode_ascii, ColType::Varchar => decode_varchar, - _ => unimplemented!() + _ => unimplemented!(), } } else { unimplemented!(); }; - let map: HashMap = data - .iter() + let map: HashMap = data.iter() .fold(accumulator, |mut acc, kv| { let (key_b, value_b) = kv.clone(); let key: String = serializer(key_b.as_plain()).unwrap(); @@ -52,7 +52,7 @@ impl Map { return Map { metadata: meta, - data: map + data: map, }; } } @@ -66,18 +66,18 @@ impl AsRust>> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Blob => Ok( - self.data + ColType::Blob => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_blob(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -90,34 +90,34 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Custom => Ok( - self.data + ColType::Custom => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_custom(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Ascii => Ok( - self.data + })) + } + ColType::Ascii => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_ascii(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Varchar => Ok( - self.data + })) + } + ColType::Varchar => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_varchar(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -130,18 +130,18 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Boolean => Ok( - self.data + ColType::Boolean => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_boolean(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -154,42 +154,42 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Bigint => Ok( - self.data + ColType::Bigint => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_bigint(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Timestamp => Ok( - self.data + })) + } + ColType::Timestamp => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_timestamp(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Time => Ok( - self.data + })) + } + ColType::Time => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_time(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Varint => Ok( - self.data + })) + } + ColType::Varint => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_varint(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -202,26 +202,26 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Int => Ok( - self.data + ColType::Int => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_int(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Date => Ok( - self.data + })) + } + ColType::Date => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_date(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -234,18 +234,18 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Smallint => Ok( - self.data + ColType::Smallint => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_smallint(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -258,18 +258,18 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Double => Ok( - self.data + ColType::Double => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_double(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -282,26 +282,26 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Decimal => Ok( - self.data + ColType::Decimal => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_decimal(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Float => Ok( - self.data + })) + } + ColType::Float => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_float(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -314,18 +314,18 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Inet => Ok( - self.data + ColType::Inet => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_inet(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -338,26 +338,26 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Uuid => Ok( - self.data + ColType::Uuid => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_timeuuid(vb.as_plain()).unwrap()); return acc; - }) - ), - ColType::Timeuuid => Ok( - self.data + })) + } + ColType::Timeuuid => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { acc.insert(k.clone(), decode_timeuuid(vb.as_plain()).unwrap()); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -370,32 +370,30 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::List => Ok( - self.data + ColType::List => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { - let list = List::new( - decode_list(vb.as_plain()).unwrap(), - value_type_option.as_ref().clone()); + let list = List::new(decode_list(vb.as_plain()).unwrap(), + value_type_option.as_ref().clone()); acc.insert(k.clone(), list); return acc; - }) - ), - ColType::Set => Ok( - self.data + })) + } + ColType::Set => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { - let list = List::new( - decode_list(vb.as_plain()).unwrap(), - value_type_option.as_ref().clone()); + let list = List::new(decode_list(vb.as_plain()).unwrap(), + value_type_option.as_ref().clone()); acc.insert(k.clone(), list); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -408,21 +406,20 @@ impl AsRust> for Map { match self.metadata.value.clone().unwrap() { ColTypeOptionValue::CMap((_, value_type_option)) => { match value_type_option.id { - ColType::Map => Ok( - self.data + ColType::Map => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { - let list = Map::new( - decode_map(vb.as_plain()).unwrap(), - value_type_option.as_ref().clone()); + let list = Map::new(decode_map(vb.as_plain()).unwrap(), + value_type_option.as_ref().clone()); acc.insert(k.clone(), list); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } @@ -436,25 +433,24 @@ impl AsRust> for Map { ColTypeOptionValue::CMap((_, value_type_option)) => { let list_type_option = match value_type_option.value { Some(ColTypeOptionValue::UdtType(ref t)) => t, - _ => unreachable!() + _ => unreachable!(), }; match value_type_option.id { - ColType::Udt => Ok( - self.data + ColType::Udt => { + Ok(self.data .iter() .fold(map, |mut acc, (k, vb)| { - let list = UDT::new( - decode_udt(vb.as_plain()).unwrap(), - list_type_option.clone()); + let list = UDT::new(decode_udt(vb.as_plain()).unwrap(), + list_type_option.clone()); acc.insert(k.clone(), list); return acc; - }) - ), - _ => unreachable!() + })) + } + _ => unreachable!(), } - }, - _ => unreachable!() + } + _ => unreachable!(), } } } diff --git a/src/types/mod.rs b/src/types/mod.rs index af7b007..91e308f 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -10,7 +10,7 @@ use std::io::{Cursor, Read}; use std::net::SocketAddr; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt, ByteOrder}; use {FromBytes, IntoBytes, FromCursor}; -use error::{Result as CDRSResult}; +use error::Result as CDRSResult; use types::data_serialization_types::decode_inet; pub mod data_serialization_types; @@ -121,7 +121,7 @@ pub fn to_int(int: i64) -> Vec { #[derive(Debug, Clone)] pub struct CString { - string: String + string: String, } impl CString { @@ -172,7 +172,7 @@ impl FromCursor for CString { #[derive(Debug, Clone)] pub struct CStringLong { - string: String + string: String, } impl CStringLong { @@ -218,7 +218,7 @@ impl FromCursor for CStringLong { #[derive(Debug, Clone)] pub struct CStringList { - pub list: Vec + pub list: Vec, } impl CStringList { @@ -261,12 +261,12 @@ impl FromCursor for CStringList { } } -/**/ +// #[derive(Debug, Clone)] /// The structure that represents Cassandra byte type pub struct CBytes { - bytes: Vec + bytes: Vec, } impl CBytes { @@ -305,7 +305,7 @@ impl IntoBytes for CBytes { /// Cassandra short bytes #[derive(Debug, Clone)] pub struct CBytesShort { - bytes: Vec + bytes: Vec, } impl CBytesShort { @@ -373,7 +373,7 @@ impl FromBytes for Vec { /// (https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L222). #[derive(Debug)] pub struct CInet { - addr: SocketAddr + addr: SocketAddr, } impl FromCursor for CInet { @@ -384,9 +384,7 @@ impl FromCursor for CInet { let port = CInt::from_cursor(&mut cursor); let socket_addr = SocketAddr::new(ip, port as u16); - CInet { - addr: socket_addr - } + CInet { addr: socket_addr } } } @@ -493,7 +491,8 @@ mod tests { // CStringList #[test] fn test_cstringlist() { - let mut cursor: Cursor> = Cursor::new(vec![0, 2, 0, 3, 102, 111, 111, 0, 3, 102, 111, 111]); + let mut cursor: Cursor> = Cursor::new(vec![0, 2, 0, 3, 102, 111, 111, 0, 3, 102, + 111, 111]); let list = CStringList::from_cursor(&mut cursor); let plain = list.into_plain(); assert_eq!(plain.len(), 2); diff --git a/src/types/rows.rs b/src/types/rows.rs index e290e70..41322d5 100644 --- a/src/types/rows.rs +++ b/src/types/rows.rs @@ -13,16 +13,18 @@ use std::io; #[derive(Debug)] pub struct Row { metadata: RowsMetadata, - row_content: Vec + row_content: Vec, } impl Row { pub fn from_frame_body(body: BodyResResultRows) -> Vec { return body.rows_content .iter() - .map(|row| Row { - metadata: body.metadata.clone(), - row_content: row.clone() + .map(|row| { + Row { + metadata: body.metadata.clone(), + row_content: row.clone(), + } }) .collect(); } @@ -56,7 +58,7 @@ impl IntoRustByName> for Row { let bytes = cbytes.as_plain().clone(); let converted = match cassandra_type { &ColType::Blob => decode_blob(bytes), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -73,9 +75,10 @@ impl IntoRustByName for Row { &ColType::Ascii => decode_ascii(bytes), &ColType::Varchar => decode_varchar(bytes), // TODO: clarify when to use decode_text. - // it's not mentioned in https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L582 + // it's not mentioned in + // https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L582 // &ColType::XXX => decode_text(bytes).ok(), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); @@ -91,10 +94,11 @@ impl IntoRustByName for Row { let converted = match cassandra_type { &ColType::Boolean => decode_boolean(bytes), _ => { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of converter. {:?} got, but - (bool ) is only supported.", cassandra_type)); + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of converter. {:?} got, but + (bool ) is only supported.", + cassandra_type)); Err(io_err) } }; @@ -116,10 +120,11 @@ impl IntoRustByName for Row { &ColType::Varint => decode_varint(bytes), &ColType::Float => decode_varint(bytes), _ => { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of converter. {:?} got, but - (Int,Bigint,Timestamp,Time,Varint,Float ) is only supported.", cassandra_type)); + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of converter. {:?} got, but + (Int,Bigint,Timestamp,Time,Varint,Float ) is only supported.", + cassandra_type)); Err(io_err) } }; @@ -138,10 +143,11 @@ impl IntoRustByName for Row { &ColType::Int => decode_int(bytes), &ColType::Date => decode_date(bytes), _ => { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of converter. {:?} got, but - (Int,date ) is only supported.", cassandra_type)); + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of converter. {:?} got, but + (Int,date ) is only supported.", + cassandra_type)); Err(io_err) } }; @@ -159,10 +165,11 @@ impl IntoRustByName for Row { let converted = match cassandra_type { &ColType::Smallint => decode_smallint(bytes), _ => { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of converter. {:?} got, but - (Smallint) is only supported.", cassandra_type)); + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of converter. {:?} got, but + (Smallint) is only supported.", + cassandra_type)); Err(io_err) } }; @@ -179,10 +186,11 @@ impl IntoRustByName for Row { let converted = match cassandra_type { &ColType::Double => decode_double(bytes), _ => { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of converter. {:?} got, but - (Double) is only supported.", cassandra_type)); + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of converter. {:?} got, but + (Double) is only supported.", + cassandra_type)); Err(io_err) } }; @@ -201,10 +209,11 @@ impl IntoRustByName for Row { &ColType::Decimal => decode_decimal(bytes), &ColType::Float => decode_float(bytes), _ => { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of converter. {:?} got, but - (Float,Decimal) is only supported.", cassandra_type)); + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of converter. {:?} got, but + (Float,Decimal) is only supported.", + cassandra_type)); Err(io_err) } }; @@ -222,10 +231,11 @@ impl IntoRustByName for Row { let converted = match cassandra_type { &ColType::Inet => decode_inet(bytes), _ => { - let io_err = io::Error::new( - io::ErrorKind::NotFound, - format!("Unsupported type of converter. {:?} got, but - (Inet) is only supported.", cassandra_type)); + let io_err = + io::Error::new(io::ErrorKind::NotFound, + format!("Unsupported type of converter. {:?} got, but + (Inet) is only supported.", + cassandra_type)); Err(io_err) } }; @@ -243,7 +253,7 @@ impl IntoRustByName for Row { let converted = match cassandra_type { &ColType::Uuid => decode_timeuuid(bytes), &ColType::Timeuuid => decode_timeuuid(bytes), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); @@ -258,9 +268,13 @@ impl IntoRustByName for Row { return match cassandra_type.col_type.id { // in fact, both decode_list and decode_set return Ok - ColType::List => Ok(List::new(decode_list(bytes).unwrap(), cassandra_type.col_type.clone())), - ColType::Set => Ok(List::new(decode_set(bytes).unwrap(), cassandra_type.col_type.clone())), - _ => unreachable!() + ColType::List => { + Ok(List::new(decode_list(bytes).unwrap(), cassandra_type.col_type.clone())) + } + ColType::Set => { + Ok(List::new(decode_set(bytes).unwrap(), cassandra_type.col_type.clone())) + } + _ => unreachable!(), }; }); } @@ -273,9 +287,11 @@ impl IntoRustByName for Row { return match cassandra_type.col_type.id { // in fact, both decode_map and decode_set return Ok - ColType::Map => Ok(Map::new(decode_map(bytes).unwrap(), cassandra_type.col_type.clone())), - _ => unreachable!() - } + ColType::Map => { + Ok(Map::new(decode_map(bytes).unwrap(), cassandra_type.col_type.clone())) + } + _ => unreachable!(), + }; }); } } @@ -286,15 +302,15 @@ impl IntoRustByName for Row { let bytes = cbytes.as_plain().clone(); let cudt = match cassandra_type.col_type.value { Some(ColTypeOptionValue::UdtType(ref t)) => t.clone(), - _ => unreachable!() + _ => unreachable!(), }; return match cassandra_type.col_type.id { ColType::Map => Ok(UDT::new(decode_udt(bytes).unwrap(), cudt)), - _ => unreachable!() - } + _ => unreachable!(), + }; }); } } -//TODO: add uuid +// TODO: add uuid diff --git a/src/types/udt.rs b/src/types/udt.rs index 1c47a46..c4b4292 100644 --- a/src/types/udt.rs +++ b/src/types/udt.rs @@ -11,16 +11,16 @@ use error::Result; #[derive(Debug)] pub struct UDT { - data: HashMap + data: HashMap, } impl UDT { pub fn new(data: Vec, metadata: CUdt) -> UDT { let meta_iter = metadata.descriptions.iter(); - let acc: HashMap = HashMap::with_capacity(metadata.descriptions.len()); - let d = meta_iter - .zip(data.iter()) + let acc: HashMap = + HashMap::with_capacity(metadata.descriptions.len()); + let d = meta_iter.zip(data.iter()) .fold(acc, |mut a, v| { let (m, val_b) = v; let &(ref name_b, ref val_type) = m; @@ -29,9 +29,7 @@ impl UDT { return a; }); - return UDT { - data: d - }; + return UDT { data: d }; } } @@ -41,8 +39,8 @@ impl IntoRustByName> for UDT { let &(ref col_type, ref bytes) = v; return match col_type.id { ColType::Blob => decode_blob(bytes.as_plain()).map_err(|err| err.into()), - _ => unreachable!() - } + _ => unreachable!(), + }; }); } } @@ -55,7 +53,7 @@ impl IntoRustByName for UDT { ColType::Custom => decode_custom(bytes.as_plain()), ColType::Ascii => decode_ascii(bytes.as_plain()), ColType::Varchar => decode_varchar(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -68,7 +66,7 @@ impl IntoRustByName for UDT { let &(ref col_type, ref bytes) = v; let converted = match col_type.id { ColType::Boolean => decode_boolean(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -84,7 +82,7 @@ impl IntoRustByName for UDT { ColType::Timestamp => decode_timestamp(bytes.as_plain()), ColType::Time => decode_time(bytes.as_plain()), ColType::Varint => decode_varint(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -98,7 +96,7 @@ impl IntoRustByName for UDT { let converted = match col_type.id { ColType::Int => decode_int(bytes.as_plain()), ColType::Date => decode_date(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -111,7 +109,7 @@ impl IntoRustByName for UDT { let &(ref col_type, ref bytes) = v; let converted = match col_type.id { ColType::Smallint => decode_smallint(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -124,7 +122,7 @@ impl IntoRustByName for UDT { let &(ref col_type, ref bytes) = v; let converted = match col_type.id { ColType::Double => decode_double(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -138,7 +136,7 @@ impl IntoRustByName for UDT { let converted = match col_type.id { ColType::Decimal => decode_decimal(bytes.as_plain()), ColType::Float => decode_float(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -151,7 +149,7 @@ impl IntoRustByName for UDT { let &(ref col_type, ref bytes) = v; let converted = match col_type.id { ColType::Inet => decode_inet(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -165,7 +163,7 @@ impl IntoRustByName for UDT { let converted = match col_type.id { ColType::Uuid => decode_timeuuid(bytes.as_plain()), ColType::Timeuuid => decode_timeuuid(bytes.as_plain()), - _ => unreachable!() + _ => unreachable!(), }; return converted.map_err(|err| err.into()); }); @@ -180,13 +178,13 @@ impl IntoRustByName for UDT { ColType::List => { let list_bytes = decode_list(bytes.as_plain()).unwrap(); Ok(List::new(list_bytes, col_type.clone().clone())) - }, + } ColType::Set => { let list_bytes = decode_set(bytes.as_plain()).unwrap(); Ok(List::new(list_bytes, col_type.clone().clone())) - }, - _ => unreachable!() - } + } + _ => unreachable!(), + }; }); } } @@ -198,8 +196,8 @@ impl IntoRustByName for UDT { let list_bytes = decode_map(bytes.as_plain()).unwrap(); return match col_type.id { ColType::Map => Ok(Map::new(list_bytes, col_type.clone().clone())), - _ => unreachable!() - } + _ => unreachable!(), + }; }); } } @@ -216,13 +214,13 @@ impl IntoRustByName for UDT { let col_type_value = match col_type.value.as_ref() { Some(&ColTypeOptionValue::UdtType(ref ctv)) => ctv, - _ => unreachable!() + _ => unreachable!(), };; return match col_type.id { ColType::Udt => Ok(UDT::new(list_bytes, col_type_value.clone())), - _ => unreachable!() - } + _ => unreachable!(), + }; }); } } diff --git a/src/types/value.rs b/src/types/value.rs index 9437cbc..17dfdc6 100644 --- a/src/types/value.rs +++ b/src/types/value.rs @@ -6,7 +6,7 @@ use super::*; pub enum ValueType { Normal(i32), Null, - NotSet + NotSet, } impl IntoBytes for ValueType { @@ -14,7 +14,7 @@ impl IntoBytes for ValueType { return match *self { ValueType::Normal(n) => to_int(n as i64), ValueType::Null => i_to_n_bytes(-1, INT_LEN), - ValueType::NotSet => i_to_n_bytes(-2, INT_LEN) + ValueType::NotSet => i_to_n_bytes(-2, INT_LEN), }; } } @@ -23,7 +23,7 @@ impl IntoBytes for ValueType { #[derive(Debug, Clone)] pub struct Value { pub body: Vec, - pub value_type: ValueType + pub value_type: ValueType, } impl Value { @@ -32,7 +32,7 @@ impl Value { let l = body.len() as i32; return Value { body: body, - value_type: ValueType::Normal(l) + value_type: ValueType::Normal(l), }; } @@ -40,7 +40,7 @@ impl Value { pub fn new_null() -> Value { return Value { body: vec![], - value_type: ValueType::Null + value_type: ValueType::Null, }; } @@ -48,7 +48,7 @@ impl Value { pub fn new_not_set() -> Value { return Value { body: vec![], - value_type: ValueType::NotSet + value_type: ValueType::NotSet, }; } } @@ -89,7 +89,7 @@ mod tests { assert_eq!(normal_value.body, plain_value); match normal_value.value_type { ValueType::Normal(l) => assert_eq!(l, len), - _ => unreachable!() + _ => unreachable!(), } } @@ -99,7 +99,7 @@ mod tests { assert_eq!(null_value.body, vec![]); match null_value.value_type { ValueType::Null => assert!(true), - _ => unreachable!() + _ => unreachable!(), } } @@ -109,7 +109,7 @@ mod tests { assert_eq!(not_set_value.body, vec![]); match not_set_value.value_type { ValueType::NotSet => assert!(true), - _ => unreachable!() + _ => unreachable!(), } } From 3dcae3b3be0ece2193c01c84ae1e6533b4a06de6 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Mon, 6 Feb 2017 22:47:28 -0500 Subject: [PATCH 02/19] removed the fmt --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 1786558..dcd88c6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ before_script: (cargo install rustfmt || true) script: - | export PATH=$PATH:~/.cargo/bin && - cargo fmt -- --write-mode=diff && + cargo build && cargo test From 6673be6d0efaec77a36e2546a211c46c6bd5c9e9 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 00:14:34 -0500 Subject: [PATCH 03/19] Added fmt as part of travis --- .travis.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 35e8ffd..332baf9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,7 @@ matrix: allow_failures: - rust: nightly + before_install: - sudo update-java-alternatives -s java-8-oracle - export JAVA_HOME=/usr/lib/jvm/java-8-oracle @@ -16,10 +17,13 @@ before_install: - sudo sh ./apache-cassandra-3.9/bin/cassandra -R - sleep 20 - -#services: - #- cassandra - +cache: cargo +before_script: (cargo install rustfmt || true) +script: +- | + cargo fmt -- --write-mode=diff && + cargo build && + cargo test addons: apt: From 1531ba2fb90a9ee6ff614e1bd134936c3bd84f9f Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 00:21:04 -0500 Subject: [PATCH 04/19] update the path to travis --- .travis.yml | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 332baf9..6c26664 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,5 @@ language: rust +cache: cargo rust: - stable - beta @@ -17,13 +18,15 @@ before_install: - sudo sh ./apache-cassandra-3.9/bin/cassandra -R - sleep 20 -cache: cargo -before_script: (cargo install rustfmt || true) + +install: + - (cargo install rustfmt || true) + - PATH=$PATH:/home/travis/.cargo/bin + script: -- | - cargo fmt -- --write-mode=diff && - cargo build && - cargo test + - cargo fmt -- --write-mode=diff + - cargo build --verbose + - cargo test --verbose addons: apt: From 9d672fdff26dfede8234e51ebc2d788803ea8503 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 01:10:25 -0500 Subject: [PATCH 05/19] cargo fmt added --- examples/batch_queries.rs | 1 - examples/create_table.rs | 2 +- examples/prepare_execute.rs | 1 - examples/read_table_into_struct.rs | 1 - examples/server_events.rs | 10 ++-------- examples/simple_with_auth.rs | 18 +++++++++--------- src/connection_manager.rs | 16 +++++++++------- src/types/data_serialization_types.rs | 4 +--- src/types/map.rs | 2 +- src/types/udt.rs | 2 +- tests/create_ks_and_table.rs | 13 +++++++------ 11 files changed, 31 insertions(+), 39 deletions(-) diff --git a/examples/batch_queries.rs b/examples/batch_queries.rs index 4768c99..a11fe36 100644 --- a/examples/batch_queries.rs +++ b/examples/batch_queries.rs @@ -44,4 +44,3 @@ fn main() { println!("batch result {:?}", batched.get_body()); } - diff --git a/examples/create_table.rs b/examples/create_table.rs index d47a6ee..25e0e50 100644 --- a/examples/create_table.rs +++ b/examples/create_table.rs @@ -36,6 +36,6 @@ fn main() { match session.query(create_table_query, with_tracing, with_warnings) { Ok(ref res) => println!("table created: {:?}", res.get_body()), - Err(ref err) => println!("Error occured: {:?}", err) + Err(ref err) => println!("Error occured: {:?}", err), } } diff --git a/examples/prepare_execute.rs b/examples/prepare_execute.rs index a1d36a7..b37bf70 100644 --- a/examples/prepare_execute.rs +++ b/examples/prepare_execute.rs @@ -42,4 +42,3 @@ fn main() { println!("executed:\n{:?}", executed); } - diff --git a/examples/read_table_into_struct.rs b/examples/read_table_into_struct.rs index 49b02c6..8d8e61a 100644 --- a/examples/read_table_into_struct.rs +++ b/examples/read_table_into_struct.rs @@ -97,4 +97,3 @@ fn main() { } } - diff --git a/examples/server_events.rs b/examples/server_events.rs index 4435f0e..65634a1 100644 --- a/examples/server_events.rs +++ b/examples/server_events.rs @@ -7,11 +7,7 @@ use std::thread; use cdrs::client::CDRS; use cdrs::authenticators::PasswordAuthenticator; use cdrs::compression::Compression; -use cdrs::frame::events::{ - SimpleServerEvent, - ServerEvent, - TopologyChangeType -}; +use cdrs::frame::events::{SimpleServerEvent, ServerEvent, TopologyChangeType}; use cdrs::transport::TransportPlain; // default credentials @@ -27,9 +23,7 @@ fn main() { let (mut listener, stream) = session.listen_for(vec![SimpleServerEvent::SchemaChange]).unwrap(); - thread::spawn(move|| { - listener.start(&Compression::None).unwrap() - }); + thread::spawn(move || listener.start(&Compression::None).unwrap()); let topology_changes = stream // inspects all events in a stream diff --git a/examples/simple_with_auth.rs b/examples/simple_with_auth.rs index d118717..37d2fb5 100644 --- a/examples/simple_with_auth.rs +++ b/examples/simple_with_auth.rs @@ -23,15 +23,15 @@ fn main() { let with_warnings = false; let query_op = session.query(select_query, with_tracing, with_warnings); - match query_op { - - Ok(res) => { - println!("Result frame: {:?},\nparsed body: {:?}", - res, - res.get_body()) - } - Err(err) => println!("{:?}", err), - } + match query_op { + + Ok(res) => { + println!("Result frame: {:?},\nparsed body: {:?}", + res, + res.get_body()) + } + Err(err) => println!("{:?}", err), + } } Err(err) => println!("{:?}", err), diff --git a/src/connection_manager.rs b/src/connection_manager.rs index ac9d4a8..21aaf5e 100644 --- a/src/connection_manager.rs +++ b/src/connection_manager.rs @@ -16,16 +16,18 @@ pub struct ConnectionManager { compression: Compression, } -impl -ConnectionManager { -/// Creates a new instance of `ConnectionManager`. -/// It requires transport, authenticator and compression as inputs. - pub fn new(transport: X, authenticator: T, compression: Compression) - -> ConnectionManager { +impl + ConnectionManager { + /// Creates a new instance of `ConnectionManager`. + /// It requires transport, authenticator and compression as inputs. + pub fn new(transport: X, + authenticator: T, + compression: Compression) + -> ConnectionManager { ConnectionManager { transport: transport, authenticator: authenticator, - compression: compression + compression: compression, } } } diff --git a/src/types/data_serialization_types.rs b/src/types/data_serialization_types.rs index 5d22fd5..edb3127 100644 --- a/src/types/data_serialization_types.rs +++ b/src/types/data_serialization_types.rs @@ -136,9 +136,7 @@ pub fn decode_map(bytes: Vec) -> Result, io::Error> { let mut cursor: io::Cursor> = io::Cursor::new(bytes); let l = CInt::from_cursor(&mut cursor); let list = (0..l) - .map(|_| { - return (CBytes::from_cursor(&mut cursor), CBytes::from_cursor(&mut cursor)); - }) + .map(|_| { return (CBytes::from_cursor(&mut cursor), CBytes::from_cursor(&mut cursor)); }) .collect(); Ok(list) } diff --git a/src/types/map.rs b/src/types/map.rs index 19206a7..51de83a 100644 --- a/src/types/map.rs +++ b/src/types/map.rs @@ -29,7 +29,7 @@ impl Map { // check that key could be converted into String let serializer = if let ColTypeOptionValue::CMap((key_type, _)) = - map_option_type.unwrap() { + map_option_type.unwrap() { match key_type.id { ColType::Custom => decode_custom, ColType::Ascii => decode_ascii, diff --git a/src/types/udt.rs b/src/types/udt.rs index c4b4292..29bdd4e 100644 --- a/src/types/udt.rs +++ b/src/types/udt.rs @@ -215,7 +215,7 @@ impl IntoRustByName for UDT { let col_type_value = match col_type.value.as_ref() { Some(&ColTypeOptionValue::UdtType(ref ctv)) => ctv, _ => unreachable!(), - };; + }; return match col_type.id { ColType::Udt => Ok(UDT::new(list_bytes, col_type_value.clone())), diff --git a/tests/create_ks_and_table.rs b/tests/create_ks_and_table.rs index 0f06ed2..773888c 100644 --- a/tests/create_ks_and_table.rs +++ b/tests/create_ks_and_table.rs @@ -21,7 +21,8 @@ fn it_works() { let client = CDRS::new(tcp_transport.unwrap(), authenticator); let mut session = client.start(Compression::None).unwrap(); let drop_ks = "DROP KEYSPACE my_ks;"; - let create_ks_cql = "CREATE KEYSPACE my_ks WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 } ;"; + let create_ks_cql = "CREATE KEYSPACE my_ks WITH REPLICATION = { 'class' : 'SimpleStrategy', \ + 'replication_factor' : 1 } ;"; let create_table_cql = "CREATE TABLE my_ks.users ( user_name varchar PRIMARY KEY, password varchar, @@ -41,14 +42,14 @@ fn it_works() { .consistency(Consistency::One) .finalize(); - let create_ks_query_result = session.query(create_ks_query, with_tracing, with_warnings); + let create_ks_query_result = session.query(create_ks_query, with_tracing, with_warnings); assert_eq!(create_ks_query_result.is_ok(), true); match create_ks_query_result { Ok(ref res) => println!("keyspace created: {:?}", res.get_body()), - Err(ref err) => println!("Error occured: {:?}", err) + Err(ref err) => println!("Error occured: {:?}", err), } @@ -57,19 +58,19 @@ fn it_works() { .finalize(); match session.query(create_table_query, with_tracing, with_warnings) { Ok(ref res) => println!("table created: {:?}", res.get_body()), - Err(ref err) => println!("Error occured: {:?}", err) + Err(ref err) => println!("Error occured: {:?}", err), } let drop_ks_query = QueryBuilder::new(drop_ks) .consistency(Consistency::One) .finalize(); - let drop_ks_query_result = session.query(drop_ks_query, with_tracing, with_warnings) ; + let drop_ks_query_result = session.query(drop_ks_query, with_tracing, with_warnings); assert_eq!(drop_ks_query_result.is_ok(), true); match drop_ks_query_result { Ok(ref res) => println!("keyspace dropped: {:?}", res.get_body()), - Err(ref err) => println!("Error occured: {:?}", err) + Err(ref err) => println!("Error occured: {:?}", err), } } From 06adbb41609efb7b82c97a5dbfa2bae0e800707f Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 01:25:01 -0500 Subject: [PATCH 06/19] no clue --- src/transport.rs | 2 +- tests/create_ks_and_table.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/transport.rs b/src/transport.rs index ea3f9ab..daf6c16 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -51,7 +51,7 @@ impl CDRSTransport for TransportPlain { /// of a peer from `Transport` and creates a new encrypted /// transport with new TCP stream under hood. fn try_clone(&self) -> io::Result { - let addr = try!( self.tcp.peer_addr()); + let addr = try!(self.tcp.peer_addr()); TcpStream::connect(addr).map(|socket| TransportPlain { tcp: socket }) } diff --git a/tests/create_ks_and_table.rs b/tests/create_ks_and_table.rs index 773888c..6737c3f 100644 --- a/tests/create_ks_and_table.rs +++ b/tests/create_ks_and_table.rs @@ -12,7 +12,7 @@ const _ADDR: &'static str = "127.0.0.1:9042"; #[test] -fn it_works() { +fn create_keyspace_and_table() { const _ADDR: &'static str = "127.0.0.1:9042"; let authenticator = NoneAuthenticator; let tcp_transport = TransportPlain::new(_ADDR); From 871316d24f9548bf227705e78c4dd02a269dd0ec Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 09:11:47 -0500 Subject: [PATCH 07/19] ovewrite --- src/frame/frame_result.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/frame/frame_result.rs b/src/frame/frame_result.rs index 8e8595f..e47a9fb 100644 --- a/src/frame/frame_result.rs +++ b/src/frame/frame_result.rs @@ -87,7 +87,6 @@ impl ResResultBody { ResResultBody::SchemaChange(SchemaChange::from_cursor(&mut cursor)) } - } } From c1198140dc0568f413e587eeefb8483d33f842a8 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 09:57:15 -0500 Subject: [PATCH 08/19] Added new test case --- src/frame/frame_auth_response.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/frame/frame_auth_response.rs b/src/frame/frame_auth_response.rs index d1def92..a9d9112 100644 --- a/src/frame/frame_auth_response.rs +++ b/src/frame/frame_auth_response.rs @@ -43,3 +43,31 @@ impl Frame { } } } + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn body_req_auth_response() { + let few_bytes: Vec = vec![0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + let data = CBytes::new(few_bytes); + let body = BodyReqAuthResponse::new(data); + assert_eq!(body.data.into_plain(), vec![0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + } + + #[test] + fn body_req_auth_frame() { + let few_bytes: Vec = vec![0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + let frame = Frame::new_req_auth_response(few_bytes); + assert_eq!(frame.version,Version::Request); + assert_eq!(frame.flags,vec![Flag::Ignore]); + assert_eq!(frame.stream,0); + assert_eq!(frame.opcode,Opcode::AuthResponse); + assert_eq!(frame.tracing_id,None); + //assert_eq!(frame.warnings,vec![]); + assert_eq!(frame.body,vec![0, 0, 0, 14,0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + } +} + From 07bf6b868e65e44af0b92870f58b6a134271efed Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 10:02:13 -0500 Subject: [PATCH 09/19] formated with rustfmt --- src/frame/frame_auth_response.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/frame/frame_auth_response.rs b/src/frame/frame_auth_response.rs index a9d9112..c859d54 100644 --- a/src/frame/frame_auth_response.rs +++ b/src/frame/frame_auth_response.rs @@ -52,22 +52,23 @@ mod tests { #[test] fn body_req_auth_response() { let few_bytes: Vec = vec![0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let data = CBytes::new(few_bytes); + let data = CBytes::new(few_bytes); let body = BodyReqAuthResponse::new(data); - assert_eq!(body.data.into_plain(), vec![0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + assert_eq!(body.data.into_plain(), + vec![0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); } #[test] fn body_req_auth_frame() { let few_bytes: Vec = vec![0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let frame = Frame::new_req_auth_response(few_bytes); - assert_eq!(frame.version,Version::Request); - assert_eq!(frame.flags,vec![Flag::Ignore]); - assert_eq!(frame.stream,0); - assert_eq!(frame.opcode,Opcode::AuthResponse); - assert_eq!(frame.tracing_id,None); + assert_eq!(frame.version, Version::Request); + assert_eq!(frame.flags, vec![Flag::Ignore]); + assert_eq!(frame.stream, 0); + assert_eq!(frame.opcode, Opcode::AuthResponse); + assert_eq!(frame.tracing_id, None); //assert_eq!(frame.warnings,vec![]); - assert_eq!(frame.body,vec![0, 0, 0, 14,0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + assert_eq!(frame.body, + vec![0, 0, 0, 14, 0, 0, 0, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); } } - From 3dfe0dafc41a50a25c8852c5d55de3151e304ed0 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 10:04:08 -0500 Subject: [PATCH 10/19] edited readme --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 254e8ea..8f764cd 100644 --- a/README.md +++ b/README.md @@ -420,8 +420,9 @@ Please refer to each project's style guidelines and guidelines for submitting pa 1. **Fork** the repo on GitHub 2. **Clone** the project to your own machine 3. **Commit** changes to your own branch - 4. **Push** your work back up to your fork - 5. Submit a **Pull request** so that we can review your changes + 4. ** run ```cargo test --all-features && cargo fmt -- --write-mode=diff``` + 5. **Push** your work back up to your fork + 6. Submit a **Pull request** so that we can review your changes NOTE: Be sure to merge the latest from "upstream" before making a pull request! while running the tests you might need a local cassandra server working. From 6cc52e2a05586ac1f7f72bd18e239cbd76c66fa3 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 10:22:22 -0500 Subject: [PATCH 11/19] updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f764cd..96346ca 100644 --- a/README.md +++ b/README.md @@ -420,7 +420,7 @@ Please refer to each project's style guidelines and guidelines for submitting pa 1. **Fork** the repo on GitHub 2. **Clone** the project to your own machine 3. **Commit** changes to your own branch - 4. ** run ```cargo test --all-features && cargo fmt -- --write-mode=diff``` + 4. **Run ```cargo test --all-features && cargo fmt -- --write-mode=diff``` 5. **Push** your work back up to your fork 6. Submit a **Pull request** so that we can review your changes From 94374a1527f28ff4f1fb14e8139af260bbf3cec4 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 11:36:31 -0500 Subject: [PATCH 12/19] added more test --- src/compression.rs | 50 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/src/compression.rs b/src/compression.rs index 92deb4c..aeb7532 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -69,7 +69,20 @@ pub enum Compression { } impl Compression { - /// It encodes `bytes` basing on type of compression. + + /// It encodes `bytes` basing on type of `Compression`.. + /// + /// # Examples + /// + /// ``` + /// use cdrs::compression::Compression; + /// + /// let snappy_compression = Compression::Snappy; + /// let bytes = String::from("Hello World").into_bytes().to_vec(); + /// let encoded = snappy_compression.encode(bytes.clone()).unwrap(); + /// assert_eq!(snappy_compression.decode(encoded).unwrap(), bytes); + /// + /// ``` pub fn encode(&self, bytes: Vec) -> Result> { return match self { &Compression::Lz4 => Compression::encode_lz4(bytes), @@ -79,6 +92,19 @@ impl Compression { } /// It decodes `bytes` basing on type of compression. + /// + /// # Examples + /// + /// ``` + /// use cdrs::compression::Compression; + /// let lz4_compression = Compression::Lz4; + /// let bytes = String::from("Hello World").into_bytes().to_vec(); + /// let encoded = lz4_compression.encode(bytes.clone()).unwrap(); + /// let len = encoded.len() as u8; + /// let mut input = vec![0, 0, 0, len]; + /// input.extend_from_slice(encoded.as_slice()); + /// assert_eq!(lz4_compression.decode(input).unwrap(), bytes); + /// ``` pub fn decode(&self, bytes: Vec) -> Result> { return match self { &Compression::Lz4 => Compression::decode_lz4(bytes), @@ -189,13 +215,29 @@ mod tests { #[test] fn test_compression_decode_lz4() { - let snappy_compression = Compression::Lz4; + let lz4_compression = Compression::Lz4; let bytes = String::from("Hello World").into_bytes().to_vec(); - let encoded = snappy_compression.encode(bytes.clone()).unwrap(); + let encoded = lz4_compression.encode(bytes.clone()).unwrap(); let len = encoded.len() as u8; let mut input = vec![0, 0, 0, len]; input.extend_from_slice(encoded.as_slice()); - assert_eq!(snappy_compression.decode(input).unwrap(), bytes); + assert_eq!(lz4_compression.decode(input).unwrap(), bytes); + } + + #[test] + fn test_compression_encode_none() { + let none_compression = Compression::None; + let bytes = String::from("Hello World").into_bytes().to_vec(); + none_compression.encode(bytes.clone()).expect("Should work without exceptions"); + } + + + #[test] + fn test_compression_decode_none() { + let none_compression = Compression::None; + let bytes = String::from("Hello World").into_bytes().to_vec(); + let encoded = none_compression.encode(bytes.clone()).unwrap(); + assert_eq!(none_compression.decode(encoded).unwrap(), bytes); } } From cfe5afa008b51f632f8a7c667f75cd4d89c30b33 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 11:43:47 -0500 Subject: [PATCH 13/19] ran fmt --- src/compression.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/compression.rs b/src/compression.rs index aeb7532..466f88a 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -69,7 +69,6 @@ pub enum Compression { } impl Compression { - /// It encodes `bytes` basing on type of `Compression`.. /// /// # Examples From 4ee4cb3b54ec2939f16495ab8a35d7c20624c240 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 12:10:04 -0500 Subject: [PATCH 14/19] added docs --- src/consistency.rs | 66 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 53 insertions(+), 13 deletions(-) diff --git a/src/consistency.rs b/src/consistency.rs index cab52ca..86cd656 100644 --- a/src/consistency.rs +++ b/src/consistency.rs @@ -11,28 +11,64 @@ use super::FromBytes; /// To find more details about each consistency level please refer to Cassandra official docs. #[derive(Debug, PartialEq, Clone)] pub enum Consistency { - #[allow(missing_docs)] + /// A write must be written to the commit log and memtable on all replica nodes in the cluster + /// for that partition key. Provides the highest consistency + /// and the lowest availability of any other level. Any, - #[allow(missing_docs)] + /// + /// A write must be written to the commit log and memtable of at least one replica node. + /// Satisfies the needs of most users because consistency requirements are not stringent. One, - #[allow(missing_docs)] + /// A write must be written to the commit log and memtable of at least two replica nodes. + /// Similar to ONE. Two, - #[allow(missing_docs)] + + /// A write must be written to the commit log and memtable of at least three replica nodes. + /// Similar to TWO. Three, - #[allow(missing_docs)] + /// A write must be written to the commit log and memtable on a quorum of replica nodes. + /// Provides strong consistency if you can tolerate some level of failure. Quorum, - #[allow(missing_docs)] + /// A write must be written to the commit log and memtable on all replica nodes in the cluster + /// for that partition key. + /// Provides the highest consistency and the lowest availability of any other level. All, - #[allow(missing_docs)] + /// Strong consistency. A write must be written to the commit log and memtable on a quorum + /// of replica nodes in the same data center as thecoordinator node. + /// Avoids latency of inter-data center communication. + /// Used in multiple data center clusters with a rack-aware replica placement strategy, + /// such as NetworkTopologyStrategy, and a properly configured snitch. + /// Use to maintain consistency locally (within the single data center). + /// Can be used with SimpleStrategy. LocalQuorum, - #[allow(missing_docs)] + /// Strong consistency. A write must be written to the commit log and memtable on a quorum of + /// replica nodes in all data center. + /// Used in multiple data center clusters to strictly maintain consistency at the same level + /// in each data center. For example, choose this level + /// if you want a read to fail when a data center is down and the QUORUM + /// cannot be reached on that data center. EachQuorum, - #[allow(missing_docs)] + /// Achieves linearizable consistency for lightweight transactions by preventing unconditional + /// updates. You cannot configure this level as a normal consistency level, + /// configured at the driver level using the consistency level field. + /// You configure this level using the serial consistency field + /// as part of the native protocol operation. See failure scenarios. Serial, - #[allow(missing_docs)] + /// Same as SERIAL but confined to the data center. A write must be written conditionally + /// to the commit log and memtable on a quorum of replica nodes in the same data center. + /// Same as SERIAL. Used for disaster recovery. See failure scenarios. LocalSerial, - #[allow(missing_docs)] + /// A write must be sent to, and successfully acknowledged by, + /// at least one replica node in the local data center. + /// In a multiple data center clusters, a consistency level of ONE is often desirable, + /// but cross-DC traffic is not. LOCAL_ONE accomplishes this. + /// For security and quality reasons, you can use this consistency level + /// in an offline datacenter to prevent automatic connection + /// to online nodes in other data centers if an offline node goes down. LocalOne, + /// This is an error scenario either the client code doesn't support it or server is sending + /// bad headers + Unknown, } impl Default for Consistency { @@ -55,6 +91,8 @@ impl IntoBytes for Consistency { &Consistency::Serial => to_short(0x0008), &Consistency::LocalSerial => to_short(0x0009), &Consistency::LocalOne => to_short(0x000A), + &Consistency::Unknown => to_short(0x0063), + //giving Unknown a value of 99 }; } } @@ -73,7 +111,7 @@ impl From for Consistency { 0x0008 => Consistency::Serial, 0x0009 => Consistency::LocalSerial, 0x000A => Consistency::LocalOne, - _ => unreachable!(), + _ => Consistency::Unknown, }; } } @@ -92,7 +130,7 @@ impl FromBytes for Consistency { 0x0008 => Consistency::Serial, 0x0009 => Consistency::LocalSerial, 0x000A => Consistency::LocalOne, - _ => unreachable!(), + _ => Consistency::Unknown, }; } } @@ -140,6 +178,7 @@ mod tests { assert_eq!(Consistency::from(8), Consistency::Serial); assert_eq!(Consistency::from(9), Consistency::LocalSerial); assert_eq!(Consistency::from(10), Consistency::LocalOne); + assert_eq!(Consistency::from(11), Consistency::Unknown); } #[test] @@ -157,6 +196,7 @@ mod tests { assert_eq!(Consistency::from_bytes(vec![0, 9]), Consistency::LocalSerial); assert_eq!(Consistency::from_bytes(vec![0, 10]), Consistency::LocalOne); + assert_eq!(Consistency::from_bytes(vec![0, 11]), Consistency::Unknown); } #[test] From b5192735a02f8726f9c2138ff65459cd03aad77b Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 12:20:04 -0500 Subject: [PATCH 15/19] added test case for unknown consistency --- src/consistency.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/consistency.rs b/src/consistency.rs index 86cd656..e205aae 100644 --- a/src/consistency.rs +++ b/src/consistency.rs @@ -163,6 +163,7 @@ mod tests { assert_eq!(Consistency::Serial.into_cbytes(), vec![0, 8]); assert_eq!(Consistency::LocalSerial.into_cbytes(), vec![0, 9]); assert_eq!(Consistency::LocalOne.into_cbytes(), vec![0, 10]); + assert_eq!(Consistency::Unknown.into_cbytes(), vec![0, 99]); } #[test] From 9f4bc52f1327a80394e78949bff73fed768515ce Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 12:41:34 -0500 Subject: [PATCH 16/19] added test case for error --- src/compression.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/compression.rs b/src/compression.rs index 466f88a..068fd54 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -239,4 +239,15 @@ mod tests { assert_eq!(none_compression.decode(encoded).unwrap(), bytes); } + + #[test] + fn test_compression_encode_snappy_with_non_utf8() { + let lz4_compression = Compression::Lz4; + let bytes: Vec = vec![0x7f,0x7f,0x7f,0x7f,0x7f]; + let encoded = lz4_compression.encode(bytes.clone()).unwrap(); + let decode = lz4_compression.decode(encoded); + assert_eq!(decode.is_err(),true); + } + + } From 4a18bd78da623535a1a12b123d5085846620a920 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 12:42:01 -0500 Subject: [PATCH 17/19] added test case for error --- src/compression.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compression.rs b/src/compression.rs index 068fd54..931cb23 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -243,10 +243,10 @@ mod tests { #[test] fn test_compression_encode_snappy_with_non_utf8() { let lz4_compression = Compression::Lz4; - let bytes: Vec = vec![0x7f,0x7f,0x7f,0x7f,0x7f]; + let bytes: Vec = vec![0x7f, 0x7f, 0x7f, 0x7f, 0x7f]; let encoded = lz4_compression.encode(bytes.clone()).unwrap(); let decode = lz4_compression.decode(encoded); - assert_eq!(decode.is_err(),true); + assert_eq!(decode.is_err(), true); } From 755647531d2225c9dad62c729e18465433815c36 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 13:00:00 -0500 Subject: [PATCH 18/19] Added one more test case --- src/compression.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/compression.rs b/src/compression.rs index 931cb23..a25fd3d 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -241,7 +241,7 @@ mod tests { #[test] - fn test_compression_encode_snappy_with_non_utf8() { + fn test_compression_encode_lz4_with_invalid_input() { let lz4_compression = Compression::Lz4; let bytes: Vec = vec![0x7f, 0x7f, 0x7f, 0x7f, 0x7f]; let encoded = lz4_compression.encode(bytes.clone()).unwrap(); @@ -250,4 +250,12 @@ mod tests { } + #[test] + fn test_compression_encode_snappy_with_non_utf8() { + let snappy_compression = Compression::Snappy; + let v = vec![0xff, 0xff]; + let encoded = snappy_compression.encode(v.clone()).expect("Should work without exceptions"); + assert_eq!(snappy_compression.decode(encoded).unwrap(), v); + } + } From 1f1ba8d51a42f293e4db19db285de04b8be80136 Mon Sep 17 00:00:00 2001 From: harrydevnull Date: Wed, 8 Feb 2017 13:42:18 -0500 Subject: [PATCH 19/19] clippy warning --- README.md | 2 ++ src/compression.rs | 34 ++++++++++++++++------------------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 96346ca..5d6979b 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ [![crates.io version](https://img.shields.io/crates/v/cdrs.svg)](https://crates.io/crates/cdrs) [![Coverage Status](https://coveralls.io/repos/github/harrydevnull/cdrs/badge.svg?branch=master)](https://coveralls.io/github/harrydevnull/cdrs?branch=master) +[![codecov](https://codecov.io/gh/harrydevnull/cdrs/branch/master/graph/badge.svg)](https://codecov.io/gh/harrydevnull/cdrs) + **CDRS** is a native Cassandra driver written in [Rust](https://www.rust-lang.org). The motivation to write it in Rust is a lack of native one. diff --git a/src/compression.rs b/src/compression.rs index a25fd3d..52fb27d 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -33,12 +33,10 @@ impl fmt::Display for CompressionError { impl Error for CompressionError { fn description(&self) -> &str { - let desc = match self { + match self { &CompressionError::Snappy(ref err) => err.description(), &CompressionError::Lz4(ref s) => s.as_str(), - }; - - return desc; + } } } @@ -83,11 +81,11 @@ impl Compression { /// /// ``` pub fn encode(&self, bytes: Vec) -> Result> { - return match self { + match self { &Compression::Lz4 => Compression::encode_lz4(bytes), &Compression::Snappy => Compression::encode_snappy(bytes), &Compression::None => Ok(bytes), - }; + } } /// It decodes `bytes` basing on type of compression. @@ -105,32 +103,32 @@ impl Compression { /// assert_eq!(lz4_compression.decode(input).unwrap(), bytes); /// ``` pub fn decode(&self, bytes: Vec) -> Result> { - return match self { + match self { &Compression::Lz4 => Compression::decode_lz4(bytes), &Compression::Snappy => Compression::decode_snappy(bytes), &Compression::None => Ok(bytes), - }; + } } /// It transforms compression method into a `&str`. pub fn as_str(&self) -> Option<&'static str> { - return match self { + match self { &Compression::Lz4 => Some(LZ4), &Compression::Snappy => Some(SNAPPY), &Compression::None => None, - }; + } } fn encode_snappy(bytes: Vec) -> Result> { let mut encoder = snap::Encoder::new(); - return encoder.compress_vec(bytes.as_slice()) - .map_err(|err| CompressionError::Snappy(Box::new(err))); + encoder.compress_vec(bytes.as_slice()) + .map_err(|err| CompressionError::Snappy(Box::new(err))) } fn decode_snappy(bytes: Vec) -> Result> { let mut decoder = snap::Decoder::new(); - return decoder.decompress_vec(bytes.as_slice()) - .map_err(|err| CompressionError::Snappy(Box::new(err))); + decoder.decompress_vec(bytes.as_slice()) + .map_err(|err| CompressionError::Snappy(Box::new(err))) } fn encode_lz4(bytes: Vec) -> Result> { @@ -140,8 +138,8 @@ impl Compression { fn decode_lz4(bytes: Vec) -> Result> { // skip first 4 bytes in accordance to // https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L805 - return lz4::decompress(&bytes[4..]) - .map_err(|err| CompressionError::Lz4(err.description().to_string())); + lz4::decompress(&bytes[4..]) + .map_err(|err| CompressionError::Lz4(err.description().to_string())) } } @@ -157,11 +155,11 @@ impl<'a> From<&'a str> for Compression { /// It converts `str` into `Compression`. If string is neither `lz4` nor `snappy` then /// `Compression::None` will be returned fn from(compression_str: &'a str) -> Compression { - return match compression_str { + match compression_str { LZ4 => Compression::Lz4, SNAPPY => Compression::Snappy, _ => Compression::None, - }; + } } }