Skip to content

Instantly share code, notes, and snippets.

using System;
using System.Threading.Tasks;
public static class TaskExtensions
{
public delegate void ExceptionCallback(Exception exception);
public delegate void CompleteCallback<in T>(T result);
public delegate void CompleteCallback();
public static Task<T> WithResult<T>(this Task task, Func<Task, T> func) =>
@Sl4vP0weR
Sl4vP0weR / ConvertibleExtension.cs
Created January 6, 2022 21:50
Extension that allows you to convert IConvertible by generic
public static T To<T>(this IConvertible convertible)
where T : IConvertible
{
if (convertible is null)
return default;
var convertMethod = typeof(IConvertible).GetMethod($"To{typeof(T).Name}");
if (convertMethod is null)
throw new ArgumentException($"{convertible.GetType().Name} can't be converted to {typeof(T).Name}");
var value = convertMethod.Invoke(convertible, new object[] { null });
return (T)value;
@Sl4vP0weR
Sl4vP0weR / TimeSince.cs
Last active November 21, 2021 18:07
Time since a certain period
public struct TimeSince
{
public TimeSince(DateTime? from = default)
{
From = from.HasValue ? from.Value : DateTime.Now;
}
readonly DateTime From;
public static implicit operator float(TimeSince @this) => (float)((TimeSpan)@this).TotalSeconds;
public static implicit operator TimeSince(float @this) => new TimeSince(DateTime.Now.AddSeconds(@this));
@Sl4vP0weR
Sl4vP0weR / LazyFileStream.cs
Last active May 9, 2022 08:21
FileStream that not consuming too much memory to read/write.
/// <summary>
/// FileStream that not consuming too much memory to read/write.
/// </summary>
public class LazyFileStream :
FileStream, IDisposable
{
public LazyFileStream(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.ReadWrite, int buffer = 4096, FileOptions options = FileOptions.SequentialScan | FileOptions.Asynchronous) : base(path, mode, access, share, buffer, options)
{ }
public void Write(byte[] data, int offset = 0)
@Sl4vP0weR
Sl4vP0weR / FieldDelegator.cs
Last active May 18, 2021 06:13
FieldDelegator
public class FieldDelegator<T> : FieldDelegator where T : Delegate
{
public FieldDelegator(FieldInfo field, object owner = null) : base(field, owner) { }
public static void Do(FieldInfo fld, object owner = null, T del = null, bool combine = true) =>
FieldDelegator.Do(fld, owner, del, combine);
public void Do(T del, bool combine = true) => Do(Instance, Owner, del, combine);
}
public class FieldDelegator
{
@Sl4vP0weR
Sl4vP0weR / NetMessagesAccessor.cs
Created April 21, 2021 09:13
Unturned NetMessages accessor
public static class NetMessagesAccessor
{
static Type netMessages = Assembly.GetAssembly(typeof(Provider)).GetType("SDG.Unturned.NetMessages");
public static Delegate ConvertDelegate(Delegate del) =>
Delegate.CreateDelegate(
netMessages.GetNestedType(del.GetType().Name),
del.Target,
del.Method
);
public delegate void ClientWriteHandler(NetPakWriter writer);