From fa65c81b2614b091869e1b9095182e2df4612f8f Mon Sep 17 00:00:00 2001 From: Robin Freyler Date: Tue, 6 Feb 2024 14:37:35 +0100 Subject: [PATCH] modernize Rust formatting (#59) --- .rustfmt.toml | 70 ++------------------------------- benches/setup.rs | 21 ++++------ src/backend/bucket/fixed_str.rs | 6 +-- src/backend/bucket/mod.rs | 18 ++------- src/backend/buffer.rs | 38 ++++++------------ src/backend/simple.rs | 12 +----- src/backend/string.rs | 19 +++------ src/compat.rs | 5 +-- src/interner.rs | 21 ++-------- src/lib.rs | 5 +-- src/serde_impl.rs | 32 +++------------ src/symbol.rs | 6 +-- tests/allocator.rs | 16 ++------ tests/tests.rs | 7 +--- 14 files changed, 53 insertions(+), 223 deletions(-) diff --git a/.rustfmt.toml b/.rustfmt.toml index ef20e40..4c6e3cd 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,67 +1,3 @@ -max_width = 90 # changed -hard_tabs = false -tab_spaces = 4 -newline_style = "Auto" -use_small_heuristics = "Default" -indent_style = "Block" -wrap_comments = false -format_code_in_doc_comments = false -comment_width = 80 -normalize_comments = true # changed -normalize_doc_attributes = false -# license_template_path = "LICENSE_TEMPLATE" # changed -format_strings = false -format_macro_matchers = false -format_macro_bodies = true -empty_item_single_line = true -struct_lit_single_line = true -fn_single_line = false -where_single_line = false -imports_indent = "Block" -imports_layout = "Vertical" # changed -imports_granularity="Crate" # changed -reorder_imports = true -reorder_modules = true -reorder_impl_items = false -type_punctuation_density = "Wide" -space_before_colon = false -space_after_colon = true -spaces_around_ranges = false -binop_separator = "Front" -remove_nested_parens = true -combine_control_expr = false # changed -overflow_delimited_expr = false -struct_field_align_threshold = 0 -enum_discrim_align_threshold = 0 -match_arm_blocks = true -force_multiline_blocks = true # changed -fn_args_layout = "Tall" -brace_style = "SameLineWhere" -control_brace_style = "AlwaysSameLine" -trailing_semicolon = false # changed -trailing_comma = "Vertical" -match_block_trailing_comma = false -blank_lines_upper_bound = 1 -blank_lines_lower_bound = 0 -edition = "2018" # changed -version = "One" -merge_derives = true -use_try_shorthand = true # changed -use_field_init_shorthand = true # changed -force_explicit_abi = true -condense_wildcard_suffixes = false -color = "Auto" -unstable_features = true # changed -disable_all_formatting = false -skip_children = false -hide_parse_errors = false -error_on_line_overflow = false -error_on_unformatted = false -report_todo = "Always" -report_fixme = "Always" -ignore = [] - -# Below are `rustfmt` internal settings -# -# emit_mode = "Files" -# make_backup = false +imports_granularity = "Crate" +imports_layout = "HorizontalVertical" +edition = "2021" \ No newline at end of file diff --git a/benches/setup.rs b/benches/setup.rs index 0824a36..97f510d 100644 --- a/benches/setup.rs +++ b/benches/setup.rs @@ -1,22 +1,15 @@ use string_interner::{ - backend::{ - Backend, - BucketBackend, - BufferBackend, - SimpleBackend, - StringBackend, - }, + backend::{Backend, BucketBackend, BufferBackend, SimpleBackend, StringBackend}, DefaultSymbol, StringInterner, }; /// Alphabet containing all characters that may be put into a benchmark string. const ALPHABET: [u8; 64] = [ - b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', - b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'A', b'B', - b'C', b'D', b'E', b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', b'P', - b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', b'Z', b'0', b'1', b'2', b'3', - b'4', b'5', b'6', b'7', b'8', b'9', b'_', b'-', + b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', b'p', + b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'A', b'B', b'C', b'D', b'E', b'F', + b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', b'P', b'Q', b'R', b'S', b'T', b'U', b'V', + b'W', b'X', b'Y', b'Z', b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'_', b'-', ]; /// A word builder for benchmark purposes. @@ -39,10 +32,10 @@ impl WordBuilder { 'l: for index in &mut self.indices { if *index == (64 - 1) { *index = 0; - continue 'l + continue 'l; } *index += 1; - return Some(&self.indices[..]) + return Some(&self.indices[..]); } None } diff --git a/src/backend/bucket/fixed_str.rs b/src/backend/bucket/fixed_str.rs index 71e2648..1cb3ebc 100644 --- a/src/backend/bucket/fixed_str.rs +++ b/src/backend/bucket/fixed_str.rs @@ -44,7 +44,7 @@ impl FixedString { pub fn push_str(&mut self, string: &str) -> Option { let len = self.len(); if self.capacity() < len + string.len() { - return None + return None; } self.contents.push_str(string); debug_assert_eq!(self.contents.len(), len + string.len()); @@ -52,9 +52,7 @@ impl FixedString { // SAFETY: We convert from bytes to utf8 from which we know through the // input string that they must represent valid utf8. unsafe { - core::str::from_utf8_unchecked( - &self.contents.as_bytes()[len..len + string.len()], - ) + core::str::from_utf8_unchecked(&self.contents.as_bytes()[len..len + string.len()]) }, )) } diff --git a/src/backend/bucket/mod.rs b/src/backend/bucket/mod.rs index 0b07ddd..3e2c074 100644 --- a/src/backend/bucket/mod.rs +++ b/src/backend/bucket/mod.rs @@ -3,24 +3,12 @@ mod fixed_str; mod interned_str; -use self::{ - fixed_str::FixedString, - interned_str::InternedStr, -}; +use self::{fixed_str::FixedString, interned_str::InternedStr}; use super::Backend; -use crate::{ - compat::Vec, - symbol::expect_valid_symbol, - DefaultSymbol, - Symbol, -}; +use crate::{compat::Vec, symbol::expect_valid_symbol, DefaultSymbol, Symbol}; #[cfg(not(feature = "std"))] use alloc::string::String; -use core::{ - iter::Enumerate, - marker::PhantomData, - slice, -}; +use core::{iter::Enumerate, marker::PhantomData, slice}; /// An interner backend that reduces memory allocations by using string buckets. /// /// # Note diff --git a/src/backend/buffer.rs b/src/backend/buffer.rs index 4bc990e..4429418 100644 --- a/src/backend/buffer.rs +++ b/src/backend/buffer.rs @@ -1,17 +1,8 @@ #![cfg(feature = "backends")] use super::Backend; -use crate::{ - compat::Vec, - symbol::expect_valid_symbol, - DefaultSymbol, - Symbol, -}; -use core::{ - marker::PhantomData, - mem, - str, -}; +use crate::{compat::Vec, symbol::expect_valid_symbol, DefaultSymbol, Symbol}; +use core::{marker::PhantomData, mem, str}; /// An interner backend that appends all interned string information in a single buffer. /// @@ -207,7 +198,7 @@ fn encode_var_usize(buffer: &mut Vec, mut value: usize) -> usize { if value <= 0x7F { // Shortcut the common case for low value. buffer.push(value as u8); - return 1 + return 1; } let mut len_chunks = 0; loop { @@ -217,7 +208,7 @@ fn encode_var_usize(buffer: &mut Vec, mut value: usize) -> usize { buffer.push(chunk); len_chunks += 1; if value == 0 { - break + break; } } len_chunks @@ -236,7 +227,7 @@ fn encode_var_usize(buffer: &mut Vec, mut value: usize) -> usize { unsafe fn decode_var_usize_unchecked(buffer: &[u8]) -> (usize, usize) { let first = unsafe { *buffer.get_unchecked(0) }; if first <= 0x7F_u8 { - return (first as usize, 1) + return (first as usize, 1); } let mut result: usize = 0; let mut i = 0; @@ -245,7 +236,7 @@ unsafe fn decode_var_usize_unchecked(buffer: &[u8]) -> (usize, usize) { let shifted = ((byte & 0x7F_u8) as usize) << ((i * 7) as u32); result += shifted; if (byte & 0x80) == 0 { - break + break; } i += 1; } @@ -259,7 +250,7 @@ unsafe fn decode_var_usize_unchecked(buffer: &[u8]) -> (usize, usize) { fn decode_var_usize(buffer: &[u8]) -> Option<(usize, usize)> { if !buffer.is_empty() && buffer[0] <= 0x7F_u8 { // Shortcut the common case for low values. - return Some((buffer[0] as usize, 1)) + return Some((buffer[0] as usize, 1)); } let mut result: usize = 0; let mut i = 0; @@ -268,7 +259,7 @@ fn decode_var_usize(buffer: &[u8]) -> Option<(usize, usize)> { let shifted = ((byte & 0x7F_u8) as usize).checked_shl((i * 7) as u32)?; result = result.checked_add(shifted)?; if (byte & 0x80) == 0 { - break + break; } i += 1; } @@ -277,10 +268,7 @@ fn decode_var_usize(buffer: &[u8]) -> Option<(usize, usize)> { #[cfg(test)] mod tests { - use super::{ - decode_var_usize, - encode_var_usize, - }; + use super::{decode_var_usize, encode_var_usize}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; @@ -450,14 +438,14 @@ where #[inline] fn next(&mut self) -> Option { - self.backend.resolve_index_to_str(self.current).and_then( - |(string, next_string_index)| { + self.backend + .resolve_index_to_str(self.current) + .and_then(|(string, next_string_index)| { let symbol = S::try_from_usize(self.current)?; self.current = next_string_index; self.yielded += 1; Some((symbol, string)) - }, - ) + }) } } diff --git a/src/backend/simple.rs b/src/backend/simple.rs index 564e92e..9db495b 100644 --- a/src/backend/simple.rs +++ b/src/backend/simple.rs @@ -2,20 +2,12 @@ use super::Backend; use crate::{ - compat::{ - Box, - ToString, - Vec, - }, + compat::{Box, ToString, Vec}, symbol::expect_valid_symbol, DefaultSymbol, Symbol, }; -use core::{ - iter::Enumerate, - marker::PhantomData, - slice, -}; +use core::{iter::Enumerate, marker::PhantomData, slice}; /// A simple backend that stores a separate allocation for every interned string. /// diff --git a/src/backend/string.rs b/src/backend/string.rs index dd34e16..bfa150f 100644 --- a/src/backend/string.rs +++ b/src/backend/string.rs @@ -2,19 +2,12 @@ use super::Backend; use crate::{ - compat::{ - String, - Vec, - }, + compat::{String, Vec}, symbol::expect_valid_symbol, DefaultSymbol, Symbol, }; -use core::{ - iter::Enumerate, - marker::PhantomData, - slice, -}; +use core::{iter::Enumerate, marker::PhantomData, slice}; /// An interner backend that accumulates all interned string contents into one string. /// @@ -66,11 +59,11 @@ where { fn eq(&self, other: &Self) -> bool { if self.ends.len() != other.ends.len() { - return false + return false; } for ((_, lhs), (_, rhs)) in self.into_iter().zip(other) { if lhs != rhs { - return false + return false; } } true @@ -117,9 +110,7 @@ where // method. // - The spans we use for `(start..end]` ranges are always // constructed in accordance to valid utf8 byte ranges. - unsafe { - core::str::from_utf8_unchecked(&self.buffer.as_bytes()[span.from..span.to]) - } + unsafe { core::str::from_utf8_unchecked(&self.buffer.as_bytes()[span.from..span.to]) } } /// Returns the span for the given symbol if any. diff --git a/src/compat.rs b/src/compat.rs index 9c8f8e5..54bd7d6 100644 --- a/src/compat.rs +++ b/src/compat.rs @@ -4,10 +4,7 @@ use cfg_if::cfg_if; pub use ::hashbrown::{ hash_map, - hash_map::{ - DefaultHashBuilder, - HashMap, - }, + hash_map::{DefaultHashBuilder, HashMap}, }; cfg_if! { diff --git a/src/interner.rs b/src/interner.rs index f33a8e9..89170b8 100644 --- a/src/interner.rs +++ b/src/interner.rs @@ -1,24 +1,14 @@ use crate::{ backend::Backend, - compat::{ - DefaultHashBuilder, - HashMap, - }, + compat::{DefaultHashBuilder, HashMap}, DefaultBackend, DefaultSymbol, Symbol, }; use core::{ fmt, - fmt::{ - Debug, - Formatter, - }, - hash::{ - BuildHasher, - Hash, - Hasher, - }, + fmt::{Debug, Formatter}, + hash::{BuildHasher, Hash, Hasher}, iter::FromIterator, }; @@ -271,10 +261,7 @@ where /// If the interner already interns the maximum number of strings possible /// by the chosen symbol type. #[inline] - pub fn get_or_intern_static( - &mut self, - string: &'static str, - ) -> ::Symbol { + pub fn get_or_intern_static(&mut self, string: &'static str) -> ::Symbol { self.get_or_intern_using(string, B::intern_static) } diff --git a/src/lib.rs b/src/lib.rs index dd4e02a..7306e6d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -137,8 +137,5 @@ pub use self::{ backend::DefaultBackend, compat::DefaultHashBuilder, interner::StringInterner, - symbol::{ - DefaultSymbol, - Symbol, - }, + symbol::{DefaultSymbol, Symbol}, }; diff --git a/src/serde_impl.rs b/src/serde_impl.rs index b15f7eb..9ca51b3 100644 --- a/src/serde_impl.rs +++ b/src/serde_impl.rs @@ -1,28 +1,10 @@ -use crate::{ - backend::Backend, - StringInterner, - Symbol, -}; +use crate::{backend::Backend, StringInterner, Symbol}; #[cfg(not(feature = "std"))] use alloc::boxed::Box; -use core::{ - default::Default, - fmt, - hash::BuildHasher, - marker, -}; +use core::{default::Default, fmt, hash::BuildHasher, marker}; use serde::{ - de::{ - Deserialize, - Deserializer, - SeqAccess, - Visitor, - }, - ser::{ - Serialize, - SerializeSeq, - Serializer, - }, + de::{Deserialize, Deserializer, SeqAccess, Visitor}, + ser::{Serialize, SerializeSeq, Serializer}, }; impl Serialize for StringInterner @@ -96,10 +78,8 @@ where where A: SeqAccess<'de>, { - let mut interner: StringInterner = StringInterner::with_capacity_and_hasher( - seq.size_hint().unwrap_or(0), - H::default(), - ); + let mut interner: StringInterner = + StringInterner::with_capacity_and_hasher(seq.size_hint().unwrap_or(0), H::default()); while let Some(s) = seq.next_element::>()? { interner.get_or_intern(s); } diff --git a/src/symbol.rs b/src/symbol.rs index b60360d..a9c0fb0 100644 --- a/src/symbol.rs +++ b/src/symbol.rs @@ -5,11 +5,7 @@ //! method returns `Symbol` types that allow to look-up the original string //! using [`StringInterner::resolve`](`crate::StringInterner::resolve`). -use core::num::{ - NonZeroU16, - NonZeroU32, - NonZeroUsize, -}; +use core::num::{NonZeroU16, NonZeroU32, NonZeroUsize}; /// Types implementing this trait can be used as symbols for string interners. /// diff --git a/tests/allocator.rs b/tests/allocator.rs index 6b8ec79..a5bb108 100644 --- a/tests/allocator.rs +++ b/tests/allocator.rs @@ -1,14 +1,6 @@ use std::{ - alloc::{ - GlobalAlloc, - Layout, - System, - }, - sync::atomic::{ - AtomicBool, - AtomicUsize, - Ordering, - }, + alloc::{GlobalAlloc, Layout, System}, + sync::atomic::{AtomicBool, AtomicUsize, Ordering}, }; pub struct TracingAllocator { @@ -112,7 +104,7 @@ impl TracedStats { fn push_allocations(&self, layout: Layout) { let size = layout.size(); if !self.is_active() || size == 0 { - return + return; } self.len_allocations.fetch_add(1, Ordering::SeqCst); self.current_memory_usage.fetch_add(size, Ordering::SeqCst); @@ -122,7 +114,7 @@ impl TracedStats { fn push_deallocations(&self, layout: Layout) { let size = layout.size(); if !self.is_active() || size == 0 { - return + return; } self.len_deallocations.fetch_add(1, Ordering::SeqCst); self.current_memory_usage.fetch_sub(size, Ordering::SeqCst); diff --git a/tests/tests.rs b/tests/tests.rs index ae51517..4650401 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -1,12 +1,7 @@ mod allocator; use allocator::TracingAllocator; -use string_interner::{ - backend, - DefaultHashBuilder, - DefaultSymbol, - Symbol, -}; +use string_interner::{backend, DefaultHashBuilder, DefaultSymbol, Symbol}; #[global_allocator] static ALLOCATOR: TracingAllocator = TracingAllocator::new();