Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/agents/all.txt
Git LFS file not shown
2 changes: 1 addition & 1 deletion src/guidelines/checklist/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@
[M-INTEGRATION-TESTS]: ../libs/resilience/#M-INTEGRATION-TESTS
[M-AVOID-STATICS]: ../libs/resilience/#M-AVOID-STATICS
[M-OOBE]: ../libs/building/#M-OOBE
[M-SYS-CRATES]: ../libs/resilience/#M-SYS-CRATES
[M-SYS-CRATES]: ../libs/building/#M-SYS-CRATES
[M-FEATURES-ADDITIVE]: ../libs/building/#M-FEATURES-ADDITIVE

<!-- Apps -->
Expand Down
2 changes: 2 additions & 0 deletions src/guidelines/correctness/M-PANIC-MESSAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

When code panics intentionally (via `panic!`, `assert!`, `unreachable!`, `todo!`, or similar), a message must be present to clearly state what went wrong and, where applicable, include relevant values.

Use `expect("reason")` instead of `unwrap()` so the panic message explains why an `Option` should contain a value or a `Result` should succeed.

```rust,ignore
// Bad, the panic gives the developer little to act on.
assert!(buffer.len() >= HEADER_SIZE);
Expand Down
2 changes: 1 addition & 1 deletion src/guidelines/correctness/M-PANIC-ON-BUG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn divide_by_fast(x: u32, y: u32) -> u32 { ... }

// Here, passing an invalid URI is not a contract violation.
// Since parsing is inherently fallible, a Result must be returned.
fn parse_uri(s: &str) -> Result<Uri, ParseError> { };
fn parse_uri(s: &str) -> Result<Uri, ParseError> { ... }

```

Expand Down
6 changes: 3 additions & 3 deletions src/guidelines/docs/M-MODULE-DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

<why>easy API docs navigation.</why>

Any public library module must have `//!` module documentation, and the first sentence must follow [M-DOC-FIRST-SENTENCE].
Any public library module must have `//!` module documentation, and the first sentence must follow [M-FIRST-DOC-SENTENCE].

```rust,edition2021,ignore
pub mod ffi {
//! Contains FFI abstractions.

pub struct String {};
pub struct String {}
}
```

Expand All @@ -32,4 +32,4 @@ The rest of the module documentation should be comprehensive, i.e., cover the mo
This does not mean every module should contain all of these items. But if there is something to say about the interaction of the contained types,
their module documentation is the right place.

[M-DOC-FIRST-SENTENCE]: ./#M-DOC-FIRST-SENTENCE
[M-FIRST-DOC-SENTENCE]: ./#M-FIRST-DOC-SENTENCE
6 changes: 3 additions & 3 deletions src/guidelines/ffi/M-FFI-TRANSLATES.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ impl Message {
A proper separation of concerns might collapse construction and transmission into a single FFI entry point in `foo-ffi`:

```rust,ignore
#[no_mangle]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn transmit_message(
destination: *const [u8; 8],
data: *const u8,
data_len: usize,
) -> u8 {
let data = std::slice::from_raw_parts(data, data_len).to_vec();
match Message::new(*destination, data).transmit() {
let data = unsafe { std::slice::from_raw_parts(data, data_len) }.to_vec();
match Message::new(unsafe { *destination }, data).transmit() {
Ok(()) => 0,
Err(_) => 1,
}
Expand Down
5 changes: 3 additions & 2 deletions src/guidelines/libs/interop/M-IMPL-IO.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ fn parse_data(data: impl std::io::Read) {}
Synchronous functions should use [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and
[`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html). Asynchronous _functions_ targeting more than one runtime should use
[`futures::io::AsyncRead`](https://docs.rs/futures/latest/futures/io/trait.AsyncRead.html) and similar.
_Types_ that need to perform runtime-specific, continuous I/O should follow [M-RUNTIME-ABSTRACTED] instead.
_Types_ that need to perform runtime-specific, continuous I/O should follow the runtime-dispatch enum pattern illustrated in
[M-MOCKABLE-SYSCALLS] instead.

[M-RUNTIME-ABSTRACTED]: ./#M-RUNTIME-ABSTRACTED
[M-MOCKABLE-SYSCALLS]: ../resilience/#M-MOCKABLE-SYSCALLS
19 changes: 9 additions & 10 deletions src/guidelines/libs/resilience/M-MOCKABLE-SYSCALLS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Library {
}
```

Behind the scenes, `LibraryCore` is a non-public enum, similar to [M-RUNTIME-ABSTRACTED], that either dispatches
Behind the scenes, `LibraryCore` is a non-public enum that either dispatches
calls to the respective sys call, or to an mocking controller.

```rust, ignore
Expand All @@ -65,10 +65,11 @@ enum LibraryCore {

impl LibraryCore {
// Some function you'd forward to the operating system.
fn random_u32(&self) {
fn random_u32(&self) -> u32 {
match self {
Self::Native => unsafe { os_random_u32() }
Self::Mocked(m) => m.random_u32()
Self::Native => unsafe { os_random_u32() },
#[cfg(feature = "test-util")]
Self::Mocked(m) => m.random_u32(),
}
}
}
Expand All @@ -86,7 +87,7 @@ mod mock {
// `MockCtrlInner` below.
impl MockCtrl {
pub fn set_next_u32(&self, x: u32) { ... }
pub fn random_u32(&self) { ... }
pub fn random_u32(&self) -> u32 { ... }
}

// Contains actual logic, e.g., the next random number we should return.
Expand All @@ -96,15 +97,15 @@ mod mock {
}
```

Runtime-aware libraries already build on top of the [M-RUNTIME-ABSTRACTED] pattern should extend their runtime enum instead:
Runtime-aware libraries that already dispatch through a runtime enum should extend that enum instead:

```rust, ignore
enum Runtime {
#[cfg(feature="tokio")]
Tokio(tokio::Tokio),

#[cfg(feature="smol")]
Smol(smol::Smol)
Smol(smol::Smol),

#[cfg(feature="test-util")]
Mock(mock::MockCtrl)
Expand All @@ -118,8 +119,6 @@ instances shared a single controller:
```rust, ignore
impl Library {
pub fn new_mocked() -> (Self, MockCtrl) { ... } // good
pub fn new_mocked_bad(&mut MockCtrl) -> Self { ... } // prone to misuse
pub fn new_mocked_bad(mock: &mut MockCtrl) -> Self { ... } // prone to misuse
}
```

[M-RUNTIME-ABSTRACTED]: ../ux/#M-RUNTIME-ABSTRACTED
4 changes: 2 additions & 2 deletions src/guidelines/libs/ux/M-AVOID-WRAPPERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

<why>low cognitive load and ergonomic APIs.</why>

As a specialization of [M-ABSTRACTIONS-DONT-NEST], generic wrappers and smart pointers like
As a specialization of [M-SIMPLE-ABSTRACTIONS], generic wrappers and smart pointers like
`Rc<T>`, `Arc<T>`, `Box<T>`, or `RefCell<T>` should be avoided in public APIs.

From a user perspective these are mostly implementation details, and introduce infectious complexity that users have to
Expand All @@ -28,4 +28,4 @@ Smart pointers in APIs are acceptable when:

- The smart pointer, based on benchmarks, significantly improves performance and the complexity is justified.

[M-ABSTRACTIONS-DONT-NEST]: ./#M-ABSTRACTIONS-DONT-NEST
[M-SIMPLE-ABSTRACTIONS]: ./#M-SIMPLE-ABSTRACTIONS
4 changes: 2 additions & 2 deletions src/guidelines/libs/ux/M-DI-HIERARCHY.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ _on top_ of your inherent functions. Each trait should be relatively narrow, e.g
trait is needed it should be made a subtrait, e.g., `trait DataAccess: StoreObject + LoadObject {}`.

Code working with these traits should ideally accept them as generic type parameters as long as their use does not contribute to significant nesting
(compare [M-ABSTRACTIONS-DONT-NEST]).
(compare [M-SIMPLE-ABSTRACTIONS]).

```rust,ignore
// Good, generic does not have infectious impact, uses only most specific trait
Expand Down Expand Up @@ -84,4 +84,4 @@ async fn read_database(x: &DataAccess) { ... }

[M-AVOID-WRAPPERS]: ./#M-AVOID-WRAPPERS
[M-MOCKABLE-SYSCALLS]: ../resilience/#M-MOCKABLE-SYSCALLS
[M-ABSTRACTIONS-DONT-NEST]: ./#M-ABSTRACTIONS-DONT-NEST
[M-SIMPLE-ABSTRACTIONS]: ./#M-SIMPLE-ABSTRACTIONS
2 changes: 1 addition & 1 deletion src/guidelines/libs/ux/M-ESSENTIAL-FN-INHERENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl HttpClient {
// Forward calls to inherent impls. `HttpClient` can be used
impl Download for HttpClient {
fn download_file(&self, url: impl AsRef<str>) {
Self::download_file(self, url)
self.download_file(url)
}
}
```
2 changes: 1 addition & 1 deletion src/guidelines/libs/ux/M-INIT-CASCADED.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ also check if [C-NEWTYPE] is applicable:
```rust, ignore
# struct Deposit;
# struct Account;
# struct Currency
# struct Currency;
impl Deposit {
// Better, signature cleaner
pub fn new(account: Account, amount: Currency) -> Self { }
Expand Down
7 changes: 4 additions & 3 deletions src/guidelines/libs/ux/M-SERVICES-CLONE.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ impl ServiceA {
// If we only need to access `common` from `new` we don't have
// to store it. Otherwise, make a clone we store in `Self`.
let common = common.clone();
Self { common }
}
}
```
Expand All @@ -43,13 +44,13 @@ Under the hood this `Clone` should **not** create a fat copy of the entire servi
struct ServiceCommonInner {}

#[derive(Clone)]
pub ServiceCommon {
pub struct ServiceCommon {
inner: Arc<ServiceCommonInner>
}

impl ServiceCommon {
pub fn new() {
Self { inner: Arc::new(ServiceCommonInner::new()) }
pub fn new() -> Self {
Self { inner: Arc::new(ServiceCommonInner {}) }
}

// Method forwards ...
Expand Down
2 changes: 1 addition & 1 deletion src/guidelines/macros/M-PROC-IMPLIED-ITEMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ struct UserType;
struct UserType;
struct ExtraType;
impl UserType {
fn foo() -> ExtraType { ... };
fn foo() -> ExtraType { ... }
}
```

Expand Down
2 changes: 1 addition & 1 deletion src/guidelines/performance/M-FAST-HASHER.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ Rust's default hasher is reasonably DoS safe on untrusted user input, but this c
let lookup = HashMap::<UserID, Data>::with_capacity(1024);

// Good, uses faster foldhash for internal keys.
let lookup = foldhash::HashMap<UserID, Data>::with_capacity(1024);
let lookup = foldhash::HashMap::<UserID, Data>::with_capacity(1024);
```
2 changes: 1 addition & 1 deletion src/guidelines/performance/M-LOG-OVERHEAD.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ for m in messages {
}

// Best: If possible, let telemetry users reconstruct what happened offline
log(("Processing message batch", messages.batch_id()))
log(("Processing message batch", messages.batch_id()));
for m in messages { ... }
```
4 changes: 2 additions & 2 deletions src/guidelines/performance/M-YIELD-POINTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Your future might be executed in a runtime that cannot work around blocking or l
considered bad design and cause runtime overhead. If your complex task performs I/O regularly it will simply utilize these await points to preempt itself:

```rust, ignore
async fn process_items(items: &[items]) {
async fn process_items(items: &[Item]) {
// Keep processing items, the runtime will preempt you automatically.
for i in items {
read_item(i).await;
Expand All @@ -22,7 +22,7 @@ If your task performs long-running CPU operations without intermixed I/O, it sho

```rust, ignore
async fn process_items(zip_file: File) {
let items = zip_file.read().async;
let items = zip_file.read().await;
for i in items {
decompress(i);
yield_now().await;
Expand Down
10 changes: 5 additions & 5 deletions src/guidelines/universal/M-DOCUMENTED-MAGIC.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ You should prefer named constants over inline values.

```rust, ignore
// Bad: it's relatively obvious that this waits for a day, but not why
wait_timeout(60 * 60 * 24).await // Wait at most a day
wait_timeout(60 * 60 * 24).await; // Wait at most a day

// Better
wait_timeout(60 * 60 * 24).await // Large enough value to ensure the server
// can finish. Setting this too low might
// make us abort a valid request. Based on
// `api.foo.com` timeout policies.
wait_timeout(60 * 60 * 24).await; // Large enough value to ensure the server
// can finish. Setting this too low might
// make us abort a valid request. Based on
// `api.foo.com` timeout policies.

// Best

Expand Down
1 change: 0 additions & 1 deletion src/guidelines/universal/M-STATIC-VERIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ missing_debug_implementations = "warn"
redundant_imports = "warn"
redundant_lifetimes = "warn"
trivial_numeric_casts = "warn"
unsafe_op_in_unsafe_fn = "warn"
unused_lifetimes = "warn"
```

Expand Down
Loading