• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IFieldAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • Dto
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IFloatingPointType
      • Dto
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
        • DtoTarget(IDataType)
        • IntermediateTarget
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
        • CustomAttributeUtilities
        • ToStringRequest
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystemBrowse
        • IFileSystemCreateDirectory
        • IFileSystemDelete
        • IFileSystemFileAttribute
        • IFileSystemMount
        • IFileSystemMove
        • IFileSystemObserve
        • IFileSystemOpenStream
        • IFileSystemOpenMemory
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Utilities
        • Dispose
        • FileDictionary
        • FileScanner
        • FilterEnumerable
        • OperationSession
        • PollingFilterWatchToken
        • VisitTree
      • Article
        • Examples
        • PrintTree
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
        • Unicode.CLDR43
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Memory
      • Introduction
      • IMemory<T>
      • BlockMemory<T>
      • FileMemory
      • ListMemory<L, T>
      • MemoryMemory<T>
      • MMFMemory<T>
      • PointerMemory<T>
      • Slice<M, T>
      • StreamMemory
      • Concurrency
        • RWLockedMemory
        • SynchronizedMemory
      • Serialization
        • Benchmarks
        • Fixed<T>
        • Variable<T>
        • ZigZag<T>
        • StringEncoding
      • Articles
        • Fixed-size and Variable-sized
        • IBlockPool<T>
        • Print Tree
        • Read and Write events
        • Stream View
        • Zero Heap
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageDescriptionsBase
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Localization Templates
        • Logging
        • Validation
    • Avalanche.Module
      • Introduction
      • IServiceCollection
      • IServiceBuilder
      • IHostBuilder
      • Dependencies
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Protobuf
      • Introduction
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • ArrayList
        • ArrayUtilities
        • BijectionMap
        • CachedSelect
        • DictionaryAdapter
        • EnumerableExtensions
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • StructList
        • Tuples
        • TupleUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • SharedResource
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Variable-sized memory

    ListMemory<List<T>, T>, BlockMemory<T> and StreamMemory<T> are variable-sized memories.

    IMemory<byte> listMemory = new ListMemory<List<byte>, byte>(new());
    IMemory<byte> blockMemory = new BlockMemory<byte>();
    IMemory<byte> streamMemory = new StreamMemory(new MemoryStream());
    

    The IList.IsFixedSize returns 'False'.

    WriteLine(listMemory.IsFixedSize);      // 'False'
    WriteLine(blockMemory.IsFixedSize);     // 'False'
    WriteLine(streamMemory.IsFixedSize);    // 'False'
    

    Count changing methods, Insert, InsertAt, InsertFrom, InsertElementsAt, RemoveElementsAt, Clear can be used.

    listMemory.Add(item: 10);
    listMemory.Insert(0L, 9);
    listMemory.Count = 5;
    listMemory.Clear();
    

    Fixed-size memory

    ListMemory<T[], T>, MemoryMemory<T>, PointerMemory<T> and MMFMemory<T> are fixed-size memories.

    IMemory<byte> arrayMemory = new ListMemory<byte[], byte>(new byte[50]);
    IMemory<byte> memoryMemory = new MemoryMemory<byte>( (Memory<byte>) new byte[50] );
    
    byte[] data = new byte[50];
    fixed (byte* ptr = data)
    {
        IMemory<byte> pointerMemory = new PointerMemory<byte>(ptr, data.Length);
    }
    using IMemory<byte> mmfMemory = MMFMemory<byte>.CreateNew(null, 50);
    

    The IList.IsFixedSize returns 'True'.

    WriteLine(arrayMemory.IsFixedSize);     // 'True'
    WriteLine(memoryMemory.IsFixedSize);    // 'True'
    WriteLine(mmfMemory.IsFixedSize);       // 'True'
    

    The IList.MaxCount returns allocation count.

    WriteLine(arrayMemory.MaxCount);        // '50'
    WriteLine(memoryMemory.MaxCount);       // '50'
    WriteLine(mmfMemory.MaxCount);          // '4096'
    

    Count changing methods Insert, InsertAt, InsertFrom, InsertElementsAt, RemoveElementsAt, Clear throw NotSupportedException.

    try
    {
        arrayMemory.Add(item: 10);
        arrayMemory.Insert(0L, 9);
        arrayMemory.Count = 5;
        arrayMemory.Clear();
    } catch (NotSupportedException)
    {
        // Cannot add elements to byte[].
    }
    

    Fixed-size to Variable-sized

    Slice<M, T> adapts to variable-sized, up until allocation limit.

    // Create fixed-sized memory
    IMemory<byte> arrayMemory = new ListMemory<byte[], byte>(new byte[50]);
    // Adapt to variable-sized
    IMemory<byte> arrayMemoryAllocation = new Slice<IMemory<byte>, byte>(
        decoree: arrayMemory, 
        offset: 10L, 
        count: 9L, 
        allocation: 20L);
    
    decoree:   ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
    slice:      offset → ▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░          
                         ↑ count ↑                              
                         ↑      allocation           ↑          
    

    Elements can be added up until allocation number of elements.

    WriteLine(arrayMemory.IsFixedSize);            // 'True'
    WriteLine(arrayMemoryAllocation.IsFixedSize);  // 'False'
    WriteLine(arrayMemoryAllocation.Count);        // '9'
    WriteLine(arrayMemoryAllocation.MaxCount);     // '20'
    
    // Modify content
    arrayMemoryAllocation.Add(item: 10);
    arrayMemoryAllocation.Insert(0L, 9);
    arrayMemoryAllocation.Count = 20L;
    arrayMemoryAllocation.Count = 5L;
    
    // Clear
    arrayMemoryAllocation.Clear();
    WriteLine(arrayMemoryAllocation.Count);        // '0'
    WriteLine(arrayMemoryAllocation.MaxCount);     // '20'
    

    Full Example

    Full example
    using Avalanche.Memory;
    using Avalanche.Utilities;
    using static System.Console;
    
    public class sizevariability
    {
        public unsafe static void Run()
        {
            {
                // <01>
                IMemory<byte> listMemory = new ListMemory<List<byte>, byte>(new());
                IMemory<byte> blockMemory = new BlockMemory<byte>();
                IMemory<byte> streamMemory = new StreamMemory(new MemoryStream());
                // </01>
    
                // <02>
                WriteLine(listMemory.IsFixedSize);      // 'False'
                WriteLine(blockMemory.IsFixedSize);     // 'False'
                WriteLine(streamMemory.IsFixedSize);    // 'False'
                // </02>
    
                // <03>
                listMemory.Add(item: 10);
                listMemory.Insert(0L, 9);
                listMemory.Count = 5;
                listMemory.Clear();
                // </03>
            }
            unsafe {
                // <11>
                IMemory<byte> arrayMemory = new ListMemory<byte[], byte>(new byte[50]);
                IMemory<byte> memoryMemory = new MemoryMemory<byte>( (Memory<byte>) new byte[50] );
    
                byte[] data = new byte[50];
                fixed (byte* ptr = data)
                {
                    IMemory<byte> pointerMemory = new PointerMemory<byte>(ptr, data.Length);
                }
                using IMemory<byte> mmfMemory = MMFMemory<byte>.CreateNew(null, 50);
                // </11>
    
                // <12>
                WriteLine(arrayMemory.IsFixedSize);     // 'True'
                WriteLine(memoryMemory.IsFixedSize);    // 'True'
                WriteLine(mmfMemory.IsFixedSize);       // 'True'
                // </12>
    
                // <13>
                WriteLine(arrayMemory.MaxCount);        // '50'
                WriteLine(memoryMemory.MaxCount);       // '50'
                WriteLine(mmfMemory.MaxCount);          // '4096'
                // </13>
    
                // <14>
                try
                {
                    arrayMemory.Add(item: 10);
                    arrayMemory.Insert(0L, 9);
                    arrayMemory.Count = 5;
                    arrayMemory.Clear();
                } catch (NotSupportedException)
                {
                    // Cannot add elements to byte[].
                }
                // </14>
            }
            {
                // <21>
                // Create fixed-sized memory
                IMemory<byte> arrayMemory = new ListMemory<byte[], byte>(new byte[50]);
                // Adapt to variable-sized
                IMemory<byte> arrayMemoryAllocation = new Slice<IMemory<byte>, byte>(
                    decoree: arrayMemory, 
                    offset: 10L, 
                    count: 9L, 
                    allocation: 20L);
                // </21>
    
                // <22>
                WriteLine(arrayMemory.IsFixedSize);            // 'True'
                WriteLine(arrayMemoryAllocation.IsFixedSize);  // 'False'
                WriteLine(arrayMemoryAllocation.Count);        // '9'
                WriteLine(arrayMemoryAllocation.MaxCount);     // '20'
    
                // Modify content
                arrayMemoryAllocation.Add(item: 10);
                arrayMemoryAllocation.Insert(0L, 9);
                arrayMemoryAllocation.Count = 20L;
                arrayMemoryAllocation.Count = 5L;
    
                // Clear
                arrayMemoryAllocation.Clear();
                WriteLine(arrayMemoryAllocation.Count);        // '0'
                WriteLine(arrayMemoryAllocation.MaxCount);     // '20'
                // </22>
            }
        }
    }
    
    In This Article
    Back to top