diff --git a/scylla-cql/src/deserialize/mod.rs b/scylla-cql/src/deserialize/mod.rs index ea92ec233b..b789ead165 100644 --- a/scylla-cql/src/deserialize/mod.rs +++ b/scylla-cql/src/deserialize/mod.rs @@ -252,6 +252,7 @@ impl TypeCheckError { } /// Retrieve an error reason by downcasting to specific type. + #[inline] pub fn downcast_ref(&self) -> Option<&T> { self.0.downcast_ref() } @@ -284,6 +285,7 @@ impl DeserializationError { } /// Retrieve an error reason by downcasting to specific type. + #[inline] pub fn downcast_ref(&self) -> Option<&T> { self.0.downcast_ref() } diff --git a/scylla-cql/src/deserialize/row.rs b/scylla-cql/src/deserialize/row.rs index cdc4a9db3b..a2abc64f97 100644 --- a/scylla-cql/src/deserialize/row.rs +++ b/scylla-cql/src/deserialize/row.rs @@ -269,6 +269,7 @@ pub struct BuiltinTypeCheckError { // Not part of the public API; used in derive macros. #[doc(hidden)] +#[inline] pub fn mk_typck_err( cql_types: impl IntoIterator>, kind: impl Into, @@ -423,6 +424,7 @@ pub struct BuiltinDeserializationError { // Not part of the public API; used in derive macros. #[doc(hidden)] +#[inline] pub fn mk_deser_err(kind: impl Into) -> DeserializationError { mk_deser_err_named(std::any::type_name::(), kind) } diff --git a/scylla-cql/src/deserialize/value.rs b/scylla-cql/src/deserialize/value.rs index b636b46132..d55e0ad2b2 100644 --- a/scylla-cql/src/deserialize/value.rs +++ b/scylla-cql/src/deserialize/value.rs @@ -1050,6 +1050,7 @@ where Some(do_next()) } + #[inline] fn size_hint(&self) -> (usize, Option) { self.raw_iter.size_hint() } @@ -1310,6 +1311,7 @@ impl<'frame, 'metadata> Iterator for UdtIterator<'frame, 'metadata> { Some((head, raw_res)) } + #[inline] fn size_hint(&self) -> (usize, Option) { self.raw_iter.size_hint() } @@ -1403,6 +1405,7 @@ impl<'frame> FixedLengthBytesSequenceIterator<'frame> { impl<'frame> Iterator for FixedLengthBytesSequenceIterator<'frame> { type Item = Result>, LowLevelDeserializationError>; + #[inline] fn next(&mut self) -> Option { self.remaining = self.remaining.checked_sub(1)?; Some(self.slice.read_cql_bytes()) @@ -1433,6 +1436,7 @@ impl<'frame> From> for BytesSequenceIterator<'frame> { impl<'frame> Iterator for BytesSequenceIterator<'frame> { type Item = Result>, LowLevelDeserializationError>; + #[inline] fn next(&mut self) -> Option { if self.slice.as_slice().is_empty() { None @@ -1946,6 +1950,7 @@ impl Display for MapDeserializationErrorKind { } impl From for BuiltinDeserializationErrorKind { + #[inline] fn from(err: MapDeserializationErrorKind) -> Self { Self::MapError(err) } @@ -1979,6 +1984,7 @@ impl Display for TupleDeserializationErrorKind { } impl From for BuiltinDeserializationErrorKind { + #[inline] fn from(err: TupleDeserializationErrorKind) -> Self { Self::TupleError(err) } @@ -2009,6 +2015,7 @@ impl Display for UdtDeserializationErrorKind { } impl From for BuiltinDeserializationErrorKind { + #[inline] fn from(err: UdtDeserializationErrorKind) -> Self { Self::UdtError(err) } diff --git a/scylla-cql/src/frame/frame_errors.rs b/scylla-cql/src/frame/frame_errors.rs index 570b9a9de5..16ee42a20b 100644 --- a/scylla-cql/src/frame/frame_errors.rs +++ b/scylla-cql/src/frame/frame_errors.rs @@ -147,6 +147,7 @@ pub enum CqlResponseParseError { } impl CqlResponseParseError { + #[inline] pub fn to_response_kind(&self) -> CqlResponseKind { match self { CqlResponseParseError::CqlErrorParseError(_) => CqlResponseKind::Error, @@ -486,6 +487,7 @@ pub enum LowLevelDeserializationError { } impl From for LowLevelDeserializationError { + #[inline] fn from(value: std::io::Error) -> Self { Self::IoError(Arc::new(value)) } diff --git a/scylla-cql/src/frame/mod.rs b/scylla-cql/src/frame/mod.rs index 43a15b859f..3721cc3690 100644 --- a/scylla-cql/src/frame/mod.rs +++ b/scylla-cql/src/frame/mod.rs @@ -48,6 +48,7 @@ pub enum Compression { } impl Compression { + #[inline] pub fn as_str(&self) -> &'static str { match self { Compression::Lz4 => "lz4", @@ -57,6 +58,7 @@ impl Compression { } impl Display for Compression { + #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } @@ -98,10 +100,12 @@ impl SerializedRequest { Ok(Self { data }) } + #[inline] pub fn set_stream(&mut self, stream: i16) { self.data[2..4].copy_from_slice(&stream.to_be_bytes()); } + #[inline] pub fn get_data(&self) -> &[u8] { &self.data[..] } @@ -116,6 +120,7 @@ pub struct FrameParams { } impl Default for FrameParams { + #[inline] fn default() -> Self { Self { version: 0x04, diff --git a/scylla-cql/src/frame/protocol_features.rs b/scylla-cql/src/frame/protocol_features.rs index fd142ac647..faf63ab030 100644 --- a/scylla-cql/src/frame/protocol_features.rs +++ b/scylla-cql/src/frame/protocol_features.rs @@ -68,6 +68,7 @@ impl ProtocolFeatures { } } + #[inline] pub fn prepared_flags_contain_lwt_mark(&self, flags: u32) -> bool { self.lwt_optimization_meta_bit_mask .map(|mask| (flags & mask) == mask) diff --git a/scylla-cql/src/frame/request/auth_response.rs b/scylla-cql/src/frame/request/auth_response.rs index c03bebaaf9..1b5214cf65 100644 --- a/scylla-cql/src/frame/request/auth_response.rs +++ b/scylla-cql/src/frame/request/auth_response.rs @@ -15,6 +15,7 @@ pub struct AuthResponse { impl SerializableRequest for AuthResponse { const OPCODE: RequestOpcode = RequestOpcode::AuthResponse; + #[inline] fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { Ok(write_bytes_opt(self.response.as_ref(), buf) .map_err(AuthResponseSerializationError::ResponseSerialization)?) diff --git a/scylla-cql/src/frame/request/batch.rs b/scylla-cql/src/frame/request/batch.rs index a0d6acd371..4d3e5594a6 100644 --- a/scylla-cql/src/frame/request/batch.rs +++ b/scylla-cql/src/frame/request/batch.rs @@ -53,6 +53,7 @@ pub struct BatchTypeParseError { impl TryFrom for BatchType { type Error = BatchTypeParseError; + #[inline] fn try_from(value: u8) -> Result { match value { 0 => Ok(Self::Logged), @@ -182,6 +183,7 @@ where { const OPCODE: RequestOpcode = RequestOpcode::Batch; + #[inline] fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { self.do_serialize(buf)?; Ok(()) @@ -230,6 +232,7 @@ impl BatchStatement<'_> { // Can be removed once https://github.com/rust-lang/rust-clippy/issues/12495 is fixed. #[allow(clippy::needless_lifetimes)] impl<'s, 'b> From<&'s BatchStatement<'b>> for BatchStatement<'s> { + #[inline] fn from(value: &'s BatchStatement) -> Self { match value { BatchStatement::Query { text } => BatchStatement::Query { text: text.clone() }, diff --git a/scylla-cql/src/frame/request/execute.rs b/scylla-cql/src/frame/request/execute.rs index ee758b01c5..c4ff2caa0f 100644 --- a/scylla-cql/src/frame/request/execute.rs +++ b/scylla-cql/src/frame/request/execute.rs @@ -23,6 +23,7 @@ pub struct Execute<'a> { impl SerializableRequest for Execute<'_> { const OPCODE: RequestOpcode = RequestOpcode::Execute; + #[inline] fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { // Serializing statement id types::write_short_bytes(&self.id[..], buf) @@ -37,6 +38,7 @@ impl SerializableRequest for Execute<'_> { } impl DeserializableRequest for Execute<'_> { + #[inline] fn deserialize(buf: &mut &[u8]) -> Result { let id = types::read_short_bytes(buf)?.to_vec().into(); let parameters = QueryParameters::deserialize(buf)?; diff --git a/scylla-cql/src/frame/request/mod.rs b/scylla-cql/src/frame/request/mod.rs index b9a197f82c..40542fac28 100644 --- a/scylla-cql/src/frame/request/mod.rs +++ b/scylla-cql/src/frame/request/mod.rs @@ -75,6 +75,7 @@ pub enum RequestOpcode { impl TryFrom for RequestOpcode { type Error = TryFromPrimitiveError; + #[inline] fn try_from(value: u8) -> Result { match value { 0x01 => Ok(Self::Startup), @@ -98,6 +99,7 @@ pub trait SerializableRequest { fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError>; + #[inline] fn to_bytes(&self) -> Result { let mut v = Vec::new(); self.serialize(&mut v)?; @@ -157,6 +159,7 @@ impl Request<'_> { } /// Retrieves consistency from request frame, if present. + #[inline] pub fn get_consistency(&self) -> Option { match self { Request::Query(q) => Some(q.parameters.consistency), @@ -168,6 +171,7 @@ impl Request<'_> { } /// Retrieves serial consistency from request frame. + #[inline] pub fn get_serial_consistency(&self) -> Option> { match self { Request::Query(q) => Some(q.parameters.serial_consistency), diff --git a/scylla-cql/src/frame/request/options.rs b/scylla-cql/src/frame/request/options.rs index ce3ba4b9e0..fa80ca9b54 100644 --- a/scylla-cql/src/frame/request/options.rs +++ b/scylla-cql/src/frame/request/options.rs @@ -7,6 +7,7 @@ pub struct Options; impl SerializableRequest for Options { const OPCODE: RequestOpcode = RequestOpcode::Options; + #[inline] fn serialize(&self, _buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { Ok(()) } diff --git a/scylla-cql/src/frame/request/prepare.rs b/scylla-cql/src/frame/request/prepare.rs index b4f2d26f09..b42e2a50a1 100644 --- a/scylla-cql/src/frame/request/prepare.rs +++ b/scylla-cql/src/frame/request/prepare.rs @@ -16,6 +16,7 @@ pub struct Prepare<'a> { impl SerializableRequest for Prepare<'_> { const OPCODE: RequestOpcode = RequestOpcode::Prepare; + #[inline] fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { types::write_long_string(self.query, buf) .map_err(PrepareSerializationError::StatementStringSerialization)?; diff --git a/scylla-cql/src/frame/request/query.rs b/scylla-cql/src/frame/request/query.rs index 949abbceb6..34bc97a47b 100644 --- a/scylla-cql/src/frame/request/query.rs +++ b/scylla-cql/src/frame/request/query.rs @@ -37,6 +37,7 @@ pub struct Query<'q> { impl SerializableRequest for Query<'_> { const OPCODE: RequestOpcode = RequestOpcode::Query; + #[inline] fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { types::write_long_string(&self.contents, buf) .map_err(QuerySerializationError::StatementStringSerialization)?; @@ -48,6 +49,7 @@ impl SerializableRequest for Query<'_> { } impl DeserializableRequest for Query<'_> { + #[inline] fn deserialize(buf: &mut &[u8]) -> Result { let contents = Cow::Owned(types::read_long_string(buf)?.to_owned()); let parameters = QueryParameters::deserialize(buf)?; @@ -71,6 +73,7 @@ pub struct QueryParameters<'a> { } impl Default for QueryParameters<'_> { + #[inline] fn default() -> Self { Self { consistency: Default::default(), @@ -279,6 +282,7 @@ impl PagingState { } impl Default for PagingState { + #[inline] fn default() -> Self { Self::start() } diff --git a/scylla-cql/src/frame/request/register.rs b/scylla-cql/src/frame/request/register.rs index 9abcfde05c..9bc78b10c1 100644 --- a/scylla-cql/src/frame/request/register.rs +++ b/scylla-cql/src/frame/request/register.rs @@ -16,6 +16,7 @@ pub struct Register { impl SerializableRequest for Register { const OPCODE: RequestOpcode = RequestOpcode::Register; + #[inline] fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { let event_types_list = self .event_types_to_register_for diff --git a/scylla-cql/src/frame/request/startup.rs b/scylla-cql/src/frame/request/startup.rs index cab84dc398..595cc29e3c 100644 --- a/scylla-cql/src/frame/request/startup.rs +++ b/scylla-cql/src/frame/request/startup.rs @@ -16,6 +16,7 @@ pub struct Startup<'a> { impl SerializableRequest for Startup<'_> { const OPCODE: RequestOpcode = RequestOpcode::Startup; + #[inline] fn serialize(&self, buf: &mut Vec) -> Result<(), CqlRequestSerializationError> { types::write_string_map(&self.options, buf) .map_err(StartupSerializationError::OptionsSerialization)?; diff --git a/scylla-cql/src/frame/response/authenticate.rs b/scylla-cql/src/frame/response/authenticate.rs index 2bfa26e674..85fb9457ad 100644 --- a/scylla-cql/src/frame/response/authenticate.rs +++ b/scylla-cql/src/frame/response/authenticate.rs @@ -10,6 +10,7 @@ pub struct Authenticate { } impl Authenticate { + #[inline] pub fn deserialize(buf: &mut &[u8]) -> Result { let authenticator_name = types::read_string(buf) .map_err(CqlAuthenticateParseError::AuthNameParseError)? @@ -25,6 +26,7 @@ pub struct AuthSuccess { } impl AuthSuccess { + #[inline] pub fn deserialize(buf: &mut &[u8]) -> Result { let success_message = types::read_bytes_opt(buf) .map_err(CqlAuthSuccessParseError::SuccessMessageParseError)? @@ -40,6 +42,7 @@ pub struct AuthChallenge { } impl AuthChallenge { + #[inline] pub fn deserialize(buf: &mut &[u8]) -> Result { let authenticate_message = types::read_bytes_opt(buf) .map_err(CqlAuthChallengeParseError::AuthMessageParseError)? diff --git a/scylla-cql/src/frame/response/error.rs b/scylla-cql/src/frame/response/error.rs index d40397b54a..0eec9b62fb 100644 --- a/scylla-cql/src/frame/response/error.rs +++ b/scylla-cql/src/frame/response/error.rs @@ -463,12 +463,14 @@ pub enum WriteType { } impl std::fmt::Display for WriteType { + #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + ::fmt(self, f) } } impl From for OperationType { + #[inline] fn from(operation_type: u8) -> OperationType { match operation_type { 0 => OperationType::Read, @@ -479,6 +481,7 @@ impl From for OperationType { } impl From<&str> for WriteType { + #[inline] fn from(write_type_str: &str) -> WriteType { match write_type_str { "SIMPLE" => WriteType::Simple, @@ -495,6 +498,7 @@ impl From<&str> for WriteType { } impl WriteType { + #[inline] pub fn as_str(&self) -> &str { match self { WriteType::Simple => "SIMPLE", diff --git a/scylla-cql/src/frame/response/mod.rs b/scylla-cql/src/frame/response/mod.rs index 43670d8d83..86bfa2ae7f 100644 --- a/scylla-cql/src/frame/response/mod.rs +++ b/scylla-cql/src/frame/response/mod.rs @@ -62,6 +62,7 @@ pub enum ResponseOpcode { impl TryFrom for ResponseOpcode { type Error = TryFromPrimitiveError; + #[inline] fn try_from(value: u8) -> Result> { match value { 0x00 => Ok(Self::Error), @@ -93,6 +94,7 @@ pub enum Response { } impl Response { + #[inline] pub fn to_response_kind(&self) -> CqlResponseKind { match self { Response::Error(_) => CqlResponseKind::Error, @@ -135,6 +137,7 @@ impl Response { Ok(response) } + #[inline] pub fn into_non_error_response(self) -> Result { let non_error_response = match self { Response::Error(e) => return Err(e), @@ -164,6 +167,7 @@ pub enum NonErrorResponse { } impl NonErrorResponse { + #[inline] pub fn to_response_kind(&self) -> CqlResponseKind { match self { NonErrorResponse::Ready => CqlResponseKind::Ready, diff --git a/scylla-cql/src/frame/response/result.rs b/scylla-cql/src/frame/response/result.rs index 8eec391b4a..8fec50564d 100644 --- a/scylla-cql/src/frame/response/result.rs +++ b/scylla-cql/src/frame/response/result.rs @@ -184,6 +184,7 @@ impl CollectionType<'_> { } impl<'a> TableSpec<'a> { + #[inline] pub const fn borrowed(ks: &'a str, table: &'a str) -> Self { Self { ks_name: Cow::Borrowed(ks), @@ -191,24 +192,29 @@ impl<'a> TableSpec<'a> { } } + #[inline] pub fn ks_name(&'a self) -> &'a str { self.ks_name.as_ref() } + #[inline] pub fn table_name(&'a self) -> &'a str { self.table_name.as_ref() } + #[inline] pub fn into_owned(self) -> TableSpec<'static> { TableSpec::owned(self.ks_name.into_owned(), self.table_name.into_owned()) } + #[inline] pub fn to_owned(&self) -> TableSpec<'static> { TableSpec::owned(self.ks_name().to_owned(), self.table_name().to_owned()) } } impl TableSpec<'static> { + #[inline] pub fn owned(ks_name: String, table_name: String) -> Self { Self { ks_name: Cow::Owned(ks_name), @@ -428,6 +434,7 @@ mod self_borrowed_metadata { impl Deref for BytesWrapper { type Target = [u8]; + #[inline] fn deref(&self) -> &Self::Target { &self.inner } @@ -464,6 +471,7 @@ mod self_borrowed_metadata { impl SelfBorrowedMetadataContainer { /// Creates an empty [SelfBorrowedMetadataContainer]. + #[inline] pub fn mock_empty() -> Self { Self { metadata_and_raw_rows: Yoke::attach_to_cart( @@ -476,6 +484,7 @@ mod self_borrowed_metadata { } /// Returns a reference to the contained [ResultMetadata]. + #[inline] pub fn metadata(&self) -> &ResultMetadata<'_> { &self.metadata_and_raw_rows.get().0 } @@ -1283,7 +1292,6 @@ mod test_utils { } impl DeserializedMetadataAndRawRows { - #[inline] #[cfg(test)] pub(crate) fn new_for_test( metadata: ResultMetadata<'static>, diff --git a/scylla-cql/src/frame/response/supported.rs b/scylla-cql/src/frame/response/supported.rs index 055c821731..b6aea8b6a4 100644 --- a/scylla-cql/src/frame/response/supported.rs +++ b/scylla-cql/src/frame/response/supported.rs @@ -8,6 +8,7 @@ pub struct Supported { } impl Supported { + #[inline] pub fn deserialize(buf: &mut &[u8]) -> Result { let options = types::read_string_multimap(buf) .map_err(CqlSupportedParseError::OptionsMapDeserialization)?; diff --git a/scylla-cql/src/frame/server_event_type.rs b/scylla-cql/src/frame/server_event_type.rs index 379f9bc3cc..445f58b057 100644 --- a/scylla-cql/src/frame/server_event_type.rs +++ b/scylla-cql/src/frame/server_event_type.rs @@ -24,6 +24,7 @@ impl fmt::Display for EventType { impl FromStr for EventType { type Err = CqlEventParseError; + #[inline] fn from_str(s: &str) -> Result { match s { "TOPOLOGY_CHANGE" => Ok(Self::TopologyChange), diff --git a/scylla-cql/src/frame/types.rs b/scylla-cql/src/frame/types.rs index 2ea5a8b6b3..63b75c373b 100644 --- a/scylla-cql/src/frame/types.rs +++ b/scylla-cql/src/frame/types.rs @@ -41,6 +41,7 @@ pub enum Consistency { impl TryFrom for Consistency { type Error = TryFromPrimitiveError; + #[inline] fn try_from(value: u16) -> Result { match value { 0x0000 => Ok(Consistency::Any), @@ -74,6 +75,7 @@ pub enum SerialConsistency { impl TryFrom for SerialConsistency { type Error = TryFromPrimitiveError; + #[inline] fn try_from(value: i16) -> Result { match value { 0x0008 => Ok(Self::Serial), @@ -87,6 +89,7 @@ impl TryFrom for SerialConsistency { } impl Consistency { + #[inline] pub fn is_serial(&self) -> bool { matches!(self, Consistency::Serial | Consistency::LocalSerial) } @@ -117,14 +120,16 @@ impl TryFrom for SerialConsistency { } impl std::fmt::Display for Consistency { + #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + ::fmt(self, f) } } impl std::fmt::Display for SerialConsistency { + #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + ::fmt(self, f) } } @@ -160,15 +165,18 @@ fn read_raw_bytes<'a>( Ok(ret) } +#[inline] pub fn read_int(buf: &mut &[u8]) -> Result { let v = buf.read_i32::()?; Ok(v) } +#[inline] pub fn write_int(v: i32, buf: &mut impl BufMut) { buf.put_i32(v); } +#[inline] pub fn read_int_length(buf: &mut &[u8]) -> Result { let v = read_int(buf)?; let v: usize = v.try_into()?; @@ -196,11 +204,13 @@ fn type_int() { } } +#[inline] pub fn read_long(buf: &mut &[u8]) -> Result { let v = buf.read_i64::()?; Ok(v) } +#[inline] pub fn write_long(v: i64, buf: &mut impl BufMut) { buf.put_i64(v); } @@ -215,11 +225,13 @@ fn type_long() { } } +#[inline] pub fn read_short(buf: &mut &[u8]) -> Result { let v = buf.read_u16::()?; Ok(v) } +#[inline] pub fn write_short(v: u16, buf: &mut impl BufMut) { buf.put_u16(v); } @@ -250,6 +262,7 @@ fn type_short() { } // https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec#L208 +#[inline] pub fn read_bytes_opt<'a>( buf: &mut &'a [u8], ) -> Result, LowLevelDeserializationError> { @@ -263,12 +276,14 @@ pub fn read_bytes_opt<'a>( } // Same as read_bytes, but we assume the value won't be `null` +#[inline] pub fn read_bytes<'a>(buf: &mut &'a [u8]) -> Result<&'a [u8], LowLevelDeserializationError> { let len = read_int_length(buf)?; let v = read_raw_bytes(len, buf)?; Ok(v) } +#[inline] pub fn read_value<'a>(buf: &mut &'a [u8]) -> Result, LowLevelDeserializationError> { let len = read_int(buf)?; match len { @@ -282,18 +297,21 @@ pub fn read_value<'a>(buf: &mut &'a [u8]) -> Result, LowLevelDeseri } } +#[inline] pub fn read_short_bytes<'a>(buf: &mut &'a [u8]) -> Result<&'a [u8], LowLevelDeserializationError> { let len = read_short_length(buf)?; let v = read_raw_bytes(len, buf)?; Ok(v) } +#[inline] pub fn write_bytes(v: &[u8], buf: &mut impl BufMut) -> Result<(), std::num::TryFromIntError> { write_int_length(v.len(), buf)?; buf.put_slice(v); Ok(()) } +#[inline] pub fn write_bytes_opt( v: Option>, buf: &mut impl BufMut, @@ -309,12 +327,14 @@ pub fn write_bytes_opt( Ok(()) } +#[inline] pub fn write_short_bytes(v: &[u8], buf: &mut impl BufMut) -> Result<(), std::num::TryFromIntError> { write_short_length(v.len(), buf)?; buf.put_slice(v); Ok(()) } +#[inline] pub fn read_bytes_map( buf: &mut &[u8], ) -> Result, LowLevelDeserializationError> { @@ -328,6 +348,7 @@ pub fn read_bytes_map( Ok(v) } +#[inline] pub fn write_bytes_map( v: &HashMap, buf: &mut impl BufMut, @@ -355,6 +376,7 @@ fn type_bytes_map() { assert_eq!(read_bytes_map(&mut &*buf).unwrap(), val); } +#[inline] pub fn read_string<'a>(buf: &mut &'a [u8]) -> Result<&'a str, LowLevelDeserializationError> { let len = read_short_length(buf)?; let raw = read_raw_bytes(len, buf)?; @@ -362,6 +384,7 @@ pub fn read_string<'a>(buf: &mut &'a [u8]) -> Result<&'a str, LowLevelDeserializ Ok(v) } +#[inline] pub fn write_string(v: &str, buf: &mut impl BufMut) -> Result<(), std::num::TryFromIntError> { let raw = v.as_bytes(); write_short_length(v.len(), buf)?; @@ -379,6 +402,7 @@ fn type_string() { } } +#[inline] pub fn read_long_string<'a>(buf: &mut &'a [u8]) -> Result<&'a str, LowLevelDeserializationError> { let len = read_int_length(buf)?; let raw = read_raw_bytes(len, buf)?; @@ -386,6 +410,7 @@ pub fn read_long_string<'a>(buf: &mut &'a [u8]) -> Result<&'a str, LowLevelDeser Ok(v) } +#[inline] pub fn write_long_string(v: &str, buf: &mut impl BufMut) -> Result<(), std::num::TryFromIntError> { let raw = v.as_bytes(); let len = raw.len(); @@ -404,6 +429,7 @@ fn type_long_string() { } } +#[inline] pub fn read_string_map( buf: &mut &[u8], ) -> Result, LowLevelDeserializationError> { @@ -417,6 +443,7 @@ pub fn read_string_map( Ok(v) } +#[inline] pub fn write_string_map( v: &HashMap, impl AsRef>, buf: &mut impl BufMut, @@ -441,6 +468,7 @@ fn type_string_map() { assert_eq!(read_string_map(&mut &buf[..]).unwrap(), val); } +#[inline] pub fn read_string_list(buf: &mut &[u8]) -> Result, LowLevelDeserializationError> { let len = read_short_length(buf)?; let mut v = Vec::with_capacity(len); @@ -450,6 +478,7 @@ pub fn read_string_list(buf: &mut &[u8]) -> Result, LowLevelDeserial Ok(v) } +#[inline] pub fn write_string_list( v: &[String], buf: &mut impl BufMut, @@ -475,6 +504,7 @@ fn type_string_list() { assert_eq!(read_string_list(&mut &buf[..]).unwrap(), val); } +#[inline] pub fn read_string_multimap( buf: &mut &[u8], ) -> Result>, LowLevelDeserializationError> { @@ -488,6 +518,7 @@ pub fn read_string_multimap( Ok(v) } +#[inline] pub fn write_string_multimap( v: &HashMap>, buf: &mut impl BufMut, @@ -515,6 +546,7 @@ fn type_string_multimap() { assert_eq!(read_string_multimap(&mut &buf[..]).unwrap(), val); } +#[inline] pub fn read_uuid(buf: &mut &[u8]) -> Result { let raw = read_raw_bytes(16, buf)?; @@ -526,6 +558,7 @@ pub fn read_uuid(buf: &mut &[u8]) -> Result Ok(Uuid::from_bytes(*raw_array)) } +#[inline] pub fn write_uuid(uuid: &Uuid, buf: &mut impl BufMut) { buf.put_slice(&uuid.as_bytes()[..]); } @@ -539,15 +572,18 @@ fn type_uuid() { assert_eq!(u, u2); } +#[inline] pub fn read_consistency(buf: &mut &[u8]) -> Result { let raw = read_short(buf)?; Consistency::try_from(raw).map_err(LowLevelDeserializationError::UnknownConsistency) } +#[inline] pub fn write_consistency(c: Consistency, buf: &mut impl BufMut) { write_short(c as u16, buf); } +#[inline] pub fn write_serial_consistency(c: SerialConsistency, buf: &mut impl BufMut) { write_short(c as u16, buf); } @@ -571,6 +607,7 @@ fn type_consistency() { assert!(err_str.contains(&format!("{}", c))); } +#[inline] pub fn read_inet(buf: &mut &[u8]) -> Result { let len = buf.read_u8()?; let ip_addr = match len { @@ -591,6 +628,7 @@ pub fn read_inet(buf: &mut &[u8]) -> Result { diff --git a/scylla-cql/src/serialize/raw_batch.rs b/scylla-cql/src/serialize/raw_batch.rs index 6c755c5e88..f8400680b8 100644 --- a/scylla-cql/src/serialize/raw_batch.rs +++ b/scylla-cql/src/serialize/raw_batch.rs @@ -77,6 +77,7 @@ impl<'r> RawBatchValuesIterator<'r> for std::slice::Iter<'r, SerializedValues> { }) } + #[inline] fn is_empty_next(&mut self) -> Option { self.next().map(|sv| sv.is_empty()) } @@ -152,6 +153,7 @@ where self.batch_values_iterator.serialize_next(&ctx, writer) } + #[inline] fn is_empty_next(&mut self) -> Option { let _ = self.contexts.next(); let ret = self.batch_values_iterator.is_empty_next()?; diff --git a/scylla-cql/src/serialize/row.rs b/scylla-cql/src/serialize/row.rs index 2ad87e4254..ee8425633b 100644 --- a/scylla-cql/src/serialize/row.rs +++ b/scylla-cql/src/serialize/row.rs @@ -478,6 +478,7 @@ pub struct SerializedValues { impl SerializedValues { /// Constructs a new, empty `SerializedValues`. + #[inline] pub const fn new() -> Self { SerializedValues { serialized_values: Vec::new(), @@ -489,6 +490,7 @@ impl SerializedValues { pub const EMPTY: &'static SerializedValues = &SerializedValues::new(); /// Constructs `SerializedValues` from given [`SerializeRow`] object. + #[inline] pub fn from_serializable( ctx: &RowSerializationContext, row: &T, @@ -601,6 +603,7 @@ impl SerializedValues { } impl Default for SerializedValues { + #[inline] fn default() -> Self { Self::new() } @@ -615,6 +618,7 @@ pub struct SerializedValuesIterator<'a> { impl<'a> Iterator for SerializedValuesIterator<'a> { type Item = RawValue<'a>; + #[inline] fn next(&mut self) -> Option { if self.serialized_values.is_empty() { return None; diff --git a/scylla-cql/src/serialize/value.rs b/scylla-cql/src/serialize/value.rs index 93c52d4219..bc0ad6a475 100644 --- a/scylla-cql/src/serialize/value.rs +++ b/scylla-cql/src/serialize/value.rs @@ -344,6 +344,7 @@ impl SerializeValue for String { }); } impl SerializeValue for Option { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -376,6 +377,7 @@ impl SerializeValue for CqlDuration { }); } impl SerializeValue for MaybeUnset { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -388,6 +390,7 @@ impl SerializeValue for MaybeUnset { } } impl SerializeValue for &T { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -397,6 +400,7 @@ impl SerializeValue for &T { } } impl SerializeValue for Box { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -406,6 +410,7 @@ impl SerializeValue for Box { } } impl SerializeValue for HashSet { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -421,6 +426,7 @@ impl SerializeValue for HashSet SerializeValue for HashMap { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -436,6 +442,7 @@ impl SerializeValue for Ha } } impl SerializeValue for BTreeSet { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -451,6 +458,7 @@ impl SerializeValue for BTreeSet { } } impl SerializeValue for BTreeMap { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -466,6 +474,7 @@ impl SerializeValue for BTreeMap { } } impl SerializeValue for Vec { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -481,6 +490,7 @@ impl SerializeValue for Vec { } } impl<'a, T: SerializeValue + 'a> SerializeValue for &'a [T] { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -496,6 +506,7 @@ impl<'a, T: SerializeValue + 'a> SerializeValue for &'a [T] { } } impl SerializeValue for CqlValue { + #[inline] fn serialize<'b>( &self, typ: &ColumnType, @@ -997,24 +1008,28 @@ pub enum BuiltinTypeCheckErrorKind { } impl From for BuiltinTypeCheckErrorKind { + #[inline] fn from(value: SetOrListTypeCheckErrorKind) -> Self { BuiltinTypeCheckErrorKind::SetOrListError(value) } } impl From for BuiltinTypeCheckErrorKind { + #[inline] fn from(value: MapTypeCheckErrorKind) -> Self { BuiltinTypeCheckErrorKind::MapError(value) } } impl From for BuiltinTypeCheckErrorKind { + #[inline] fn from(value: TupleTypeCheckErrorKind) -> Self { BuiltinTypeCheckErrorKind::TupleError(value) } } impl From for BuiltinTypeCheckErrorKind { + #[inline] fn from(value: UdtTypeCheckErrorKind) -> Self { BuiltinTypeCheckErrorKind::UdtError(value) } @@ -1062,24 +1077,28 @@ pub enum BuiltinSerializationErrorKind { } impl From for BuiltinSerializationErrorKind { + #[inline] fn from(value: SetOrListSerializationErrorKind) -> Self { BuiltinSerializationErrorKind::SetOrListError(value) } } impl From for BuiltinSerializationErrorKind { + #[inline] fn from(value: MapSerializationErrorKind) -> Self { BuiltinSerializationErrorKind::MapError(value) } } impl From for BuiltinSerializationErrorKind { + #[inline] fn from(value: TupleSerializationErrorKind) -> Self { BuiltinSerializationErrorKind::TupleError(value) } } impl From for BuiltinSerializationErrorKind { + #[inline] fn from(value: UdtSerializationErrorKind) -> Self { BuiltinSerializationErrorKind::UdtError(value) } diff --git a/scylla-cql/src/value.rs b/scylla-cql/src/value.rs index 89be4e49d4..e98195a06b 100644 --- a/scylla-cql/src/value.rs +++ b/scylla-cql/src/value.rs @@ -42,58 +42,72 @@ pub struct CqlTimeuuid(Uuid); /// [`Uuid`] delegate methods impl CqlTimeuuid { + #[inline] pub fn nil() -> Self { Self(Uuid::nil()) } + #[inline] pub fn as_bytes(&self) -> &[u8; 16] { self.0.as_bytes() } + #[inline] pub fn as_u128(&self) -> u128 { self.0.as_u128() } + #[inline] pub fn as_fields(&self) -> (u32, u16, u16, &[u8; 8]) { self.0.as_fields() } + #[inline] pub fn as_u64_pair(&self) -> (u64, u64) { self.0.as_u64_pair() } + #[inline] pub fn from_slice(b: &[u8]) -> Result { Ok(Self(Uuid::from_slice(b)?)) } + #[inline] pub fn from_slice_le(b: &[u8]) -> Result { Ok(Self(Uuid::from_slice_le(b)?)) } + #[inline] pub fn from_bytes(bytes: [u8; 16]) -> Self { Self(Uuid::from_bytes(bytes)) } + #[inline] pub fn from_bytes_le(bytes: [u8; 16]) -> Self { Self(Uuid::from_bytes_le(bytes)) } + #[inline] pub fn from_fields(d1: u32, d2: u16, d3: u16, d4: &[u8; 8]) -> Self { Self(Uuid::from_fields(d1, d2, d3, d4)) } + #[inline] pub fn from_fields_le(d1: u32, d2: u16, d3: u16, d4: &[u8; 8]) -> Self { Self(Uuid::from_fields_le(d1, d2, d3, d4)) } + #[inline] pub fn from_u128(v: u128) -> Self { Self(Uuid::from_u128(v)) } + #[inline] pub fn from_u128_le(v: u128) -> Self { Self(Uuid::from_u128_le(v)) } + #[inline] pub fn from_u64_pair(high_bits: u64, low_bits: u64) -> Self { Self(Uuid::from_u64_pair(high_bits, low_bits)) } @@ -133,30 +147,35 @@ impl CqlTimeuuid { impl std::str::FromStr for CqlTimeuuid { type Err = uuid::Error; + #[inline] fn from_str(s: &str) -> Result { Ok(Self(Uuid::from_str(s)?)) } } impl std::fmt::Display for CqlTimeuuid { + #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.0) + <_ as std::fmt::Display>::fmt(&self.0, f) } } impl AsRef for CqlTimeuuid { + #[inline] fn as_ref(&self) -> &Uuid { &self.0 } } impl From for Uuid { + #[inline] fn from(value: CqlTimeuuid) -> Self { value.0 } } impl From for CqlTimeuuid { + #[inline] fn from(value: Uuid) -> Self { Self(value) } @@ -170,6 +189,7 @@ impl From for CqlTimeuuid { /// treat possible non-version-1 UUID the same way as UUID. /// - using signed compare for least significant bits. impl Ord for CqlTimeuuid { + #[inline] fn cmp(&self, other: &Self) -> std::cmp::Ordering { let mut res = self.msb().cmp(&other.msb()); if let std::cmp::Ordering::Equal = res { @@ -180,18 +200,21 @@ impl Ord for CqlTimeuuid { } impl PartialOrd for CqlTimeuuid { + #[inline] fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for CqlTimeuuid { + #[inline] fn eq(&self, other: &Self) -> bool { self.cmp(other) == std::cmp::Ordering::Equal } } impl std::hash::Hash for CqlTimeuuid { + #[inline] fn hash(&self, state: &mut H) { self.lsb_signed().hash(state); self.msb().hash(state); @@ -241,6 +264,7 @@ impl CqlVarint { /// two's complement big-endian binary representation. /// /// See: disclaimer about [non-normalized values](CqlVarint#db-data-format). + #[inline] pub fn from_signed_bytes_be(digits: Vec) -> Self { Self(digits) } @@ -249,6 +273,7 @@ impl CqlVarint { /// two's complement binary big-endian representation. /// /// See: disclaimer about [non-normalized values](CqlVarint#db-data-format). + #[inline] pub fn from_signed_bytes_be_slice(digits: &[u8]) -> Self { Self::from_signed_bytes_be(digits.to_vec()) } @@ -260,6 +285,7 @@ impl<'b> CqlVarintBorrowed<'b> { /// two's complement binary big-endian representation. /// /// See: disclaimer about [non-normalized values](CqlVarint#db-data-format). + #[inline] pub fn from_signed_bytes_be_slice(digits: &'b [u8]) -> Self { Self(digits) } @@ -269,12 +295,14 @@ impl<'b> CqlVarintBorrowed<'b> { impl CqlVarint { /// Converts [`CqlVarint`] to an array of bytes in two's /// complement binary big-endian representation. + #[inline] pub fn into_signed_bytes_be(self) -> Vec { self.0 } /// Returns a slice of bytes in two's complement /// binary big-endian representation. + #[inline] pub fn as_signed_bytes_be_slice(&self) -> &[u8] { &self.0 } @@ -284,6 +312,7 @@ impl CqlVarint { impl CqlVarintBorrowed<'_> { /// Returns a slice of bytes in two's complement /// binary big-endian representation. + #[inline] pub fn as_signed_bytes_be_slice(&self) -> &[u8] { self.0 } @@ -360,6 +389,7 @@ impl AsNormalizedVarintSlice for V { /// ); /// ``` impl PartialEq for CqlVarint { + #[inline] fn eq(&self, other: &Self) -> bool { self.as_normalized_slice() == other.as_normalized_slice() } @@ -367,6 +397,7 @@ impl PartialEq for CqlVarint { /// Computes the hash of normalized [`CqlVarint`]. impl std::hash::Hash for CqlVarint { + #[inline] fn hash(&self, state: &mut H) { self.as_normalized_slice().hash(state) } @@ -386,6 +417,7 @@ impl std::hash::Hash for CqlVarint { /// ); /// ``` impl PartialEq for CqlVarintBorrowed<'_> { + #[inline] fn eq(&self, other: &Self) -> bool { self.as_normalized_slice() == other.as_normalized_slice() } @@ -393,6 +425,7 @@ impl PartialEq for CqlVarintBorrowed<'_> { /// Computes the hash of normalized [`CqlVarintBorrowed`]. impl std::hash::Hash for CqlVarintBorrowed<'_> { + #[inline] fn hash(&self, state: &mut H) { self.as_normalized_slice().hash(state) } @@ -400,6 +433,7 @@ impl std::hash::Hash for CqlVarintBorrowed<'_> { #[cfg(feature = "num-bigint-03")] impl From for CqlVarint { + #[inline] fn from(value: num_bigint_03::BigInt) -> Self { Self(value.to_signed_bytes_be()) } @@ -407,6 +441,7 @@ impl From for CqlVarint { #[cfg(feature = "num-bigint-03")] impl From for num_bigint_03::BigInt { + #[inline] fn from(val: CqlVarint) -> Self { num_bigint_03::BigInt::from_signed_bytes_be(&val.0) } @@ -414,6 +449,7 @@ impl From for num_bigint_03::BigInt { #[cfg(feature = "num-bigint-03")] impl From> for num_bigint_03::BigInt { + #[inline] fn from(val: CqlVarintBorrowed<'_>) -> Self { num_bigint_03::BigInt::from_signed_bytes_be(val.0) } @@ -421,6 +457,7 @@ impl From> for num_bigint_03::BigInt { #[cfg(feature = "num-bigint-04")] impl From for CqlVarint { + #[inline] fn from(value: num_bigint_04::BigInt) -> Self { Self(value.to_signed_bytes_be()) } @@ -428,6 +465,7 @@ impl From for CqlVarint { #[cfg(feature = "num-bigint-04")] impl From for num_bigint_04::BigInt { + #[inline] fn from(val: CqlVarint) -> Self { num_bigint_04::BigInt::from_signed_bytes_be(&val.0) } @@ -435,6 +473,7 @@ impl From for num_bigint_04::BigInt { #[cfg(feature = "num-bigint-04")] impl From> for num_bigint_04::BigInt { + #[inline] fn from(val: CqlVarintBorrowed<'_>) -> Self { num_bigint_04::BigInt::from_signed_bytes_be(val.0) } @@ -485,6 +524,7 @@ impl CqlDecimal { /// representing [`CqlVarint`] and a 32-bit scale. /// /// See: disclaimer about [non-normalized values](CqlVarint#db-data-format). + #[inline] pub fn from_signed_be_bytes_and_exponent(bytes: Vec, scale: i32) -> Self { Self { int_val: CqlVarint::from_signed_bytes_be(bytes), @@ -496,6 +536,7 @@ impl CqlDecimal { /// representing [`CqlVarint`] and a 32-bit scale. /// /// See: disclaimer about [non-normalized values](CqlVarint#db-data-format). + #[inline] pub fn from_signed_be_bytes_slice_and_exponent(bytes: &[u8], scale: i32) -> Self { Self::from_signed_be_bytes_and_exponent(bytes.to_vec(), scale) } @@ -507,6 +548,7 @@ impl<'b> CqlDecimalBorrowed<'b> { /// representing [`CqlVarintBorrowed`] and a 32-bit scale. /// /// See: disclaimer about [non-normalized values](CqlVarint#db-data-format). + #[inline] pub fn from_signed_be_bytes_slice_and_exponent(bytes: &'b [u8], scale: i32) -> Self { Self { int_val: CqlVarintBorrowed::from_signed_bytes_be_slice(bytes), @@ -519,12 +561,14 @@ impl<'b> CqlDecimalBorrowed<'b> { impl CqlDecimal { /// Returns a slice of bytes in two's complement /// binary big-endian representation and a scale. + #[inline] pub fn as_signed_be_bytes_slice_and_exponent(&self) -> (&[u8], i32) { (self.int_val.as_signed_bytes_be_slice(), self.scale) } /// Converts [`CqlDecimal`] to an array of bytes in two's /// complement binary big-endian representation and a scale. + #[inline] pub fn into_signed_be_bytes_and_exponent(self) -> (Vec, i32) { (self.int_val.into_signed_bytes_be(), self.scale) } @@ -534,6 +578,7 @@ impl CqlDecimal { impl CqlDecimalBorrowed<'_> { /// Returns a slice of bytes in two's complement /// binary big-endian representation and a scale. + #[inline] pub fn as_signed_be_bytes_slice_and_exponent(&self) -> (&[u8], i32) { (self.int_val.as_signed_bytes_be_slice(), self.scale) } @@ -541,6 +586,7 @@ impl CqlDecimalBorrowed<'_> { #[cfg(feature = "bigdecimal-04")] impl From for bigdecimal_04::BigDecimal { + #[inline] fn from(value: CqlDecimal) -> Self { Self::from(( bigdecimal_04::num_bigint::BigInt::from_signed_bytes_be( @@ -553,6 +599,7 @@ impl From for bigdecimal_04::BigDecimal { #[cfg(feature = "bigdecimal-04")] impl From> for bigdecimal_04::BigDecimal { + #[inline] fn from(value: CqlDecimalBorrowed) -> Self { Self::from(( bigdecimal_04::num_bigint::BigInt::from_signed_bytes_be( @@ -567,6 +614,7 @@ impl From> for bigdecimal_04::BigDecimal { impl TryFrom for CqlDecimal { type Error = >::Error; + #[inline] fn try_from(value: bigdecimal_04::BigDecimal) -> Result { let (bigint, scale) = value.into_bigint_and_exponent(); let bytes = bigint.to_signed_bytes_be(); @@ -613,6 +661,7 @@ impl CqlDate { #[cfg(feature = "chrono-04")] impl From for CqlDate { + #[inline] fn from(value: chrono_04::NaiveDate) -> Self { let unix_epoch = chrono_04::NaiveDate::from_yo_opt(1970, 1).unwrap(); @@ -628,6 +677,7 @@ impl From for CqlDate { impl TryInto for CqlDate { type Error = ValueOverflow; + #[inline] fn try_into(self) -> Result { self.try_to_chrono_04_naive_date() } @@ -647,6 +697,7 @@ impl CqlTimestamp { #[cfg(feature = "chrono-04")] impl From> for CqlTimestamp { + #[inline] fn from(value: chrono_04::DateTime) -> Self { Self(value.timestamp_millis()) } @@ -656,6 +707,7 @@ impl From> for CqlTimestamp { impl TryInto> for CqlTimestamp { type Error = ValueOverflow; + #[inline] fn try_into(self) -> Result, Self::Error> { self.try_to_chrono_04_datetime_utc() } @@ -665,6 +717,7 @@ impl TryInto> for CqlTimestamp { impl TryFrom for CqlTime { type Error = ValueOverflow; + #[inline] fn try_from(value: chrono_04::NaiveTime) -> Result { let nanos = value .signed_duration_since(chrono_04::NaiveTime::MIN) @@ -684,6 +737,7 @@ impl TryFrom for CqlTime { impl TryInto for CqlTime { type Error = ValueOverflow; + #[inline] fn try_into(self) -> Result { let secs = (self.0 / 1_000_000_000) .try_into() @@ -697,6 +751,7 @@ impl TryInto for CqlTime { #[cfg(feature = "time-03")] impl From for CqlDate { + #[inline] fn from(value: time_03::Date) -> Self { const JULIAN_DAY_OFFSET: i64 = (1 << 31) - time_03::OffsetDateTime::UNIX_EPOCH.date().to_julian_day() as i64; @@ -719,6 +774,7 @@ impl From for CqlDate { impl TryInto for CqlDate { type Error = ValueOverflow; + #[inline] fn try_into(self) -> Result { const JULIAN_DAY_OFFSET: i64 = (1 << 31) - time_03::OffsetDateTime::UNIX_EPOCH.date().to_julian_day() as i64; @@ -733,6 +789,7 @@ impl TryInto for CqlDate { #[cfg(feature = "time-03")] impl From for CqlTimestamp { + #[inline] fn from(value: time_03::OffsetDateTime) -> Self { // Statically assert that no possible value will ever overflow. OffsetDateTime doesn't allow offset to overflow // the UTC PrimitiveDateTime value value @@ -761,6 +818,7 @@ impl From for CqlTimestamp { impl TryInto for CqlTimestamp { type Error = ValueOverflow; + #[inline] fn try_into(self) -> Result { time_03::OffsetDateTime::from_unix_timestamp_nanos(self.0 as i128 * 1_000_000) .map_err(|_| ValueOverflow) @@ -769,6 +827,7 @@ impl TryInto for CqlTimestamp { #[cfg(feature = "time-03")] impl From for CqlTime { + #[inline] fn from(value: time_03::Time) -> Self { let (h, m, s, n) = value.as_hms_nano(); @@ -783,6 +842,7 @@ impl From for CqlTime { impl TryInto for CqlTime { type Error = ValueOverflow; + #[inline] fn try_into(self) -> Result { let h = self.0 / 3_600_000_000_000; let m = self.0 / 60_000_000_000 % 60; @@ -850,6 +910,7 @@ pub enum CqlValue { } impl CqlValue { + #[inline] pub fn as_ascii(&self) -> Option<&String> { match self { Self::Ascii(s) => Some(s), @@ -857,6 +918,7 @@ impl CqlValue { } } + #[inline] pub fn as_cql_date(&self) -> Option { match self { Self::Date(d) => Some(*d), @@ -876,6 +938,7 @@ impl CqlValue { self.as_cql_date().and_then(|date| date.try_into().ok()) } + #[inline] pub fn as_cql_timestamp(&self) -> Option { match self { Self::Timestamp(i) => Some(*i), @@ -895,6 +958,7 @@ impl CqlValue { self.as_cql_timestamp().and_then(|ts| ts.try_into().ok()) } + #[inline] pub fn as_cql_time(&self) -> Option { match self { Self::Time(i) => Some(*i), @@ -914,6 +978,7 @@ impl CqlValue { self.as_cql_time().and_then(|ts| ts.try_into().ok()) } + #[inline] pub fn as_cql_duration(&self) -> Option { match self { Self::Duration(i) => Some(*i), @@ -921,6 +986,7 @@ impl CqlValue { } } + #[inline] pub fn as_counter(&self) -> Option { match self { Self::Counter(i) => Some(*i), @@ -928,6 +994,7 @@ impl CqlValue { } } + #[inline] pub fn as_boolean(&self) -> Option { match self { Self::Boolean(i) => Some(*i), @@ -935,6 +1002,7 @@ impl CqlValue { } } + #[inline] pub fn as_double(&self) -> Option { match self { Self::Double(d) => Some(*d), @@ -942,6 +1010,7 @@ impl CqlValue { } } + #[inline] pub fn as_uuid(&self) -> Option { match self { Self::Uuid(u) => Some(*u), @@ -949,6 +1018,7 @@ impl CqlValue { } } + #[inline] pub fn as_float(&self) -> Option { match self { Self::Float(f) => Some(*f), @@ -956,6 +1026,7 @@ impl CqlValue { } } + #[inline] pub fn as_int(&self) -> Option { match self { Self::Int(i) => Some(*i), @@ -963,6 +1034,7 @@ impl CqlValue { } } + #[inline] pub fn as_bigint(&self) -> Option { match self { Self::BigInt(i) => Some(*i), @@ -970,6 +1042,7 @@ impl CqlValue { } } + #[inline] pub fn as_tinyint(&self) -> Option { match self { Self::TinyInt(i) => Some(*i), @@ -977,6 +1050,7 @@ impl CqlValue { } } + #[inline] pub fn as_smallint(&self) -> Option { match self { Self::SmallInt(i) => Some(*i), @@ -984,6 +1058,7 @@ impl CqlValue { } } + #[inline] pub fn as_blob(&self) -> Option<&Vec> { match self { Self::Blob(v) => Some(v), @@ -991,6 +1066,7 @@ impl CqlValue { } } + #[inline] pub fn as_text(&self) -> Option<&String> { match self { Self::Text(s) => Some(s), @@ -998,6 +1074,7 @@ impl CqlValue { } } + #[inline] pub fn as_timeuuid(&self) -> Option { match self { Self::Timeuuid(u) => Some(*u), @@ -1005,6 +1082,7 @@ impl CqlValue { } } + #[inline] pub fn into_string(self) -> Option { match self { Self::Ascii(s) => Some(s), @@ -1013,6 +1091,7 @@ impl CqlValue { } } + #[inline] pub fn into_blob(self) -> Option> { match self { Self::Blob(b) => Some(b), @@ -1020,6 +1099,7 @@ impl CqlValue { } } + #[inline] pub fn as_inet(&self) -> Option { match self { Self::Inet(a) => Some(*a), @@ -1027,6 +1107,7 @@ impl CqlValue { } } + #[inline] pub fn as_list(&self) -> Option<&Vec> { match self { Self::List(s) => Some(s), @@ -1034,6 +1115,7 @@ impl CqlValue { } } + #[inline] pub fn as_set(&self) -> Option<&Vec> { match self { Self::Set(s) => Some(s), @@ -1041,6 +1123,7 @@ impl CqlValue { } } + #[inline] pub fn as_map(&self) -> Option<&Vec<(CqlValue, CqlValue)>> { match self { Self::Map(s) => Some(s), @@ -1048,6 +1131,7 @@ impl CqlValue { } } + #[inline] pub fn as_udt(&self) -> Option<&Vec<(String, Option)>> { match self { Self::UserDefinedType { fields, .. } => Some(fields), @@ -1055,6 +1139,7 @@ impl CqlValue { } } + #[inline] pub fn into_vec(self) -> Option> { match self { Self::List(s) => Some(s), @@ -1063,6 +1148,7 @@ impl CqlValue { } } + #[inline] pub fn into_pair_vec(self) -> Option> { match self { Self::Map(s) => Some(s), @@ -1070,6 +1156,7 @@ impl CqlValue { } } + #[inline] pub fn into_udt_pair_vec(self) -> Option)>> { match self { Self::UserDefinedType { fields, .. } => Some(fields), @@ -1077,6 +1164,7 @@ impl CqlValue { } } + #[inline] pub fn into_cql_varint(self) -> Option { match self { Self::Varint(i) => Some(i), @@ -1084,6 +1172,7 @@ impl CqlValue { } } + #[inline] pub fn into_cql_decimal(self) -> Option { match self { Self::Decimal(i) => Some(i), diff --git a/scylla/src/client/caching_session.rs b/scylla/src/client/caching_session.rs index f520c73b45..874a009b61 100644 --- a/scylla/src/client/caching_session.rs +++ b/scylla/src/client/caching_session.rs @@ -62,6 +62,7 @@ impl CachingSession where S: Default + BuildHasher + Clone, { + #[inline] pub fn from(session: Session, cache_size: usize) -> Self { Self { session, @@ -77,6 +78,7 @@ where { /// Builds a [`CachingSession`] from a [`Session`], a cache size, /// and a [`BuildHasher`], using a customer hasher. + #[inline] pub fn with_hasher(session: Session, cache_size: usize, hasher: S) -> Self { Self { session, @@ -181,6 +183,7 @@ where } /// Adds a prepared statement to the cache + #[inline] pub async fn add_prepared_statement( &self, query: impl Into<&Statement>, @@ -238,10 +241,12 @@ where } } + #[inline] pub fn get_max_capacity(&self) -> usize { self.max_capacity } + #[inline] pub fn get_session(&self) -> &Session { &self.session } diff --git a/scylla/src/client/execution_profile.rs b/scylla/src/client/execution_profile.rs index 4154815637..3cde453678 100644 --- a/scylla/src/client/execution_profile.rs +++ b/scylla/src/client/execution_profile.rs @@ -200,6 +200,7 @@ pub(crate) mod defaults { } impl Default for ExecutionProfileInner { + #[inline] fn default() -> Self { Self { request_timeout: request_timeout(), @@ -254,6 +255,7 @@ impl ExecutionProfileBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn request_timeout(mut self, timeout: Option) -> Self { self.request_timeout = Some(timeout); self @@ -261,6 +263,7 @@ impl ExecutionProfileBuilder { /// Specify a default consistency to be used for statement executions. /// It's possible to override it by explicitly setting a consistency on the chosen query. + #[inline] pub fn consistency(mut self, consistency: Consistency) -> Self { self.consistency = Some(consistency); self @@ -269,6 +272,7 @@ impl ExecutionProfileBuilder { /// Specify a default serial consistency to be used for statement executions. /// It's possible to override it by explicitly setting a serial consistency /// on the chosen statement. + #[inline] pub fn serial_consistency(mut self, serial_consistency: Option) -> Self { self.serial_consistency = Some(serial_consistency); self @@ -289,6 +293,7 @@ impl ExecutionProfileBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn load_balancing_policy( mut self, load_balancing_policy: Arc, @@ -313,6 +318,7 @@ impl ExecutionProfileBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn retry_policy(mut self, retry_policy: Arc) -> Self { self.retry_policy = Some(retry_policy); self @@ -342,6 +348,7 @@ impl ExecutionProfileBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn speculative_execution_policy( mut self, speculative_execution_policy: Option>, @@ -385,6 +392,7 @@ impl ExecutionProfileBuilder { } impl Default for ExecutionProfileBuilder { + #[inline] fn default() -> Self { ExecutionProfile::builder() } @@ -431,6 +439,7 @@ impl ExecutionProfile { } /// Creates a blank builder that can be used to construct new ExecutionProfile. + #[inline] pub fn builder() -> ExecutionProfileBuilder { ExecutionProfileBuilder { request_timeout: None, @@ -443,11 +452,13 @@ impl ExecutionProfile { } /// Creates a builder having all options set to the same as set in this ExecutionProfile. + #[inline] pub fn to_builder(&self) -> ExecutionProfileBuilder { self.0.to_builder() } /// Returns a new handle to this ExecutionProfile. + #[inline] pub fn into_handle(self) -> ExecutionProfileHandle { ExecutionProfileHandle(Arc::new((ArcSwap::new(self.0), None))) } @@ -456,36 +467,43 @@ impl ExecutionProfile { /// The tag, as its name suggests, is only useful for debugging purposes, while being confused /// about which statement/session is assigned which handle. Identifying handles with tags /// could then help. + #[inline] pub fn into_handle_with_label(self, label: String) -> ExecutionProfileHandle { ExecutionProfileHandle(Arc::new((ArcSwap::new(self.0), Some(label)))) } /// Gets client timeout associated with this profile. + #[inline] pub fn get_request_timeout(&self) -> Option { self.0.request_timeout } /// Gets consistency associated with this profile. + #[inline] pub fn get_consistency(&self) -> Consistency { self.0.consistency } /// Gets serial consistency (if set) associated with this profile. + #[inline] pub fn get_serial_consistency(&self) -> Option { self.0.serial_consistency } /// Gets load balancing policy associated with this profile. + #[inline] pub fn get_load_balancing_policy(&self) -> &Arc { &self.0.load_balancing_policy } /// Gets retry policy associated with this profile. + #[inline] pub fn get_retry_policy(&self) -> &Arc { &self.0.retry_policy } /// Gets speculative execution policy associated with this profile. + #[inline] pub fn get_speculative_execution_policy(&self) -> Option<&Arc> { self.0.speculative_execution_policy.as_ref() } @@ -511,17 +529,20 @@ impl ExecutionProfileHandle { } /// Creates a builder having all options set to the same as set in the ExecutionProfile pointed by this handle. + #[inline] pub fn pointee_to_builder(&self) -> ExecutionProfileBuilder { self.0 .0.load().to_builder() } /// Returns execution profile pointed by this handle. + #[inline] pub fn to_profile(&self) -> ExecutionProfile { ExecutionProfile(self.access()) } /// Makes the handle point to a new execution profile. /// All entities (statements/Session) holding this handle will reflect the change. + #[inline] pub fn map_to_another_profile(&mut self, profile: ExecutionProfile) { self.0 .0.store(profile.0) } diff --git a/scylla/src/client/self_identity.rs b/scylla/src/client/self_identity.rs index 7c33e845f0..2be61d9f97 100644 --- a/scylla/src/client/self_identity.rs +++ b/scylla/src/client/self_identity.rs @@ -44,6 +44,7 @@ pub struct SelfIdentity<'id> { } impl<'id> SelfIdentity<'id> { + #[inline] pub fn new() -> Self { Self::default() } @@ -51,27 +52,32 @@ impl<'id> SelfIdentity<'id> { /// Advertises a custom driver name, which can be used if a custom driver build is running, /// or an entirely different driver is operating on top of Rust driver /// (e.g. cpp-rust-driver). + #[inline] pub fn set_custom_driver_name(&mut self, custom_driver_name: impl Into>) { self.custom_driver_name = Some(custom_driver_name.into()); } /// Advertises a custom driver name. See [Self::set_custom_driver_name] for use cases. + #[inline] pub fn with_custom_driver_name(mut self, custom_driver_name: impl Into>) -> Self { self.custom_driver_name = Some(custom_driver_name.into()); self } /// Custom driver name to be advertised. See [Self::set_custom_driver_name] for use cases. + #[inline] pub fn get_custom_driver_name(&self) -> Option<&str> { self.custom_driver_name.as_deref() } /// Advertises a custom driver version. See [Self::set_custom_driver_name] for use cases. + #[inline] pub fn set_custom_driver_version(&mut self, custom_driver_version: impl Into>) { self.custom_driver_version = Some(custom_driver_version.into()); } /// Advertises a custom driver version. See [Self::set_custom_driver_name] for use cases. + #[inline] pub fn with_custom_driver_version( mut self, custom_driver_version: impl Into>, @@ -81,33 +87,39 @@ impl<'id> SelfIdentity<'id> { } /// Custom driver version to be advertised. See [Self::set_custom_driver_version] for use cases. + #[inline] pub fn get_custom_driver_version(&self) -> Option<&str> { self.custom_driver_version.as_deref() } /// Advertises an application name, which can be used to distinguish different applications /// connected to the same cluster. + #[inline] pub fn set_application_name(&mut self, application_name: impl Into>) { self.application_name = Some(application_name.into()); } /// Advertises an application name. See [Self::set_application_name] for use cases. + #[inline] pub fn with_application_name(mut self, application_name: impl Into>) -> Self { self.application_name = Some(application_name.into()); self } /// Application name to be advertised. See [Self::set_application_name] for use cases. + #[inline] pub fn get_application_name(&self) -> Option<&str> { self.application_name.as_deref() } /// Advertises an application version. See [Self::set_application_name] for use cases. + #[inline] pub fn set_application_version(&mut self, application_version: impl Into>) { self.application_version = Some(application_version.into()); } /// Advertises an application version. See [Self::set_application_name] for use cases. + #[inline] pub fn with_application_version( mut self, application_version: impl Into>, @@ -117,23 +129,27 @@ impl<'id> SelfIdentity<'id> { } /// Application version to be advertised. See [Self::set_application_version] for use cases. + #[inline] pub fn get_application_version(&self) -> Option<&str> { self.application_version.as_deref() } /// Advertises a client ID, which can be set to distinguish different instances /// of the same application connected to the same cluster. + #[inline] pub fn set_client_id(&mut self, client_id: impl Into>) { self.client_id = Some(client_id.into()); } /// Advertises a client ID. See [Self::set_client_id] for use cases. + #[inline] pub fn with_client_id(mut self, client_id: impl Into>) -> Self { self.client_id = Some(client_id.into()); self } /// Client ID to be advertised. See [Self::set_client_id] for use cases. + #[inline] pub fn get_client_id(&self) -> Option<&str> { self.client_id.as_deref() } diff --git a/scylla/src/client/session.rs b/scylla/src/client/session.rs index 44de7862fb..56d609cb2e 100644 --- a/scylla/src/client/session.rs +++ b/scylla/src/client/session.rs @@ -417,6 +417,8 @@ pub(crate) enum RunRequestResult { Completed(ResT), } +/// Represents a CQL session, which can be used to communicate +/// with the database. impl Session { /// Sends a request to the database and receives a response.\ /// Executes an unprepared CQL statement without paging, i.e. all results are received in a single response. @@ -474,6 +476,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn query_unpaged( &self, statement: impl Into, @@ -533,6 +536,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn query_single_page( &self, statement: impl Into, @@ -579,6 +583,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn query_iter( &self, statement: impl Into, @@ -630,6 +635,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn execute_unpaged( &self, prepared: &PreparedStatement, @@ -694,6 +700,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn execute_single_page( &self, prepared: &PreparedStatement, @@ -743,6 +750,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn execute_iter( &self, prepared: impl Into, @@ -796,6 +804,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn batch( &self, batch: &Batch, @@ -803,11 +812,7 @@ impl Session { ) -> Result { self.do_batch(batch, values).await } -} -/// Represents a CQL session, which can be used to communicate -/// with the database -impl Session { /// Estabilishes a CQL session with the database /// /// Usually it's easier to use [SessionBuilder](crate::client::session_builder::SessionBuilder) @@ -1231,6 +1236,7 @@ impl Session { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn prepare( &self, statement: impl Into, @@ -1663,6 +1669,7 @@ impl Session { /// Driver collects various metrics like number of queries or query latencies. /// They can be read using this method #[cfg(feature = "metrics")] + #[inline] pub fn get_metrics(&self) -> Arc { Arc::clone(&self.metrics) } @@ -1671,6 +1678,7 @@ impl Session { /// /// Driver collects various information about network topology or schema. /// It can be read using this method. + #[inline] pub fn get_cluster_state(&self) -> Arc { self.cluster.get_state() } @@ -2110,6 +2118,7 @@ impl Session { /// Retrieves the handle to execution profile that is used by this session /// by default, i.e. when an executed statement does not define its own handle. + #[inline] pub fn get_default_execution_profile_handle(&self) -> &ExecutionProfileHandle { &self.default_execution_profile_handle } diff --git a/scylla/src/client/session_builder.rs b/scylla/src/client/session_builder.rs index ee1371c50f..e66d852ddc 100644 --- a/scylla/src/client/session_builder.rs +++ b/scylla/src/client/session_builder.rs @@ -82,6 +82,7 @@ impl GenericSessionBuilder { /// # Default configuration /// * Compression: None /// + #[inline] pub fn new() -> Self { SessionBuilder { config: SessionConfig::new(), @@ -114,6 +115,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn known_node(mut self, hostname: impl AsRef) -> Self { self.config.add_known_node(hostname); self @@ -133,6 +135,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn known_node_addr(mut self, node_addr: SocketAddr) -> Self { self.config.add_known_node_addr(node_addr); self @@ -151,6 +154,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn known_nodes(mut self, hostnames: impl IntoIterator>) -> Self { self.config.add_known_nodes(hostnames); self @@ -173,6 +177,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn known_nodes_addr( mut self, node_addrs: impl IntoIterator>, @@ -199,6 +204,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn user(mut self, username: impl Into, passwd: impl Into) -> Self { self.config.authenticator = Some(Arc::new(PlainTextAuthenticator::new( username.into(), @@ -252,6 +258,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn authenticator_provider( mut self, authenticator_provider: Arc, @@ -317,6 +324,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn address_translator(mut self, translator: Arc) -> Self { self.config.address_translator = Some(translator); self @@ -351,6 +359,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn tls_context(mut self, tls_context: Option>) -> Self { self.config.tls_context = tls_context.map(|t| t.into()); self @@ -384,6 +393,7 @@ impl CloudSessionBuilder { /// Creates a new SessionBuilder with default configuration, /// based on provided path to Scylla Cloud Config yaml. + #[inline] pub fn new( cloud_config: impl AsRef, tls_provider: CloudTlsProvider, @@ -416,6 +426,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn local_ip_address(mut self, local_ip_address: Option>) -> Self { self.config.local_ip_address = local_ip_address.map(Into::into); self @@ -445,6 +456,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn shard_aware_local_port_range(mut self, port_range: ShardAwarePortRange) -> Self { self.config.shard_aware_local_port_range = port_range; self @@ -468,6 +480,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn compression(mut self, compression: Option) -> Self { self.config.compression = compression; self @@ -490,6 +503,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn schema_agreement_interval(mut self, timeout: Duration) -> Self { self.config.schema_agreement_interval = timeout; self @@ -517,6 +531,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn default_execution_profile_handle( mut self, profile_handle: ExecutionProfileHandle, @@ -541,6 +556,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn tcp_nodelay(mut self, nodelay: bool) -> Self { self.config.tcp_nodelay = nodelay; self @@ -565,6 +581,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn tcp_keepalive_interval(mut self, interval: Duration) -> Self { if interval <= Duration::from_secs(1) { warn!( @@ -595,6 +612,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn use_keyspace(mut self, keyspace_name: impl Into, case_sensitive: bool) -> Self { self.config.used_keyspace = Some(keyspace_name.into()); self.config.keyspace_case_sensitive = case_sensitive; @@ -617,6 +635,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub async fn build(&self) -> Result { Session::connect(self.config.clone()).await } @@ -639,6 +658,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn connection_timeout(mut self, duration: Duration) -> Self { self.config.connect_timeout = duration; self @@ -665,6 +685,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn pool_size(mut self, size: PoolSize) -> Self { self.config.connection_pool_size = size; self @@ -705,6 +726,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn disallow_shard_aware_port(mut self, disallow: bool) -> Self { self.config.disallow_shard_aware_port = disallow; self @@ -727,6 +749,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn timestamp_generator(mut self, timestamp_generator: Arc) -> Self { self.config.timestamp_generator = Some(timestamp_generator); self @@ -748,6 +771,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn keyspaces_to_fetch( mut self, keyspaces: impl IntoIterator>, @@ -772,6 +796,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn fetch_schema_metadata(mut self, fetch: bool) -> Self { self.config.fetch_schema_metadata = fetch; self @@ -797,6 +822,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn metadata_request_serverside_timeout(mut self, timeout: Duration) -> Self { self.config.metadata_request_serverside_timeout = Some(timeout); self @@ -821,6 +847,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn keepalive_interval(mut self, interval: Duration) -> Self { if interval <= Duration::from_secs(1) { warn!( @@ -852,6 +879,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn keepalive_timeout(mut self, timeout: Duration) -> Self { if timeout <= Duration::from_secs(1) { warn!( @@ -880,6 +908,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn schema_agreement_timeout(mut self, timeout: Duration) -> Self { self.config.schema_agreement_timeout = timeout; self @@ -901,6 +930,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn auto_await_schema_agreement(mut self, enabled: bool) -> Self { self.config.schema_agreement_automatic_waiting = enabled; self @@ -935,6 +965,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn host_filter(mut self, filter: Arc) -> Self { self.config.host_filter = Some(filter); self @@ -956,6 +987,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn refresh_metadata_on_auto_schema_agreement(mut self, refresh_metadata: bool) -> Self { self.config.refresh_metadata_on_auto_schema_agreement = refresh_metadata; self @@ -986,6 +1018,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn tracing_info_fetch_attempts(mut self, attempts: NonZeroU32) -> Self { self.config.tracing_info_fetch_attempts = attempts; self @@ -1016,6 +1049,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn tracing_info_fetch_interval(mut self, interval: Duration) -> Self { self.config.tracing_info_fetch_interval = interval; self @@ -1039,6 +1073,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn tracing_info_fetch_consistency(mut self, consistency: Consistency) -> Self { self.config.tracing_info_fetch_consistency = consistency; self @@ -1071,6 +1106,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn write_coalescing(mut self, enable: bool) -> Self { self.config.enable_write_coalescing = enable; self @@ -1096,6 +1132,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn write_coalescing_delay(mut self, delay: WriteCoalescingDelay) -> Self { self.config.write_coalescing_delay = delay; self @@ -1121,6 +1158,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn cluster_metadata_refresh_interval(mut self, interval: Duration) -> Self { self.config.cluster_metadata_refresh_interval = interval; self @@ -1154,6 +1192,7 @@ impl GenericSessionBuilder { /// # Ok(()) /// # } /// ``` + #[inline] pub fn custom_identity(mut self, identity: SelfIdentity<'static>) -> Self { self.config.identity = identity; self @@ -1162,6 +1201,7 @@ impl GenericSessionBuilder { /// Creates a [`SessionBuilder`] with default configuration, same as [`SessionBuilder::new`] impl Default for SessionBuilder { + #[inline] fn default() -> Self { SessionBuilder::new() } diff --git a/scylla/src/cluster/node.rs b/scylla/src/cluster/node.rs index e4e9332ae3..c1a5a69ab6 100644 --- a/scylla/src/cluster/node.rs +++ b/scylla/src/cluster/node.rs @@ -53,15 +53,18 @@ impl NodeAddr { NodeAddr::Translatable(addr) | NodeAddr::Untranslatable(addr) => addr, } } + #[inline] pub fn ip(&self) -> IpAddr { self.into_inner().ip() } + #[inline] pub fn port(&self) -> u16 { self.into_inner().port() } } impl Display for NodeAddr { + #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.into_inner()) } @@ -148,6 +151,7 @@ impl Node { } } + #[inline] pub fn sharder(&self) -> Option { self.pool.as_ref()?.sharder() } @@ -173,6 +177,7 @@ impl Node { /// Returns true if the driver has any open connections in the pool for this /// node. + #[inline] pub fn is_connected(&self) -> bool { let Ok(pool) = self.get_pool() else { return false; @@ -183,6 +188,7 @@ impl Node { /// Returns a boolean which indicates whether this node was is enabled. /// Only enabled nodes will have connections open. For disabled nodes, /// no connections will be opened. + #[inline] pub fn is_enabled(&self) -> bool { self.pool.is_some() } diff --git a/scylla/src/cluster/state.rs b/scylla/src/cluster/state.rs index 9796d4b33b..6ef37411ca 100644 --- a/scylla/src/cluster/state.rs +++ b/scylla/src/cluster/state.rs @@ -217,16 +217,19 @@ impl ClusterState { } /// Access keyspace details collected by the driver. + #[inline] pub fn get_keyspace(&self, keyspace: impl AsRef) -> Option<&Keyspace> { self.keyspaces.get(keyspace.as_ref()) } /// Returns an iterator over keyspaces. + #[inline] pub fn keyspaces_iter(&self) -> impl Iterator { self.keyspaces.iter().map(|(k, v)| (k.as_str(), v)) } /// Access details about nodes known to the driver + #[inline] pub fn get_nodes_info(&self) -> &[Arc] { &self.all_nodes } @@ -268,6 +271,7 @@ impl ClusterState { } /// Access to replicas owning a given token + #[inline] pub fn get_token_endpoints( &self, keyspace: &str, @@ -303,6 +307,7 @@ impl ClusterState { /// or named values (e.g. struct that derives `SerializeRow`), as you would /// when executing a request. No additional values are allowed besides values /// for primary key columns. + #[inline] pub fn get_endpoints( &self, keyspace: &str, @@ -314,6 +319,7 @@ impl ClusterState { } /// Access replica location info + #[inline] pub fn replica_locator(&self) -> &ReplicaLocator { &self.locator } diff --git a/scylla/src/observability/metrics.rs b/scylla/src/observability/metrics.rs index a0ad5d01dd..d7da287d9d 100644 --- a/scylla/src/observability/metrics.rs +++ b/scylla/src/observability/metrics.rs @@ -307,6 +307,7 @@ impl Metrics { } /// Returns average latency in milliseconds + #[inline] pub fn get_latency_avg_ms(&self) -> Result { Self::mean(&self.histogram.load()) } @@ -363,61 +364,73 @@ impl Metrics { } /// Returns counter for errors occurred in nonpaged queries + #[inline] pub fn get_errors_num(&self) -> u64 { self.errors_num.load(ORDER_TYPE) } /// Returns counter for nonpaged queries + #[inline] pub fn get_queries_num(&self) -> u64 { self.queries_num.load(ORDER_TYPE) } /// Returns counter for errors occurred in paged queries + #[inline] pub fn get_errors_iter_num(&self) -> u64 { self.errors_iter_num.load(ORDER_TYPE) } /// Returns counter for pages requested in paged queries + #[inline] pub fn get_queries_iter_num(&self) -> u64 { self.queries_iter_num.load(ORDER_TYPE) } /// Returns counter measuring how many times a retry policy has decided to retry a query + #[inline] pub fn get_retries_num(&self) -> u64 { self.retries_num.load(ORDER_TYPE) } /// Returns mean rate of queries per second + #[inline] pub fn get_mean_rate(&self) -> f64 { self.meter.mean_rate() } /// Returns one-minute rate of queries per second + #[inline] pub fn get_one_minute_rate(&self) -> f64 { self.meter.one_minute_rate() } /// Returns five-minute rate of queries per second + #[inline] pub fn get_five_minute_rate(&self) -> f64 { self.meter.five_minute_rate() } /// Returns fifteen-minute rate of queries per second + #[inline] pub fn get_fifteen_minute_rate(&self) -> f64 { self.meter.fifteen_minute_rate() } /// Returns total number of active connections + #[inline] pub fn get_total_connections(&self) -> u64 { self.total_connections.load(ORDER_TYPE) } /// Returns counter for connection timeouts + #[inline] pub fn get_connection_timeouts(&self) -> u64 { self.connection_timeouts.load(ORDER_TYPE) } /// Returns counter for request timeouts + #[inline] pub fn get_request_timeouts(&self) -> u64 { self.request_timeouts.load(ORDER_TYPE) } @@ -509,6 +522,7 @@ impl Metrics { #[cfg(test)] impl Default for Metrics { + #[inline] fn default() -> Self { Self::new() } diff --git a/scylla/src/policies/host_filter.rs b/scylla/src/policies/host_filter.rs index c271bdf490..09df09afb6 100644 --- a/scylla/src/policies/host_filter.rs +++ b/scylla/src/policies/host_filter.rs @@ -21,6 +21,7 @@ pub trait HostFilter: Send + Sync { pub struct AcceptAllHostFilter; impl HostFilter for AcceptAllHostFilter { + #[inline] fn accept(&self, _peer: &Peer) -> bool { true } @@ -53,6 +54,7 @@ impl AllowListHostFilter { } impl HostFilter for AllowListHostFilter { + #[inline] fn accept(&self, peer: &Peer) -> bool { match peer.address { crate::cluster::NodeAddr::Translatable(addr) => self.allowed.contains(&addr), @@ -72,12 +74,14 @@ pub struct DcHostFilter { impl DcHostFilter { /// Creates a new `DcHostFilter` that accepts nodes only from the /// `local_dc`. + #[inline] pub fn new(local_dc: String) -> Self { Self { local_dc } } } impl HostFilter for DcHostFilter { + #[inline] fn accept(&self, peer: &Peer) -> bool { peer.datacenter.as_ref() == Some(&self.local_dc) } diff --git a/scylla/src/policies/retry/default.rs b/scylla/src/policies/retry/default.rs index bc3be2b716..5f5895b8c1 100644 --- a/scylla/src/policies/retry/default.rs +++ b/scylla/src/policies/retry/default.rs @@ -10,18 +10,21 @@ use super::{RequestInfo, RetryDecision, RetryPolicy, RetrySession}; pub struct DefaultRetryPolicy; impl DefaultRetryPolicy { + #[inline] pub fn new() -> DefaultRetryPolicy { DefaultRetryPolicy } } impl Default for DefaultRetryPolicy { + #[inline] fn default() -> DefaultRetryPolicy { DefaultRetryPolicy::new() } } impl RetryPolicy for DefaultRetryPolicy { + #[inline] fn new_session(&self) -> Box { Box::new(DefaultRetrySession::new()) } @@ -34,6 +37,7 @@ pub struct DefaultRetrySession { } impl DefaultRetrySession { + #[inline] pub fn new() -> DefaultRetrySession { DefaultRetrySession { was_unavailable_retry: false, @@ -44,6 +48,7 @@ impl DefaultRetrySession { } impl Default for DefaultRetrySession { + #[inline] fn default() -> DefaultRetrySession { DefaultRetrySession::new() } @@ -128,6 +133,7 @@ impl RetrySession for DefaultRetrySession { } } + #[inline] fn reset(&mut self) { *self = DefaultRetrySession::new(); } diff --git a/scylla/src/policies/retry/downgrading_consistency.rs b/scylla/src/policies/retry/downgrading_consistency.rs index d39c65dfcd..b430e3f0f1 100644 --- a/scylla/src/policies/retry/downgrading_consistency.rs +++ b/scylla/src/policies/retry/downgrading_consistency.rs @@ -13,18 +13,21 @@ use crate::errors::{DbError, RequestAttemptError, WriteType}; pub struct DowngradingConsistencyRetryPolicy; impl DowngradingConsistencyRetryPolicy { + #[inline] pub fn new() -> DowngradingConsistencyRetryPolicy { DowngradingConsistencyRetryPolicy } } impl Default for DowngradingConsistencyRetryPolicy { + #[inline] fn default() -> DowngradingConsistencyRetryPolicy { DowngradingConsistencyRetryPolicy::new() } } impl RetryPolicy for DowngradingConsistencyRetryPolicy { + #[inline] fn new_session(&self) -> Box { Box::new(DowngradingConsistencyRetrySession::new()) } @@ -35,12 +38,14 @@ pub struct DowngradingConsistencyRetrySession { } impl DowngradingConsistencyRetrySession { + #[inline] pub fn new() -> DowngradingConsistencyRetrySession { DowngradingConsistencyRetrySession { was_retry: false } } } impl Default for DowngradingConsistencyRetrySession { + #[inline] fn default() -> DowngradingConsistencyRetrySession { DowngradingConsistencyRetrySession::new() } @@ -170,6 +175,7 @@ impl RetrySession for DowngradingConsistencyRetrySession { } } + #[inline] fn reset(&mut self) { *self = DowngradingConsistencyRetrySession::new(); } diff --git a/scylla/src/policies/retry/fallthrough.rs b/scylla/src/policies/retry/fallthrough.rs index 6a9600026e..fb50ad263e 100644 --- a/scylla/src/policies/retry/fallthrough.rs +++ b/scylla/src/policies/retry/fallthrough.rs @@ -6,27 +6,32 @@ pub struct FallthroughRetryPolicy; pub struct FallthroughRetrySession; impl FallthroughRetryPolicy { + #[inline] pub fn new() -> FallthroughRetryPolicy { FallthroughRetryPolicy } } impl Default for FallthroughRetryPolicy { + #[inline] fn default() -> FallthroughRetryPolicy { FallthroughRetryPolicy } } impl RetryPolicy for FallthroughRetryPolicy { + #[inline] fn new_session(&self) -> Box { Box::new(FallthroughRetrySession) } } impl RetrySession for FallthroughRetrySession { + #[inline] fn decide_should_retry(&mut self, _query_info: RequestInfo) -> RetryDecision { RetryDecision::DontRetry } + #[inline] fn reset(&mut self) {} } diff --git a/scylla/src/policies/speculative_execution.rs b/scylla/src/policies/speculative_execution.rs index 91e2293252..a70062d2fc 100644 --- a/scylla/src/policies/speculative_execution.rs +++ b/scylla/src/policies/speculative_execution.rs @@ -56,10 +56,12 @@ pub struct PercentileSpeculativeExecutionPolicy { } impl SpeculativeExecutionPolicy for SimpleSpeculativeExecutionPolicy { + #[inline] fn max_retry_count(&self, _: &Context) -> usize { self.max_retry_count } + #[inline] fn retry_interval(&self, _: &Context) -> Duration { self.retry_interval } @@ -67,6 +69,7 @@ impl SpeculativeExecutionPolicy for SimpleSpeculativeExecutionPolicy { #[cfg(feature = "metrics")] impl SpeculativeExecutionPolicy for PercentileSpeculativeExecutionPolicy { + #[inline] fn max_retry_count(&self, _: &Context) -> usize { self.max_retry_count } diff --git a/scylla/src/policies/timestamp_generator.rs b/scylla/src/policies/timestamp_generator.rs index b35f3ad1be..43c4856894 100644 --- a/scylla/src/policies/timestamp_generator.rs +++ b/scylla/src/policies/timestamp_generator.rs @@ -20,12 +20,14 @@ pub trait TimestampGenerator: Send + Sync { pub struct SimpleTimestampGenerator {} impl SimpleTimestampGenerator { + #[inline] pub fn new() -> Self { SimpleTimestampGenerator {} } } impl TimestampGenerator for SimpleTimestampGenerator { + #[inline] fn next_timestamp(&self) -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) @@ -55,6 +57,7 @@ pub struct MonotonicTimestampGenerator { impl MonotonicTimestampGenerator { /// Creates a new monotonic timestamp generator with default settings + #[inline] pub fn new() -> Self { MonotonicTimestampGenerator { last: AtomicI64::new(0), @@ -66,6 +69,7 @@ impl MonotonicTimestampGenerator { } } + #[inline] pub fn with_warning_times( mut self, warning_threshold: Duration, @@ -78,6 +82,7 @@ impl MonotonicTimestampGenerator { self } + #[inline] pub fn without_warnings(mut self) -> Self { self.config = None; self @@ -125,6 +130,7 @@ impl MonotonicTimestampGenerator { } impl Default for MonotonicTimestampGenerator { + #[inline] fn default() -> Self { Self::new() } diff --git a/scylla/src/routing/locator/mod.rs b/scylla/src/routing/locator/mod.rs index 6c820e37cf..b3aaa8543b 100644 --- a/scylla/src/routing/locator/mod.rs +++ b/scylla/src/routing/locator/mod.rs @@ -179,22 +179,26 @@ impl ReplicaLocator { } /// Gives access to the token ring, based on which all token ranges/replica sets are computed. + #[inline] pub fn ring(&self) -> &TokenRing> { self.replication_data.get_global_ring() } /// Gives a list of all nodes in the token ring. + #[inline] pub fn unique_nodes_in_global_ring(&self) -> &[Arc] { self.replication_data.unique_nodes_in_global_ring() } /// Gives a list of all known datacenters. + #[inline] pub fn datacenter_names(&self) -> &[String] { self.datacenters.as_slice() } /// Gives a list of all nodes in a specified datacenter ring (which is created by filtering the /// original ring to only contain nodes living in the specified datacenter). + #[inline] pub fn unique_nodes_in_datacenter_ring<'a>( &'a self, datacenter_name: &str, @@ -354,6 +358,7 @@ impl<'a> ReplicaSet<'a> { /// Returns `true` if the replica set contains no elements. /// /// Complexity same as of `ReplicaSet::len`. + #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } @@ -630,6 +635,7 @@ impl<'a> Iterator for ReplicaSetIterator<'a> { } impl<'a> ReplicaSet<'a> { + #[inline] pub fn into_replicas_ordered(self) -> ReplicasOrdered<'a> { ReplicasOrdered { replica_set: self } } diff --git a/scylla/src/routing/locator/token_ring.rs b/scylla/src/routing/locator/token_ring.rs index b78a0d8084..a9e8e4be41 100644 --- a/scylla/src/routing/locator/token_ring.rs +++ b/scylla/src/routing/locator/token_ring.rs @@ -24,6 +24,7 @@ impl TokenRing { } /// Iterates over all members of the ring starting at the lowest token. + #[inline] pub fn iter(&self) -> impl Iterator { self.ring.iter() } @@ -49,21 +50,25 @@ impl TokenRing { /// After reaching the maximum token it wraps around and continues from the lowest one. /// The iterator visits each member once, it doesn't have an infinite length. /// To access the token along with the element you can use `ring_range_full`. + #[inline] pub fn ring_range(&self, token: Token) -> impl Iterator { self.ring_range_full(token).map(|(_t, e)| e) } /// Traverses the ring starting at the given token and returns the first ring member encountered. + #[inline] pub fn get_elem_for_token(&self, token: Token) -> Option<&ElemT> { self.ring_range(token).next() } /// Get the total number of members in the ring. + #[inline] pub fn len(&self) -> usize { self.ring.len() } /// Returns `true` if the token ring contains no elements. + #[inline] pub fn is_empty(&self) -> bool { self.ring.is_empty() } diff --git a/scylla/src/routing/sharding.rs b/scylla/src/routing/sharding.rs index 2d75a30962..e668858ea7 100644 --- a/scylla/src/routing/sharding.rs +++ b/scylla/src/routing/sharding.rs @@ -35,6 +35,7 @@ impl ShardAwarePortRange { } impl Default for ShardAwarePortRange { + #[inline] fn default() -> Self { Self::EPHEMERAL_PORT_RANGE } @@ -63,6 +64,7 @@ pub struct Sharder { impl std::str::FromStr for Token { type Err = std::num::ParseIntError; + #[inline] fn from_str(s: &str) -> Result { Ok(Token { value: s.parse()? }) } @@ -83,6 +85,7 @@ impl ShardInfo { } impl Sharder { + #[inline] pub fn new(nr_shards: ShardCount, msb_ignore: u8) -> Self { Sharder { nr_shards, @@ -90,6 +93,7 @@ impl Sharder { } } + #[inline] pub fn shard_of(&self, token: Token) -> Shard { let mut biased_token = (token.value as u64).wrapping_add(1u64 << 63); biased_token <<= self.msb_ignore; @@ -98,6 +102,7 @@ impl Sharder { /// If we connect to Scylla using Scylla's shard aware port, then Scylla assigns a shard to the /// connection based on the source port. This calculates the assigned shard. + #[inline] pub fn shard_of_source_port(&self, source_port: u16) -> Shard { (source_port % self.nr_shards.get()) as Shard } @@ -105,6 +110,7 @@ impl Sharder { /// Randomly choose a source port `p` such that `shard == shard_of_source_port(p)`. /// /// The port is chosen from ephemeral port range [49152, 65535]. + #[inline] pub fn draw_source_port_for_shard(&self, shard: Shard) -> u16 { self.draw_source_port_for_shard_from_range( shard, @@ -134,6 +140,7 @@ impl Sharder { /// Stops once all possible ports have been returned /// /// The ports are chosen from ephemeral port range [49152, 65535]. + #[inline] pub fn iter_source_ports_for_shard(&self, shard: Shard) -> impl Iterator { self.iter_source_ports_for_shard_from_range( shard, diff --git a/scylla/src/statement/batch.rs b/scylla/src/statement/batch.rs index 0dd7030c0e..d63c203cf9 100644 --- a/scylla/src/statement/batch.rs +++ b/scylla/src/statement/batch.rs @@ -24,6 +24,7 @@ pub struct Batch { impl Batch { /// Creates a new, empty `Batch` of `batch_type` type. + #[inline] pub fn new(batch_type: BatchType) -> Self { Self { batch_type, @@ -43,6 +44,7 @@ impl Batch { } /// Creates a new, empty `Batch` of `batch_type` type with the provided statements. + #[inline] pub fn new_with_statements(batch_type: BatchType, statements: Vec) -> Self { Self { batch_type, @@ -52,34 +54,40 @@ impl Batch { } /// Appends a new statement to the batch. + #[inline] pub fn append_statement(&mut self, statement: impl Into) { self.statements.push(statement.into()); } /// Gets type of batch. + #[inline] pub fn get_type(&self) -> BatchType { self.batch_type } /// Sets the consistency to be used when executing this batch. + #[inline] pub fn set_consistency(&mut self, c: Consistency) { self.config.consistency = Some(c); } /// Gets the consistency to be used when executing this batch if it is filled. /// If this is empty, the default_consistency of the session will be used. + #[inline] pub fn get_consistency(&self) -> Option { self.config.consistency } /// Sets the serial consistency to be used when executing this batch. /// (Ignored unless the batch is an LWT) + #[inline] pub fn set_serial_consistency(&mut self, sc: Option) { self.config.serial_consistency = Some(sc); } /// Gets the serial consistency to be used when executing this batch. /// (Ignored unless the batch is an LWT) + #[inline] pub fn get_serial_consistency(&self) -> Option { self.config.serial_consistency.flatten() } @@ -89,11 +97,13 @@ impl Batch { /// If set to `true` we can be sure that it is idempotent /// If set to `false` it is unknown whether it is idempotent /// This is used in [`RetryPolicy`] to decide if retrying a query is safe + #[inline] pub fn set_is_idempotent(&mut self, is_idempotent: bool) { self.config.is_idempotent = is_idempotent; } /// Gets the idempotence of this batch + #[inline] pub fn get_is_idempotent(&self) -> bool { self.config.is_idempotent } @@ -101,11 +111,13 @@ impl Batch { /// Enable or disable CQL Tracing for this batch /// If enabled session.batch() will return a QueryResult containing tracing_id /// which can be used to query tracing information about the execution of this query + #[inline] pub fn set_tracing(&mut self, should_trace: bool) { self.config.tracing = should_trace; } /// Gets whether tracing is enabled for this batch + #[inline] pub fn get_tracing(&self) -> bool { self.config.tracing } @@ -113,11 +125,13 @@ impl Batch { /// Sets the default timestamp for this batch in microseconds. /// If not None, it will replace the server side assigned timestamp as default timestamp for /// all the statements contained in the batch. + #[inline] pub fn set_timestamp(&mut self, timestamp: Option) { self.config.timestamp = timestamp } /// Gets the default timestamp for this batch in microseconds. + #[inline] pub fn get_timestamp(&self) -> Option { self.config.timestamp } @@ -135,28 +149,33 @@ impl Batch { } /// Sets the listener capable of listening what happens during query execution. + #[inline] pub fn set_history_listener(&mut self, history_listener: Arc) { self.config.history_listener = Some(history_listener); } /// Removes the listener set by `set_history_listener`. + #[inline] pub fn remove_history_listener(&mut self) -> Option> { self.config.history_listener.take() } /// Associates the batch with execution profile referred by the provided handle. /// Handle may be later remapped to another profile, and batch will reflect those changes. + #[inline] pub fn set_execution_profile_handle(&mut self, profile_handle: Option) { self.config.execution_profile_handle = profile_handle; } /// Borrows the execution profile handle associated with this batch. + #[inline] pub fn get_execution_profile_handle(&self) -> Option<&ExecutionProfileHandle> { self.config.execution_profile_handle.as_ref() } } impl Default for Batch { + #[inline] fn default() -> Self { Self { statements: Vec::new(), @@ -175,18 +194,21 @@ pub enum BatchStatement { } impl From<&str> for BatchStatement { + #[inline] fn from(s: &str) -> Self { BatchStatement::Query(Statement::from(s)) } } impl From for BatchStatement { + #[inline] fn from(q: Statement) -> Self { BatchStatement::Query(q) } } impl From for BatchStatement { + #[inline] fn from(p: PreparedStatement) -> Self { BatchStatement::PreparedStatement(p) } @@ -195,6 +217,7 @@ impl From for BatchStatement { impl<'a: 'b, 'b> From<&'a BatchStatement> for scylla_cql::frame::request::batch::BatchStatement<'b> { + #[inline] fn from(val: &'a BatchStatement) -> Self { match val { BatchStatement::Query(query) => { @@ -293,6 +316,7 @@ pub(crate) mod batch_values { where Self: 'r; + #[inline] fn batch_values_iter(&self) -> Self::BatchValuesIter<'_> { BatchValuesFirstSerializedIterator { first: self.first.as_ref(), diff --git a/scylla/src/statement/prepared.rs b/scylla/src/statement/prepared.rs index f52abe805b..54e2728ce9 100644 --- a/scylla/src/statement/prepared.rs +++ b/scylla/src/statement/prepared.rs @@ -146,10 +146,17 @@ impl PreparedStatement { } } + /// Returns the prepared ID of the statement. + /// + /// In the current implementation of the CQL protocol (CQLv4), this is a hash + /// of the statement string. This may change in newer versions of the protocol. + #[inline] pub fn get_id(&self) -> &Bytes { &self.id } + /// Returns the CQL statement string, i.e., the one that was prepared. + #[inline] pub fn get_statement(&self) -> &str { &self.shared.statement } @@ -157,6 +164,7 @@ impl PreparedStatement { /// Sets the page size for this CQL query. /// /// Panics if given number is nonpositive. + #[inline] pub fn set_page_size(&mut self, page_size: i32) { self.page_size = page_size .try_into() @@ -169,11 +177,13 @@ impl PreparedStatement { } /// Returns the page size for this CQL query. + #[inline] pub fn get_page_size(&self) -> i32 { self.page_size.inner() } /// Gets tracing ids of queries used to prepare this statement + #[inline] pub fn get_prepare_tracing_ids(&self) -> &[Uuid] { &self.prepare_tracing_ids } @@ -181,6 +191,7 @@ impl PreparedStatement { /// Returns true if the prepared statement has necessary information /// to be routed in a token-aware manner. If false, the query /// will always be sent to a random node/shard. + #[inline] pub fn is_token_aware(&self) -> bool { !self.get_prepared_metadata().pk_indexes.is_empty() } @@ -192,6 +203,7 @@ impl PreparedStatement { /// then C, etc.). If false, the query should be routed normally. /// Note: this a Scylla-specific optimisation. Therefore, the result /// will be always false for Cassandra. + #[inline] pub fn is_confirmed_lwt(&self) -> bool { self.is_confirmed_lwt } @@ -251,6 +263,7 @@ impl PreparedStatement { // As this function creates a `PartitionKey`, it is intended rather for external usage (by users). // For internal purposes, `PartitionKey::calculate_token()` is preferred, as `PartitionKey` // is either way used internally, among others for display in traces. + #[inline] pub fn calculate_token( &self, values: &impl SerializeRow, @@ -269,6 +282,7 @@ impl PreparedStatement { } /// Return keyspace name and table name this statement is operating on. + #[inline] pub fn get_table_spec(&self) -> Option<&TableSpec> { self.get_prepared_metadata() .col_specs @@ -277,6 +291,7 @@ impl PreparedStatement { } /// Returns the name of the keyspace this statement is operating on. + #[inline] pub fn get_keyspace_name(&self) -> Option<&str> { self.get_prepared_metadata() .col_specs @@ -285,6 +300,7 @@ impl PreparedStatement { } /// Returns the name of the table this statement is operating on. + #[inline] pub fn get_table_name(&self) -> Option<&str> { self.get_prepared_metadata() .col_specs @@ -293,24 +309,28 @@ impl PreparedStatement { } /// Sets the consistency to be used when executing this statement. + #[inline] pub fn set_consistency(&mut self, c: Consistency) { self.config.consistency = Some(c); } /// Gets the consistency to be used when executing this prepared statement if it is filled. /// If this is empty, the default_consistency of the session will be used. + #[inline] pub fn get_consistency(&self) -> Option { self.config.consistency } /// Sets the serial consistency to be used when executing this statement. /// (Ignored unless the statement is an LWT) + #[inline] pub fn set_serial_consistency(&mut self, sc: Option) { self.config.serial_consistency = Some(sc); } /// Gets the serial consistency to be used when executing this statement. /// (Ignored unless the statement is an LWT) + #[inline] pub fn get_serial_consistency(&self) -> Option { self.config.serial_consistency.flatten() } @@ -320,11 +340,13 @@ impl PreparedStatement { /// If set to `true` we can be sure that it is idempotent /// If set to `false` it is unknown whether it is idempotent /// This is used in [`RetryPolicy`] to decide if retrying a query is safe + #[inline] pub fn set_is_idempotent(&mut self, is_idempotent: bool) { self.config.is_idempotent = is_idempotent; } /// Gets the idempotence of this statement + #[inline] pub fn get_is_idempotent(&self) -> bool { self.config.is_idempotent } @@ -332,11 +354,13 @@ impl PreparedStatement { /// Enable or disable CQL Tracing for this statement /// If enabled session.execute() will return a QueryResult containing tracing_id /// which can be used to query tracing information about the execution of this query + #[inline] pub fn set_tracing(&mut self, should_trace: bool) { self.config.tracing = should_trace; } /// Gets whether tracing is enabled for this statement + #[inline] pub fn get_tracing(&self) -> bool { self.config.tracing } @@ -352,12 +376,14 @@ impl PreparedStatement { /// to deserialize the results of statement execution. /// /// This option is false by default. + #[inline] pub fn set_use_cached_result_metadata(&mut self, use_cached_metadata: bool) { self.config.skip_result_metadata = use_cached_metadata; } /// Gets the information whether the driver uses cached metadata /// to decode the results of the statement's execution. + #[inline] pub fn get_use_cached_result_metadata(&self) -> bool { self.config.skip_result_metadata } @@ -366,11 +392,13 @@ impl PreparedStatement { /// If not None, it will replace the server side assigned timestamp as default timestamp /// If a statement contains a `USING TIMESTAMP` clause, calling this method won't change /// anything + #[inline] pub fn set_timestamp(&mut self, timestamp: Option) { self.config.timestamp = timestamp } /// Gets the default timestamp for this statement in microseconds. + #[inline] pub fn get_timestamp(&self) -> Option { self.config.timestamp } @@ -379,11 +407,13 @@ impl PreparedStatement { /// If not None, the driver will stop waiting for the request /// to finish after `timeout` passed. /// Otherwise, default session client timeout will be applied. + #[inline] pub fn set_request_timeout(&mut self, timeout: Option) { self.config.request_timeout = timeout } /// Gets client timeout associated with this query + #[inline] pub fn get_request_timeout(&self) -> Option { self.config.request_timeout } @@ -399,11 +429,13 @@ impl PreparedStatement { } /// Access column specifications of the bind variables of this statement + #[inline] pub fn get_variable_col_specs(&self) -> ColumnSpecs<'_, 'static> { ColumnSpecs::new(&self.shared.metadata.col_specs) } /// Access info about partition key indexes of the bind variables of this statement + #[inline] pub fn get_variable_pk_indexes(&self) -> &[PartitionKeyIndex] { &self.shared.metadata.pk_indexes } @@ -414,11 +446,13 @@ impl PreparedStatement { } /// Access column specifications of the result set returned after the execution of this statement + #[inline] pub fn get_result_set_col_specs(&self) -> ColumnSpecs<'_, 'static> { ColumnSpecs::new(self.shared.result_metadata.col_specs()) } /// Get the name of the partitioner used for this statement. + #[inline] pub fn get_partitioner_name(&self) -> &PartitionerName { &self.partitioner_name } @@ -436,22 +470,26 @@ impl PreparedStatement { } /// Sets the listener capable of listening what happens during query execution. + #[inline] pub fn set_history_listener(&mut self, history_listener: Arc) { self.config.history_listener = Some(history_listener); } /// Removes the listener set by `set_history_listener`. + #[inline] pub fn remove_history_listener(&mut self) -> Option> { self.config.history_listener.take() } /// Associates the query with execution profile referred by the provided handle. /// Handle may be later remapped to another profile, and query will reflect those changes. + #[inline] pub fn set_execution_profile_handle(&mut self, profile_handle: Option) { self.config.execution_profile_handle = profile_handle; } /// Borrows the execution profile handle associated with this query. + #[inline] pub fn get_execution_profile_handle(&self) -> Option<&ExecutionProfileHandle> { self.config.execution_profile_handle.as_ref() } diff --git a/scylla/src/statement/unprepared.rs b/scylla/src/statement/unprepared.rs index 4c41cf8eec..12ce25fa41 100644 --- a/scylla/src/statement/unprepared.rs +++ b/scylla/src/statement/unprepared.rs @@ -19,6 +19,7 @@ pub struct Statement { impl Statement { /// Creates a new [`Statement`] from a CQL statement string. + #[inline] pub fn new(query_text: impl Into) -> Self { Self { contents: query_text.into(), @@ -30,6 +31,7 @@ impl Statement { /// Returns self with page size set to the given value. /// /// Panics if given number is nonpositive. + #[inline] pub fn with_page_size(mut self, page_size: i32) -> Self { self.set_page_size(page_size); self @@ -38,6 +40,7 @@ impl Statement { /// Sets the page size for this CQL statement. /// /// Panics if given number is nonpositive. + #[inline] pub fn set_page_size(&mut self, page_size: i32) { self.page_size = page_size .try_into() @@ -50,29 +53,34 @@ impl Statement { } /// Returns the page size for this CQL statement. + #[inline] pub fn get_page_size(&self) -> i32 { self.page_size.inner() } /// Sets the consistency to be used when executing this statement. + #[inline] pub fn set_consistency(&mut self, c: Consistency) { self.config.consistency = Some(c); } /// Gets the consistency to be used when executing this statement if it is filled. /// If this is empty, the default_consistency of the session will be used. + #[inline] pub fn get_consistency(&self) -> Option { self.config.consistency } /// Sets the serial consistency to be used when executing this statement. /// (Ignored unless the statement is an LWT) + #[inline] pub fn set_serial_consistency(&mut self, sc: Option) { self.config.serial_consistency = Some(sc); } /// Gets the serial consistency to be used when executing this statement. /// (Ignored unless the statement is an LWT) + #[inline] pub fn get_serial_consistency(&self) -> Option { self.config.serial_consistency.flatten() } @@ -82,11 +90,13 @@ impl Statement { /// If set to `true` we can be sure that it is idempotent /// If set to `false` it is unknown whether it is idempotent /// This is used in [`RetryPolicy`] to decide if retrying a statement execution is safe + #[inline] pub fn set_is_idempotent(&mut self, is_idempotent: bool) { self.config.is_idempotent = is_idempotent; } /// Gets the idempotence of this statement + #[inline] pub fn get_is_idempotent(&self) -> bool { self.config.is_idempotent } @@ -94,11 +104,13 @@ impl Statement { /// Enable or disable CQL Tracing for this statement /// If enabled session.query() will return a QueryResult containing tracing_id /// which can be used to query tracing information about the execution of this query + #[inline] pub fn set_tracing(&mut self, should_trace: bool) { self.config.tracing = should_trace; } /// Gets whether tracing is enabled for this statement + #[inline] pub fn get_tracing(&self) -> bool { self.config.tracing } @@ -107,11 +119,13 @@ impl Statement { /// If not None, it will replace the server side assigned timestamp as default timestamp /// If a statement contains a `USING TIMESTAMP` clause, calling this method won't change /// anything + #[inline] pub fn set_timestamp(&mut self, timestamp: Option) { self.config.timestamp = timestamp } /// Gets the default timestamp for this statement in microseconds. + #[inline] pub fn get_timestamp(&self) -> Option { self.config.timestamp } @@ -120,11 +134,13 @@ impl Statement { /// If not None, the driver will stop waiting for the request /// to finish after `timeout` passed. /// Otherwise, default session client timeout will be applied. + #[inline] pub fn set_request_timeout(&mut self, timeout: Option) { self.config.request_timeout = timeout } /// Gets client timeout associated with this statement. + #[inline] pub fn get_request_timeout(&self) -> Option { self.config.request_timeout } @@ -142,34 +158,40 @@ impl Statement { } /// Sets the listener capable of listening what happens during statement execution. + #[inline] pub fn set_history_listener(&mut self, history_listener: Arc) { self.config.history_listener = Some(history_listener); } /// Removes the listener set by `set_history_listener`. + #[inline] pub fn remove_history_listener(&mut self) -> Option> { self.config.history_listener.take() } /// Associates the query with execution profile referred by the provided handle. /// Handle may be later remapped to another profile, and query will reflect those changes. + #[inline] pub fn set_execution_profile_handle(&mut self, profile_handle: Option) { self.config.execution_profile_handle = profile_handle; } /// Borrows the execution profile handle associated with this statement. + #[inline] pub fn get_execution_profile_handle(&self) -> Option<&ExecutionProfileHandle> { self.config.execution_profile_handle.as_ref() } } impl From for Statement { + #[inline] fn from(s: String) -> Statement { Statement::new(s) } } impl<'a> From<&'a str> for Statement { + #[inline] fn from(s: &'a str) -> Statement { Statement::new(s.to_owned()) }