Skip to content

Instantly share code, notes, and snippets.

View MiloszKrajewski's full-sized avatar

Milosz Krajewski MiloszKrajewski

  • Cambridge, UK
View GitHub Profile
@MiloszKrajewski
MiloszKrajewski / Template.cs
Created May 20, 2024 10:56
Minimal templating engine
/// <summary>
/// Minimal templating engine allowing for <c>{variable}</c> expansions which is more useful than
/// <see cref="M:String.Format()"/>'s <c>{0}</c>. The difference between this and string
/// interpolation is the fact that it can be done on user strings, not only on precompiled ones.
/// </summary>
public static partial class Template
{
// Prevents circular expansion, allowing quite deep nesting at the same time.
private const int MaximumExpansionDepth = 1024;
@MiloszKrajewski
MiloszKrajewski / MiniJsonWriter.cs
Created April 23, 2023 09:53
When you need to create JSON but don't want to use any particular library
using System;
using System.Collections.Generic;
using System.Text;
internal static class StringBuilderExtensions
{
public static StringBuilder AppendJNull(this StringBuilder builder) =>
builder.Append("null");
public static StringBuilder AppendJNumber(this StringBuilder builder, double value) =>
class UnpackTest
{
byte[] _source;
byte[] _target;
public UnpackTest()
{
int size = 1000 * Vector128<byte>.Count;
var source = new byte[size];
var target = new byte[size * 2];
// * stackalloc does not work, we need pool as consumer is async so it needs Memory not Span
// * this might be most likley overcomplicated and ArrayBufferWriter could be enough,
// but it really tries to abuse the chance that read chunks are very small so there is
// only one rent from pool and one alloc for final result
// * these 3 methods could be a struct nicely encapsulating functionality but it is used
// from async method so struct would be copied all the time
// * these 3 methods could be a class, but I would like to limit allocation to minimum,
// so it uses `ref` arguments to delegate `state` to caller and allow keeping it on stack
static async ValueTask<ReadOnlyMemory<byte>> ReceiveStringAsync(WebSocket socket, CancellationToken ct = default)
@MiloszKrajewski
MiloszKrajewski / antlr4.ps1
Last active February 9, 2024 12:04
Bootstrap script for ANTLR 4
$dp0 = $PSScriptRoot
$version = '4.13.1'
$jar = "antlr-$version-complete.jar"
$url = "https://www.antlr.org/download/$jar"
if (-not (Test-Path "$dp0/$jar")) {
Invoke-WebRequest -Uri $url -OutFile "$dp0/$jar"
}
using System.Xml.Linq;
namespace K4os.Outbox.Resources;
public class EmbeddedResourceLoader
{
public static Stream GetStream<THook>(string path) =>
typeof(THook).Assembly.GetManifestResourceStream(typeof(THook), path) ??
throw new ArgumentException($"Embedded resource '{path}' not found");
@MiloszKrajewski
MiloszKrajewski / BufferAllocation.cs
Created March 21, 2022 15:59
Byte buffer allocation benchmarks
using System.Buffers;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
namespace MemoryBenchmarks
{
[MemoryDiagnoser]
public class BufferAllocation
{
private static readonly ArrayPool<byte> Pool = ArrayPool<byte>.Shared;
@MiloszKrajewski
MiloszKrajewski / Between.cs
Created October 20, 2020 00:01
Between (C#)
public static string Between(StringBuilder result, string a, string b)
{
if (a == b) return a;
if (Compare(a, b) >= 0)
throw new InvalidOperationException();
var ai = 0;
var bi = 0;
while (true)
@MiloszKrajewski
MiloszKrajewski / TypeExtensions.cs
Last active October 18, 2024 13:42
TypeExtensions
internal static class TypeExtensions
{
/// <summary>
/// Type distance cache. It should Concurrent dictionary but it is not available
/// on all flavors of Portable Class Library.
/// </summary>
private static readonly ConcurrentDictionary<(Type, Type), int> TypeDistanceMap = new();
/// <summary>Checks if child type inherits (or implements) from parent.</summary>
/// <param name="child">The child.</param>
@MiloszKrajewski
MiloszKrajewski / Pool.cs
Created March 15, 2020 15:10
Simple object pool
public class Pool<T>
{
private readonly ConcurrentQueue<T> _queue;
private readonly Func<T> _create;
private readonly Action<T> _reset;
private readonly Action<T> _destroy;
private int _freeSlots;
public Pool(Func<T> create, Action<T> reset, Action<T> destroy, int size)
{