Skip to content

Instantly share code, notes, and snippets.

@apense
apense / Q.js
Created July 17, 2015 21:54 — forked from guptag/Q.js Examples
//To run Q.js examples:
// 1. Open a new browser tab in Chrome and turn on developer toolbar.
// 2. Copy/Paste this gist in the console and hit enter to run all the snippets.
// Based on the inspiration from samples @ https://github.com/kriskowal/q
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
@apense
apense / punycode.nim
Last active August 29, 2015 14:24
Attempt at Punycode
import strutils
import unicode
const
Base = 36
TMin = 1
TMax = 26
Skew = 38
Damp = 700
InitialBias = 72
@apense
apense / numiter.nim
Created June 23, 2015 18:23
Fibonacci numbers and Factorials as iterators
iterator factorials(k: int): int =
## Yields from 0! to k! as an iterator
var (n, f) = (0, 1)
yield 1 # for 0!
while n < k:
yield f
n = n + 1; f = f * (n + 1)
iterator fibonacci(cap: int): int =
@apense
apense / popcount.nim
Created June 10, 2015 21:28
Bit manipulation with SSE4
import benchmark as bm
proc popcnt(i: int): int =
# this doesn't check if the instruction exists!
asm """
popcnt %%rbx, %%rax
:"=a"(`result`)
:"b"(`i`)
"""
@apense
apense / m128d.nim
Created June 6, 2015 00:45
FMA intrinsics with Nim
{.passC: "-march=native".}
type m128d {.importc: "__m128d", nodecl.} = object
proc fma(x,y,z: float32): float32 {.importc: "fma", header: "<math.h>".}
proc fma(x,y,z: float64): float64 {.importc: "fmaf", header: "<math.h>".}
proc fmadd(x,y,z: m128d): m128d {.importc: "_mm_fmadd_sd", header: "<intrin.h>".}
proc loadpd(x: pointer): m128d {.importc: "_mm_load_pd", header: "<intrin.h>".}
converter tom128d(f: float): m128d =
@apense
apense / math128.nim
Created May 6, 2015 20:35
Doing 128-bit math in Nim
## NOTICE: I have no idea how this works on most systems. it will eat your family
# these probably don't work right
{.emit: """#ifndef __float128
#define __float128 long double
#define __int128 long long
#endif""".}
type float128* {.importc: "__float128", nodecl.} = clongdouble
type int128* {.importc: "__int128", nodecl.} = clonglong
@apense
apense / random_fill.nim
Created April 5, 2015 23:05
Importing Windows functions, casting, and using pointers. i.e., ugly Nim
import windows
when defined(windows):
type HCRYPTPROV* = ptr int # ULONG_PTR typedef
const PROV_RSA_FULL* = DWORD(1)
const CRYPT_VERIFYCONTEXT* = DWORD(0xf0000000)
proc CryptAcquireContextA(phProv: ptr HCRYPTPROV, pszContainer, pszProvider: LPCTSTR,
dwProvType, dwFlags: DWORD): WINBOOL {.stdcall, dynlib: "AdvApi32.dll", importc: "CryptAcquireContextA".}
proc CryptAcquireContextW(phProv: ptr HCRYPTPROV, pszContainer, pszProvider: LPCTSTR,