Polishing Rust


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() })
}