Skip to content

Instantly share code, notes, and snippets.

@peterjoel
peterjoel / bench-string-concat.rs
Created May 3, 2020 15:03
Benchmarking different methods of concatenating two strings
#![cfg(test)]
#![feature(test)]
extern crate test;
use test::bench::{black_box, Bencher};
fn concat_to_owned_push(a: &str, b: &str) -> String {
let mut s = a.to_owned();
s.push_str(b);
s
use std::marker::PhantomData;
use std::fmt;
// Marker types for specifying the side of the first item and the previously
// added item
struct Left;
struct Right;
struct Empty;
struct AlternatingVec<L, R, P = Empty, S = Empty> {
[package]
name = "lukas_threads"
version = "0.1.0"
authors = ["Peter Hall <peterjoel@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
audio_thread_priority = "0.15.0"
@peterjoel
peterjoel / main.rs
Last active July 4, 2019 09:26
Another tricky puzzle
struct A;
struct B(A);
fn d<T>(t: T) {
match std::mem::size_of_val(&t) {
n if n < 2 => print!("{}", n),
_ => print!("2"),
}
}
trait Trait {
fn p(&self);
}
macro_rules! m {
($v: expr, $t: ty, $n: literal) => {
impl Trait for $t {
fn p(&self) {
print!($n);
}
@peterjoel
peterjoel / Cargo.toml
Last active May 22, 2019 10:59
Flattening fields is not zero-cost in serde
[package]
name = "serdebug"
version = "0.1.0"
edition = "2018"
[dependencies]
serde = { version = "1.0.91", features = ["derive"] }
serde_json = "1.0.39"
@peterjoel
peterjoel / Cargo.toml
Last active May 18, 2019 13:36
Format deserializes for manually flattened struct but requires deserialize_any when the fields are flattened using serde attributes.
[package]
name = "serde_fix_s"
version = "0.1.0"
edition = "2018"
[dependencies]
serde = { version = "1.0.91", features = ["derive"] }
[dev-dependencies]
serde_test = "1"
[package]
name = "camelkebab"
version = "0.1.0"
edition = "2018"
[dependencies]
Inflector = "0.11.4"
@peterjoel
peterjoel / main.rs
Last active March 6, 2019 09:38
Two possible implementations of a safe wrapper around `core::intrinsics::type_name`
fn main() {
println!("type = {:?}", debug::type_name::<String>());
let v = vec![Some(Box::new(|s: i32| println!("{:?}", s)))];
println!("type = {:?}", debug::type_name_of_val(&v));
}
#![feature(test)]
extern crate test;
use std::cmp::min;
use std::collections::HashSet;
pub fn distribute_candies_loop_with_capacity(candies: Vec<i32>) -> i32 {
let sister_candies = (candies.len() / 2) as i32;
let mut kind = 0;
use std::collections::HashSet;
let mut candies_kinds = HashSet::with_capacity(candies.len());