csharp/1996v/Bssom.Net/Bssom.Serializer/Internal/StackallocBlockProvider.cs

StackallocBlockProvider.cs
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;

namespace Bssom.Serializer.Internal
{
    public static clast StackallocBlockProvider
    {
        internal const string ModuleName = "Bssom.StackallocBlocks";

        private static Dictionary dynamicGenerateBlockTypes;
        internal static readonly DynamicStackallocBlocksastembly Dynamicastembly;

        static StackallocBlockProvider()
        {
            dynamicGenerateBlockTypes = new Dictionary();
            Dynamicastembly = new DynamicStackallocBlocksastembly(ModuleName);
        }

        public static Type GetOrCreateType(int blockSize)
        {
            lock (dynamicGenerateBlockTypes)
            {
                if (!dynamicGenerateBlockTypes.TryGetValue(blockSize, out Type blockType))
                {
                    TypeBuilder blockTypeBuilder = Dynamicastembly.DefineBlockType(blockSize);
                    blockType = blockTypeBuilder.CreateTypeInfo();
                    dynamicGenerateBlockTypes.Add(blockSize, blockType);
                }
                return blockType;
            }
        }

#if NETFRAMEWORK
        public static astemblyBuilder astemblySave()
        {
            return Dynamicastembly.Save();
        }
#endif
    }

    internal static clast StackallocBlockHelper
    {
        public readonly static MethodInfo _WriteUIntMethodInfo = typeof(StackallocBlockHelper).GetMethod(nameof(WriteUInt));

        public static unsafe void WriteUInt(IntPtr ptr, int uintIndex, uint uintValue)
        {
            var uPtr = (uint*)ptr.ToPointer();
            *(uPtr + uintIndex) = uintValue;
        }
    }
}