Skip to content

Instantly share code, notes, and snippets.

View p7g's full-sized avatar

Patrick Gingras p7g

View GitHub Profile
@p7g
p7g / .md
Last active February 19, 2021 18:09
Dynamically implementing a Rust trait

Dynamically implementing a Rust trait

Sometimes one might need to create an object at run-time that implements a Rust trait. This is one way to do so, provided the trait to be implemented is known statically.

Here's how:

  1. Define a struct that will hold the implementation of each trait method.
  2. Define a second "object" struct that holds a "self" value and a reference to an implementation struct.
  3. Implement the desired trait for the object struct, dispatching to the function pointers in the implementation struct.

An example:

@p7g
p7g / context.tsx
Last active February 19, 2021 21:11
Some React context wrappers
import React from "react";
type Setter<T> = (newValueOrUpdater: T | ((oldValue: T) => T)) => void;
type FaaC<T, P = {}> = React.ComponentType<P & { children: (t: T) => (React.ReactElement | null) }>;
interface MutableContext<T> {
Consumer: FaaC<T>;
Mutator: FaaC<Setter<T>>;
Provider: React.ComponentType<{ value: T }>;
@p7g
p7g / mini-recoil.js
Last active January 30, 2021 18:01
A small, crappy version of facebookexperimental/Recoil (demo: https://codesandbox.io/s/mini-recoil-yqipr)
import React from "react";
const _Root = React.createContext();
export function Root({ children }) {
const [state] = React.useState(() => new Map());
return <_Root.Provider value={state}>{children}</_Root.Provider>;
}
@p7g
p7g / opt.diff
Last active December 22, 2020 05:54
diff --git a/days/day22/part2.py b/days/day22/part2.py
index ed286de..9870dc9 100644
--- a/days/day22/part2.py
+++ b/days/day22/part2.py
@@ -9,15 +9,15 @@ if __name__ == "__main__":
_, *cards = p.splitlines()
return deque(map(int, cards))
- def snapshot(*players):
- return tuple(map(tuple, players))
@p7g
p7g / 19-1.py
Created December 19, 2020 05:59
data = fetch(19).strip()
rules, messages = map(str.splitlines, data.split("\n\n"))
rs = [None] * len(rules)
for rule in rules:
id_, spec = rule.split(": ")
id_ = int(id_)
if spec[0] == '"':
@p7g
p7g / chainmap.js
Created December 17, 2020 01:08
Simple Python collections.ChainMap-esque construct in JavaScript
// The behaviour of Python's collections.ChainMap is the same as prototypal
// inheritance[1] in JavaScript:
//
// - Accessing a property of an object will traverse the prototype chain until
// the property is found (or until the end of the chain); and
// - Assigning to a property will only mutate the first object in the prototype
// chain (the object on which the property is being accessed).
//
// Thanks to this, we can implement something along the lines of Python's
// collections.ChainMap quite trivially.
times = "17,x,13,19".split(",")
equations = [(rem, int(mod)) for rem, mod in enumerate(times) if mod != "x"]
M = reduce(mul, map(itemgetter(1), equations))
x = 0
for a, m in equations:
y = M // m
z = pow(y, -1, m)
x += a * y * z
@p7g
p7g / ideas.md
Last active November 24, 2020 23:22
Python optimizer

cpython-opt (idea)

A just-in-time or ahead-of-time optimizer for CPython bytecode. The idea is to perform aggressive, possibly-expensive optimizations on Python functions without trying to compile to native code.

Example:

from cpython_opt import optimize

@optimize(aot=True, level=3)
def test():
@p7g
p7g / shunting_yard.py
Created June 28, 2020 20:38
Simple implementation of the shunting yard algorithm (https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm) in Python
operators = ['sentinel', '=', ')', '(', '+', '*', '.']
precedence = dict((b, a) for a, b in enumerate(operators))
assoc_right = {'='}
def has_higher_prec(a, b):
prec = precedence[a]
if a in assoc_right:
prec += 1
return prec > precedence[b]
@p7g
p7g / bf.asm
Last active June 14, 2020 15:59
A brainfsck interpreter in x64 assembly (nasm syntax)
global _start
extern getchar
extern putchar
extern fflush
section .data
sys_read equ 0
sys_write equ 1