Skip to content

Instantly share code, notes, and snippets.

View haudan's full-sized avatar

Daniel Hauser haudan

  • Fronius International GmbH
  • Austria
  • 11:35 (UTC +01:00)
View GitHub Profile
@haudan
haudan / first_free_key.rs
Created December 16, 2019 11:25
BTreeMap first free key
use std::collections::BTreeMap;
fn first_free_key<V>(map: &BTreeMap<usize, V>) -> usize {
map.keys()
.zip(map.keys().skip(1))
.find(|(a, b)| (*b - *a) > 1)
.map(|(a, _)| *a + 1)
.unwrap_or_else(|| map.keys().last().map(|x| x + 1).unwrap_or(0))
}
@haudan
haudan / container_of.c
Last active September 6, 2021 13:54
CONTAINER_OF macro to downcast types more easily in C
//===--------------------~ Source ~--------------------===//
#include <stdint.h>
#ifndef offsetof
#define offsetof(type, member) ((uintptr_t)&((type*)0)->member)
#endif
#define CONTAINER_OF_CONST(member_ptr, container_ty, member_name) \
((container_ty const*) ((uintptr_t) member_ptr - offsetof(container_ty, member_name)))