Code snippets for Latex, Rust, and Python

These are some common libraries and code snippets for various tasks.

Latex

Code highlighting: minted

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
\usepackage[newfloat=true]{minted}
\newmintedfile{rust}{
  linenos,
  numbersep=5pt,
  frame=lines,
  baselinestretch=1.05,
  fontsize=\footnotesize,
}

\begin{listing}[t]
  \rustfile{code.rs}%
  \vspace{-1.3em}%
  \caption{Caption}%
  \label{rs:label}%
\end{listing}

Rust

Cargo.toml workspace

1
2
3
4
5
6
7
8
9
[workspace]
members = [
    "a",
    "b",
]
resolver = "2"

[workspace.dependencies]
serde = "1.0"

Release profile

1
2
3
4
[profile.release]
lto = "thin"
incremental = true
debug = true

List exported functions

1
cargo modules generate tree  --fns --traits --types --sort-by visibility

Read human genome using needletail

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
fn read_human_genome() -> PackedSeqVec {
    let mut packed_text = PackedSeqVec::default();
    let Ok(mut reader) = needletail::parse_fastx_file("human-genome.fa") else {
        eprintln!("Did not find human-genome.fa. Add/symlink it to test runtime on it.");
        return PackedSeqVec::default();
    };
    while let Some(r) = reader.next() {
        let r = r.unwrap();
        eprintln!(
            "Read {:?} of len {:?}",
            std::str::from_utf8(r.id()),
            r.raw_seq().len()
        );
        packed_text.push_ascii(r.raw_seq());
    }
    packed_text
}

Prevent auto-vectorization

v[i] prevents auto-vectorization, because the index can panic. Sometimes we want v.get_unchecked(i) instead, but now there are no more panic and the auto-vectorizer can kick in. Sometimes we want that, but sometimes we don’t. Especially with array indexing this is prone to generate slow gather instructions. Prevent this using:

1
2
3
4
unsafe {
    asm!("");
    *v.get_unchecked(b as usize)
}

Sorting

Use rdst (docs.rs, crates.io) for fast sorting. Quick benchmark in this bevy pr, where it’s \(20\times\) faster than standard sort_unstable. But note that rdst is multithreaded by default.

1
2
use rdst::RadixSort;
v.radix_sort_unstable();

For non-integer keys, implement the RadixKey trait.

There’s also radsort (docs.rs, crates.io), which seems a bit faster for single threaded execution.

1
2
radsort::sort(&mut v);
radsort::sort_by_key(&mut v, |x| x);

Python

Export org table

1
2
import tabulate
print(tabulate.tabulate(df, headers=df.columns, tablefmt="orgtbl", floatfmt=".1f"))

Pretty plots

Much nicer/softer colours with

1
plt.style.use('ggplot')?