Skip to content

Commit

Permalink
style: format code blocks
Browse files Browse the repository at this point in the history
Signed-off-by: simonsan <[email protected]>
  • Loading branch information
simonsan committed Mar 18, 2024
1 parent a37b288 commit 74d82e3
Show file tree
Hide file tree
Showing 18 changed files with 110 additions and 89 deletions.
9 changes: 8 additions & 1 deletion dprint.json → .dprint.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,17 @@
"theme/book.js",
"target/**/*"
],
"exec": {
"commands": [{
"command": "rustfmt --edition 2021",
"exts": ["rs"]
}]
},
"plugins": [
"https://plugins.dprint.dev/markdown-0.16.4.wasm",
"https://plugins.dprint.dev/toml-0.6.1.wasm",
"https://plugins.dprint.dev/json-0.19.2.wasm",
"https://plugins.dprint.dev/typescript-0.89.3.wasm"
"https://plugins.dprint.dev/typescript-0.89.3.wasm",
"https://plugins.dprint.dev/exec-0.4.4.json@c207bf9b9a4ee1f0ecb75c594f774924baf62e8e53a2ce9d873816a408cecbf7"
]
}
10 changes: 9 additions & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,12 @@ jobs:
steps:
- uses: actions/checkout@v4

- uses: dprint/[email protected]
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1482605bfc5719782e1267fd0c0cc350fe7646b8 # v1
with:
toolchain: stable
components: rustfmt

- uses: Swatinem/rust-cache@23bce251a8cd2ffc3c1075eaa2367cf899916d84 # v2

- uses: dprint/[email protected]
52 changes: 28 additions & 24 deletions src/anti_patterns/deny-warnings.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,35 +58,39 @@ is a list of warning lints that is (hopefully) safe to deny (as of Rustc
1.48.0):

```rust,ignore
#![deny(bad_style,
const_err,
dead_code,
improper_ctypes,
non_shorthand_field_patterns,
no_mangle_generic_items,
overflowing_literals,
path_statements,
patterns_in_fns_without_body,
private_in_public,
unconditional_recursion,
unused,
unused_allocation,
unused_comparisons,
unused_parens,
while_true)]
#![deny(
bad_style,
const_err,
dead_code,
improper_ctypes,
non_shorthand_field_patterns,
no_mangle_generic_items,
overflowing_literals,
path_statements,
patterns_in_fns_without_body,
private_in_public,
unconditional_recursion,
unused,
unused_allocation,
unused_comparisons,
unused_parens,
while_true
)]
```

In addition, the following `allow`ed lints may be a good idea to `deny`:

```rust,ignore
#![deny(missing_debug_implementations,
missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results)]
#![deny(
missing_debug_implementations,
missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
```

Some may also want to add `missing-copy-implementations` to their list.
Expand Down
4 changes: 2 additions & 2 deletions src/functional/generics-type-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ mod bootp {

// private module, lest outside users invent their own protocol kinds!
mod proto_trait {
use std::path::{Path, PathBuf};
use super::{bootp, nfs};
use std::path::{Path, PathBuf};

pub(crate) trait ProtoKind {
type AuthInfo;
Expand Down Expand Up @@ -157,7 +157,7 @@ mod proto_trait {
}

use proto_trait::ProtoKind; // keep internal to prevent impls
pub use proto_trait::{Nfs, Bootp}; // re-export so callers can see them
pub use proto_trait::{Bootp, Nfs}; // re-export so callers can see them

struct FileDownloadRequest<P: ProtoKind> {
file_name: PathBuf,
Expand Down
13 changes: 8 additions & 5 deletions src/functional/optics.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,8 @@ use anyhow;
use std::str::FromStr;
struct TestStruct {
a: usize,
b: String,
a: usize,
b: String,
}
impl FromStr for TestStruct {
Expand All @@ -203,7 +203,10 @@ impl ToString for TestStruct {
}
fn main() {
let a = TestStruct { a: 5, b: "hello".to_string() };
let a = TestStruct {
a: 5,
b: "hello".to_string(),
};
println!("Our Test Struct as JSON: {}", a.to_string());
}
```
Expand Down Expand Up @@ -264,8 +267,8 @@ independent form, it is even possible to have code generation creating the
```rust,ignore
#[derive(Default, Serde)] // the "Serde" derive creates the trait impl block
struct TestStruct {
a: usize,
b: String,
a: usize,
b: String,
}
// user writes this macro to generate an associated visitor type
Expand Down
9 changes: 4 additions & 5 deletions src/idioms/coercion-arguments.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ fn three_vowels(word: &String) -> bool {
'a' | 'e' | 'i' | 'o' | 'u' => {
vowel_count += 1;
if vowel_count >= 3 {
return true
return true;
}
}
_ => vowel_count = 0
_ => vowel_count = 0,
}
}
false
Expand All @@ -54,7 +54,6 @@ fn main() {
// This works fine, but the following two lines would fail:
// println!("Ferris: {}", three_vowels("Ferris"));
// println!("Curious: {}", three_vowels("Curious"));

}
```

Expand Down Expand Up @@ -97,10 +96,10 @@ fn three_vowels(word: &str) -> bool {
'a' | 'e' | 'i' | 'o' | 'u' => {
vowel_count += 1;
if vowel_count >= 3 {
return true
return true;
}
}
_ => vowel_count = 0
_ => vowel_count = 0,
}
}
false
Expand Down
6 changes: 3 additions & 3 deletions src/idioms/ctor.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ object:
/// assert_eq!(42, s.value());
/// ```
pub struct Second {
value: u64
value: u64,
}

impl Second {
Expand Down Expand Up @@ -47,7 +47,7 @@ Rust supports default constructors with the [`Default`][std-default] trait:
/// assert_eq!(0, s.value());
/// ```
pub struct Second {
value: u64
value: u64,
}

impl Second {
Expand Down Expand Up @@ -78,7 +78,7 @@ like they do with `Second`:
/// ```
#[derive(Default)]
pub struct Second {
value: u64
value: u64,
}

impl Second {
Expand Down
5 changes: 1 addition & 4 deletions src/idioms/ffi/accepting-strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,7 @@ pub mod unsafe_module {
/// - points to memory ending in a null byte
/// - won't be mutated for the duration of this function call
#[no_mangle]
pub unsafe extern "C" fn mylib_log(
msg: *const libc::c_char,
level: libc::c_int
) {
pub unsafe extern "C" fn mylib_log(msg: *const libc::c_char, level: libc::c_int) {
let level: crate::LogLevel = match level { /* ... */ };
// SAFETY: The caller has already guaranteed this is okay (see the
Expand Down
17 changes: 8 additions & 9 deletions src/idioms/ffi/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ in a usable way:

```rust,ignore
enum DatabaseError {
IsReadOnly = 1, // user attempted a write operation
IOError = 2, // user should read the C errno() for what it was
IsReadOnly = 1, // user attempted a write operation
IOError = 2, // user should read the C errno() for what it was
FileCorrupted = 3, // user should run a repair tool to recover it
}
Expand Down Expand Up @@ -57,10 +57,7 @@ pub mod c_api {
use super::errors::DatabaseError;
#[no_mangle]
pub extern "C" fn db_error_description(
e: *const DatabaseError
) -> *mut libc::c_char {
pub extern "C" fn db_error_description(e: *const DatabaseError) -> *mut libc::c_char {
let error: &DatabaseError = unsafe {
// SAFETY: pointer lifetime is greater than the current stack frame
&*e
Expand Down Expand Up @@ -107,17 +104,19 @@ pub mod c_api {
struct ParseError {
expected: char,
line: u32,
ch: u16
ch: u16,
}
impl ParseError { /* ... */ }
impl ParseError {
/* ... */
}
/* Create a second version which is exposed as a C structure */
#[repr(C)]
pub struct parse_error {
pub expected: libc::c_char,
pub line: u32,
pub ch: u16
pub ch: u16,
}
impl From<ParseError> for parse_error {
Expand Down
4 changes: 1 addition & 3 deletions src/idioms/ffi/passing-strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ pub mod unsafe_module {
fn geterr(buffer: *mut libc::c_char, size: libc::c_int) -> libc::c_int;
}
fn report_error_to_ffi<S: Into<String>>(
err: S
) -> Result<(), std::ffi::NulError>{
fn report_error_to_ffi<S: Into<String>>(err: S) -> Result<(), std::ffi::NulError> {
let c_err = std::ffi::CString::new(err.into())?;
unsafe {
Expand Down
18 changes: 12 additions & 6 deletions src/idioms/mem-replace.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::mem;

enum MyEnum {
A { name: String, x: u8 },
B { name: String }
B { name: String },
}

fn a_to_b(e: &mut MyEnum) {
Expand All @@ -24,7 +24,9 @@ fn a_to_b(e: &mut MyEnum) {
// (note that empty strings don't allocate).
// Then, construct the new enum variant (which will
// be assigned to `*e`).
*e = MyEnum::B { name: mem::take(name) }
*e = MyEnum::B {
name: mem::take(name),
}
}
}
```
Expand All @@ -38,18 +40,22 @@ enum MultiVariateEnum {
A { name: String },
B { name: String },
C,
D
D,
}

fn swizzle(e: &mut MultiVariateEnum) {
use MultiVariateEnum::*;
*e = match e {
// Ownership rules do not allow taking `name` by value, but we cannot
// take the value out of a mutable reference, unless we replace it:
A { name } => B { name: mem::take(name) },
B { name } => A { name: mem::take(name) },
A { name } => B {
name: mem::take(name),
},
B { name } => A {
name: mem::take(name),
},
C => D,
D => C
D => C,
}
}
```
Expand Down
14 changes: 8 additions & 6 deletions src/idioms/priv-extend.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,23 @@ mod a {
pub struct S {
pub foo: i32,
}

#[non_exhaustive]
pub enum AdmitMoreVariants {
VariantA,
VariantB,
#[non_exhaustive]
VariantC { a: String }
VariantC {
a: String,
},
}
}

fn print_matched_variants(s: a::S) {
// Because S is `#[non_exhaustive]`, it cannot be named here and
// we must use `..` in the pattern.
let a::S { foo: _, ..} = s;
let a::S { foo: _, .. } = s;

let some_enum = a::AdmitMoreVariants::VariantA;
match some_enum {
a::AdmitMoreVariants::VariantA => println!("it's an A"),
Expand All @@ -50,7 +52,7 @@ fn print_matched_variants(s: a::S) {

// The wildcard match is required because more variants may be
// added in the future
_ => println!("it's a new variant")
_ => println!("it's a new variant"),
}
}
```
Expand Down Expand Up @@ -78,7 +80,7 @@ pub struct S {
pub a: i32,
// Because `b` is private, you cannot match on `S` without using `..` and `S`
// cannot be directly instantiated or matched against
_b: ()
_b: (),
}
```

Expand Down
4 changes: 3 additions & 1 deletion src/idioms/return-consumed-arg-on-error.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ pub fn send(value: String) -> Result<(), SendError> {
println!("using {value} in a meaningful way");
// Simulate non-deterministic fallible action.
use std::time::SystemTime;
let period = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
let period = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
if period.subsec_nanos() % 2 == 1 {
Ok(())
} else {
Expand Down
4 changes: 2 additions & 2 deletions src/patterns/behavioural/RAII.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ impl<'a, T> Deref for MutexGuard<'a, T> {
fn baz(x: Mutex<Foo>) {
let xx = x.lock();
xx.foo(); // foo is a method on Foo.
// The borrow checker ensures we can't store a reference to the underlying
// Foo which will outlive the guard xx.
// The borrow checker ensures we can't store a reference to the underlying
// Foo which will outlive the guard xx.
// x is unlocked when we exit this function and xx's destructor is executed.
}
Expand Down
Loading

0 comments on commit 74d82e3

Please sign in to comment.