Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created November 14, 2024 14:00
Show Gist options
  • Save ufcpp/ae6188c21da203c71eab55037c1ef13f to your computer and use it in GitHub Desktop.
Save ufcpp/ae6188c21da203c71eab55037c1ef13f to your computer and use it in GitHub Desktop.
Interceptors こんなのなら割と実用的かなぁ
namespace ConsoleApp1
{
using System.Runtime.CompilerServices;
file class Gen
{
[InterceptsLocation(@"F:\src\ConsoleApp1\ConsoleApp1\Program.cs", 1, 16)]
public static ReadOnlySpan<byte> M1(string _) => [1, 2, 3, 10, 11, 12, 100, 200, 255];
[InterceptsLocation(@"F:\src\ConsoleApp1\ConsoleApp1\Program.cs", 2, 16)]
public static ReadOnlySpan<byte> M2(string _) => [0x83, 0x01, 0x01, 0x02, 0xC3, 0x61, 0x62, 0x63, 0x03, 0xA2, 0xFF, 0x00];
}
}
namespace System.Runtime.CompilerServices
{
[Diagnostics.Conditional("CompileTimeOnly")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
file sealed class InterceptsLocationAttribute : Attribute
{
public InterceptsLocationAttribute(string path, int lineNumber, int columnNumber)
{
_ = path;
_ = lineNumber;
_ = columnNumber;
}
}
}
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
internal class Binary
{
public static ReadOnlySpan<byte> Dec([ConstantExpected] string value) => Parse(value, NumberStyles.Integer);
public static ReadOnlySpan<byte> Hex([ConstantExpected] string value) => Parse(value, NumberStyles.HexNumber);
private static ReadOnlySpan<byte> Parse(string value, NumberStyles style)
{
var s = value.AsSpan();
var list = new List<byte>();
foreach (var range in s.Split(' '))
{
var span = s[range];
if (span.IsEmpty) continue;
list.Add(byte.Parse(span, style, CultureInfo.InvariantCulture));
}
return list.ToArray();
}
}
var d = Binary.Dec("1 2 3 10 11 12 100 200 255");
var h = Binary.Hex("83 01 01 02 C3 61 62 63 03 A2 FF 00");
foreach (var i in d) Console.WriteLine(i);
foreach (var i in h) Console.WriteLine(i);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment