Skip to content

Instantly share code, notes, and snippets.

View voroninp's full-sized avatar

Pavel Voronin voroninp

View GitHub Profile
@voroninp
voroninp / ExceptionTracker.cs
Last active May 5, 2024 14:22
Exception tracker
/// <summary>
/// Tracks exception which was thrown after instantiation of the tracker.
/// </summary>
/// <remarks>
/// It can be used to get the exception in finally block of try-catch-finally.
/// </remarks>
/// <example>
/// <code>
/// var tracker = new ExceptionTracker();
/// try
@voroninp
voroninp / CatchingExtensionMethod.cs
Last active October 30, 2023 12:53
Yield return inside try catch
public static class EnumerableExtensions
{
/// <summary>
/// Handles the exception and returns either new one (can be same as received) or <c>null</c> - which means exception is handled and should not be
/// thrown. Enumerations ends in any case.
/// </summary>
public static IEnumerable<T> Catching<T, TMoveNextException>(
this IEnumerable<T> seq,
Func<TMoveNextException, Exception?> catchOnMoveNext)
where TMoveNextException : Exception
@voroninp
voroninp / AugmentExceptionWithCurrentActivityId.cs
Created December 15, 2022 11:01
Augment exception with id of current activity.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
namespace Helpers;
public static class ExceptionHelper
{
private const string ActivityIdKey = "ActivityId";
private static readonly object Sync = new();
@voroninp
voroninp / ArrayExtensions.cs
Last active October 30, 2023 13:01
Accessing array elements without bounds check. (from https://stackoverflow.com/a/66962968/921054)
public static class ArrayExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T At<T>(this T[] array, int index)
{
ref T tableRef = ref MemoryMarshal.GetArrayDataReference(array);
return ref Unsafe.Add(ref tableRef, (nint)index);
}
}
public ref struct IndexSet
{
public static int SizeInBytes(uint maxIndex)
{
var indicesCount = maxIndex + 1;
var (size, additionalBits) = ((int)(indicesCount >> 3), indicesCount & 0b111);
if (additionalBits > 0)
{
size++;
}