Skip to content

Instantly share code, notes, and snippets.

View CAFxX's full-sized avatar

Carlo Alberto Ferraris CAFxX

View GitHub Profile
@CAFxX
CAFxX / gomaxprocs.go
Last active October 29, 2024 03:15
Lock-free, fast GOMAXPROCS(0)
package xruntime
import (
"runtime"
"sync"
"sync/atomic"
"time"
)
var gmp atomic.Int32
@CAFxX
CAFxX / memchrs.c
Last active October 24, 2024 08:25
memchrs
// https://godbolt.org/z/63Ebd37vz
#include <immintrin.h>
#include <stdint.h>
#include <string.h>
void* memchrs(const void* haystack, int len, const char* needles, int n) {
if (len <= 0 || n <= 0) {
return NULL;
}
@CAFxX
CAFxX / write.go
Created August 26, 2024 06:49
Generic `io.Write`
package io
import (
"iter"
"math"
)
type Writable interface {
~string | ~[]byte | ~byte | ~rune | ~[]rune |
iter.Seq[byte] | iter.Seq[rune] | iter.Seq2[byte, error] | iter.Seq2[rune, error] |
@CAFxX
CAFxX / with_value_func.go
Created August 6, 2024 04:51
context.WithValueFunc(...)
package context
import (
"context"
"sync"
)
func WithValueFunc(ctx context.Context, key any, valFn func() any) context.Context {
return &valFunc{Context: ctx, key: key, valFn: valFn}
}
@CAFxX
CAFxX / textproto.go
Last active September 26, 2023 01:49
textproto.CanonincalMIMEHeaderKey with memoization and GC
package textproto
import (
"net/textproto"
"runtime"
"sync"
)
// CanonincalMIMEHeaderKey is like textproto.CanonicalMIMEHeaderKey but it
// memoizes results to avoid repeated allocations of the same string.
package maps
type ReadMostlyMap[K comparable, V any] struct {
mu sync.Mutex
m atomic.Pointer // map[K]V
}
func map2ptr[K comparable, V any](m map[K]V) unsafe.Pointer {
im := any(m)
return *(*unsafe.Pointer)(unsafe.Pointer(&im))
Verifying that I control the following Nostr public key: npub1j67s9mwffj6ue909esy4ldyhte9xheu5nh2lwed2qycqfdmfjmuq40chpa
@CAFxX
CAFxX / go_wishlist.md
Last active January 24, 2024 00:11
Go wishlist

Language/syntax

Shorthand error definition

Instead of things like var ErrFoo = errors.New("foo") or return fmt.Errorf("foo: %d", n) I would like a shorthand syntax that allows to define a new error type.

Simple error

@CAFxX
CAFxX / bulk_insert.go
Last active December 31, 2022 02:39
SQL bulk insert
package bulkinsert
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
)
@CAFxX
CAFxX / load_data.go
Last active December 29, 2022 06:42
MySQL bulk data loader (via LOAD DATA LOCAL INFILE)
package mysql
import (
"bytes"
"context"
"database/sql"
"encoding/csv"
"errors"
"fmt"
"io"