Skip to content

Instantly share code, notes, and snippets.

@PhilipWitte
PhilipWitte / concepts.nim
Last active March 8, 2023 00:46
How to use concept in Nim
type
CanDance = concept x
dance(x) # `x` is anything that has a `dance` procedure
proc doBallet(dancer: CanDance) =
# `dancer` can be anything that `CanDance`
dance(dancer)
# ---
@PhilipWitte
PhilipWitte / carray.nim
Last active April 5, 2021 14:58
Unchecked Array vs Pointer Arithmatic
type
CArray{.unchecked.}[T] = ptr array[1, T]
type
A = object
items: ptr float
B = object
items: CArray[float]
@PhilipWitte
PhilipWitte / composition.nim
Last active January 28, 2021 10:49
Nim Composition Concept
# Inheritance implies runtime memory overhead, so using it for small things like Particles
# is not ideal even though inheritance (to a Sprite base-type for instance) might be useful.
# We could 'auto compose' types instead as a way to use limited inheritance without it's costs
type
Sprite = object
resource: Image
position: Vector
rotation: Vector
@PhilipWitte
PhilipWitte / bench.c
Last active November 30, 2018 08:21
C Return Benchmark
// INSTRUCTIONS:
// Compile with `gcc -s -O3 -flto -o bench bench.c`
// Run with `./bench 100000 10000`
// IMPORTANT:
// The two parameters are REQUIRED and are the numbers for:
// 1. How many points in the array.
// 2. How many times to cycle through the array.
//
// The numbers are not multiplied to ensure the compiler can't cheat.
@PhilipWitte
PhilipWitte / app.nim
Last active November 7, 2016 07:23
OOP in Nim
{.this: self.}
import syntax
type
Person = object
age: int
name: string
var
boys: seq[Person]
@PhilipWitte
PhilipWitte / app.nim
Last active August 8, 2016 07:24
"Brim" - Nim version of maikklein's 'Breeze' ECS
import brim
# ---
type
Position = object
x, y: float
Velocity = object
import macros
# ---------- ---------- ---------- #
proc hasPragma(procedure:expr, name:string): bool {.compileTime.} =
# checks if a procedure has a specific pragma
let procPragma = procedure[4]#.pragma
for p in procPragma.children:
if p.repr == name:
@PhilipWitte
PhilipWitte / typeid.nim
Created February 21, 2016 11:11
Example of how to get a unique ID per type
import tables
# ---
type ID = int
var nextTypeID {.compileTime.}: ID
proc typeID(T:typedesc): ID =
const id = nextTypeID
@PhilipWitte
PhilipWitte / example.nim
Last active February 8, 2016 15:49
Nim composition "multi-inheritance" auto-dispatch
import macros
# --- --- --- #
type
Base* {.pure inheritable.} = object
Comp* {.pure inheritable.} = object
@PhilipWitte
PhilipWitte / gist:6772348
Last active December 24, 2015 08:39
Nimrod's Times.EpochTime doesn't seem to measure correctly.
import StrUtils, Times
type Vector = tuple[x, y, z, w:float]
proc new(T:typedesc[Vector], x, y, z, w:float): Vector {.noSideEffect, noInit, inline.} =
result.x = x
result.y = y
result.z = z