Polishing Rust
diesel
compile time fail whenupdate
without settingupdated_at
field- ensure
no_copy
macro attribute - look for a way to disallow usage of the
eq
method onNullable
values and suggestquery.filter(dsl::zone_id.is_not_distinct_from(req.zone_id));
- diesel ensure all queries are explicitly
order
ed - rust macro bang to return ok
a.b.c!
:a.b.c.map(Ok)
- diesel struct fields ordering matters even with name+
sql_type
but not withouttable_name
annotation - write cobol in rust
- rust diesel color conn with readonly
- rust clippy
let keys = devices.keys().copied().collect::<Vec<_>>();for key in keys {
no_panic
introduce a new unique libpanic.so, cardinality tuned for precision on codebase origin. build.rs generates uniq crates copying libpanic.so code but with uniq final .so files- haxl in rust (i.e. compile-time errors when interleaving the use of >1 resources. E.g. DB conn + gRPC calls => put back conn to pool)
-
attribute macro on
diesel
’s user structs (returned byload
,get_result
,get_results
, …) thatimpl Drop
and says"oh gee, we're dropping something we mutated but didn't write back to DB hmmm?"
(attr adds a new private int struct field that stores which fields were modified) - SIMD Floating point and integer compressed vector library
- generalize-able SIMD-oriented
Iterator
- https://github.com/velvia/compressed-vec/blob/main/src/sink.rs
- https://github.com/velvia/compressed-vec/blob/81f6f7aa9d2935b234ac92d47a17ecd82c569baf/src/vector.rs#L460
- https://github.com/velvia/compressed-vec/blob/81f6f7aa9d2935b234ac92d47a17ecd82c569baf/src/section.rs#L349
- generalize-able SIMD-oriented
Missing lints
Prefer .as_deref()
over .clone()
when using just .map(..)
on Option<String>
let route = diesel::update(&route)
.set((
req.description.clone().map(|desc| route::description.eq(desc)),
req.tags.clone().map(|tags| route::tags.eq(tags)),
req.destination.map(|dest| route::destination.eq(dest)),
req.nh_pn_id.map(|pn_id| route::nexthop_private_network_key.eq(pn_id)),
req.nh_resource_id.map(|resource_id| route::nexthop_resource_key.eq(resource_id)),
route::modification_date.eq(statement_timestamp()),
))
.get_result::<Route>(conn)
.with_resource("route", route.key)?;
req.description.as_deref().map(|desc| route::description.eq(desc)),
req.tags.as_deref().map(|tags| route::tags.eq(tags)),
Redundant Option<_>
check on is_none()
with unwrap_or_default()
assert_eq!(
user_input.as_ref().map(|x| !x.contains('@')).unwrap_or_default(),
(user_input.is_none()
|| user_input.as_ref().map(|x| !x.contains('@')).unwrap_or_default()),
);
Fix a design “angle mort” in cargo
Replace current (1.79) error:
error: the lock file $HOME/wefwefwef/reMarkable-tools.git/Cargo.lock needs to be updated but --locked was passed to prevent this
If you want to try to generate the lock file without accessing the network, remove the --locked flag and use --offline instead.
turn this error into “cargo-fetch then continue”
downgrade owned argument to Ref
An async Drop
impl
impl Drop for Thing {
fn drop(self) {
let mut rt = ::tokio::runtime::Runtime::new().unwrap();
rt.block_on(async { timeout(self.fd.close()).await.unwrap() });
}
}
// Better yet!:
// > A correctly implemented runtime will run the destructor on that future,
// > allowing it to clean up its state.
// A proc-macro to make sure a Drop impl runs within reasonable ([statically] bounded) time
impl Drop for Thing {
#[tokio::drop(timeout = "500ms")]
async fn drop(self) {
self.fd.close()
}
}
Cryptographic signatures for unsafe code
On SAFETY
annotations & their evolution through time with regards to the actual annotated code.
0 1s launch-code.git master ❯ gwd
origin git@github.com:kmcallister/launch-code.git
0 0s launch-code.git master ❯ cat README.md
Functions containing unsafe code demand extra scrutiny, because they can break Rust’s memory safety guarantees. Some projects may desire a formal process for auditing unsafe code whenever it is added or modified. This compiler plugin supports a workflow where audit status is tracked in the source code, and the history of audits is part of each file’s version control history.
It works by attaching a cryptographic signature to every unsafe fn
, as well
as every fn
that contains an unsafe
block.
#![feature(plugin)]
#[no_link]
#[plugin(public_key="examples/pubkey")]
extern crate launch_code;
#[launch_code="⠐⡛⢾⣯⢓⢵⢖⡆⣈⠇⠸⣼⢁⢦⢰⢷⡫⢙⠻⠺⢗⢻⣷⠋⣸⡐⣂⡜⠇⡍⢁⢗⢜⠢⡢⣵⠩⠲⡈⢈⢂⡑⣷⣩⢲⢖⢃⡓⠄⣴⠩⡹⡸⠥⢱⢭⡼⠡⣻⡥⢜⢔⡌⠅"]
fn totally_fine() -> u64 {
unsafe {
*std::ptr::null()
}
}
use std::char;
fn to_braille(xs: &[u8]) -> String {
xs.iter()
# .map(|&x| char::from_u32(x as u32 + 0x2800).unwrap())
.try_map(|&x| char::from_u32(x as u32 + 0x2800).unwrap())
.collect()
}
fn from_braille(xs: &str) -> Option<Vec<u8>> {
xs
.chars()
# .map(|c| match c as u32 {
# n @ 0x2800..=0x28FF => (n - 0x2800) as u8,
# _ => {
# bogus = true;
# 0
# }
# })
# .collect();
# if bogus {
# None
# } else {
# Some(vec)
# }
.optionally_map(|c| match c as u32 {
n @ 0x2800..=0x28FF => Some((n - 0x2800) as u8),
_ => None
}) # -> Option<Iter<Item=u32>>, breaks at first None.
.map(|it| -> Vec<u32> { it.collect() })
}