• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • 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
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
        • FilterEnumerable
        • PollingFilterWatchToken
    • 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
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • 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
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • 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
        • 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

    IGraphComparable

    IGraphComparable is an interface for comparables that can handle cyclic object graphs.

    /// <summary>Graph comparable object. Detects cycles.</summary>
    public interface IGraphComparable
    {
        /// <summary>Is object structure cyclical.</summary>
        [IgnoreDataMember] bool IsCyclical { get; set; }
    
        /// <summary>Compares to <paramref name="obj"/>.</summary>
        /// <param name="obj"></param>
        /// <param name="context">Compare context for tracking already compared pairs</param>
        /// <returns>
        /// Signed interger that indicates relative value to <paramref name="obj"/>. 
        ///     <![CDATA[<0]]> if <paramref name="obj"/> is preceding.
        ///     <![CDATA[>0]]> if <paramref name="obj"/> is trailing.
        ///     <![CDATA[0]]> equals.
        /// </returns>
        int CompareTo(object obj, IGraphComparerContext2 context);
    }
    

    IGraphComparable<T> uses strong type generics.

    /// <summary>Graph comparable obejct. Detects cycles.</summary>
    /// <remarks>
    /// Implementation may be start node distinctive or agnostic. 
    /// If former, then implementation typically uses order specific hashing, e.g. FNV. 
    /// If later, then uses add or xor hashing between objects.
    /// </remarks>
    public interface IGraphComparable<in T>
    {
        /// <summary>Is object structure cyclical.</summary>
        [IgnoreDataMember] bool IsCyclical { get; set; }
    
        /// <summary>Compares to <paramref name="obj"/>.</summary>
        /// <param name="obj"></param>
        /// <param name="context">Compare context for tracking already compared pairs</param>
        /// <returns>
        /// Signed interger that indicates relative value to <paramref name="obj"/>. 
        ///     <![CDATA[<0]]> if <paramref name="obj"/> is preceding.
        ///     <![CDATA[>0]]> if <paramref name="obj"/> is trailing.
        ///     <![CDATA[0]]> equals.
        /// </returns>
        int CompareTo(T? obj, IGraphComparerContext2 context);
    }
    

    IGraphEqualityComparable

    IGraphEqualityComparable is interface for comparables that are aware of cyclic object graphs.

    /// <summary>Graph equality comparable. Detects cycles.</summary>
    public interface IGraphEqualityComparable
    {
        /// <summary>Is object structure cyclical.</summary>
        [IgnoreDataMember] bool IsCyclical { get; set; }
    
        /// <summary>Compares for equality to <paramref name="obj"/>. Detects object cycles.</summary>
        /// <param name="obj"></param>
        /// <param name="context">Compare context</param>
        /// <returns></returns>
        bool EqualTo(object? obj, IGraphComparerContext2 context);
    
        /// <summary>Return a hash code in graph traverse aware request.</summary>
        /// <param name="context">Compare context</param>
        int GetHashCode(IGraphComparerContext context);
    }
    

    IGraphEqualityComparable<T> uses strong type generics.

    /// <summary>Graph equality comparable. Detects cycles.</summary>
    /// <remarks>
    /// Implementation may be start node distinctive or agnostic. 
    /// If former, then implementation typically uses order specific hashing, e.g. FNV. 
    /// If later, then uses add or xor hashing between objects.
    /// </remarks>
    public interface IGraphEqualityComparable<in T>
    {
        /// <summary>Is object structure cyclical.</summary>
        [IgnoreDataMember] bool IsCyclical { get; set; }
    
        /// <summary>Compares for equality to <paramref name="obj"/>. Detects object cycles.</summary>
        /// <param name="obj"></param>
        /// <param name="context">Compare context</param>
        /// <returns></returns>
        bool EqualTo(T? obj, IGraphComparerContext2 context);
    
        /// <summary>Return a hash code in graph traverse aware request.</summary>
        /// <param name="context">Compare context</param>
        int GetHashCode(IGraphComparerContext context);
    }
    

    Implementation

    Example implementation of IGraphComparer<T> and IGraphEqualityComparer<T> to Node class.

    /// <summary>Graph node</summary>
    public class Node : IGraphComparable<Node>, IGraphEqualityComparable<Node>, ICyclical
    {
        /// <summary>Is possibly cyclical node.</summary>
        [IgnoreDataMember] public bool IsCyclical { get => Edges.Count > 0; set { } }
        /// <summary>Id</summary>
        public readonly int Id;
        /// <summary>Forward edges/summary>
        public readonly List<Node> Edges = new List<Node>();
    
        /// <summary>Create node</summary>
        public Node(int id) => Id = id;
    
        /// <summary>Compare order to <paramref name="other"/></summary>
        public int CompareTo(Node? other, IGraphComparerContext2 context)
        {
            // Same reference
            if (this == other) return 0;
            if (other == null) return -1;
            // Is already hashed
            if (!context.Add(this, other)) return 0;
            // Id
            if (Id < other.Id) return -1;
            if (Id > other.Id) return 1;
            // Get edge count
            int c1 = Edges.Count, c2 = other.Edges.Count;
            // Compare edges
            for (int i = 0; i < Math.Min(c1, c2); i++)
            {
                int d = Edges[i].CompareTo(other.Edges[i], context);
                if (d != 0) return d;
            }
            //
            if (c1 < c2) return -1;
            if (c1 > c2) return 1;
            // Equal
            return 0;
        }
    
        /// <summary>Compare equality to <paramref name="other"/>.</summary>
        public bool EqualTo(Node? other, IGraphComparerContext2 context)
        {
            // Same reference
            if (this == other) return true;
            if (other == null) return false;
            // Is already hashed
            if (!context.Add(this, other)) return true;
            // Id
            if (Id != other.Id) return false;
            // Get edge count
            int c1 = Edges.Count, c2 = other.Edges.Count;
            // Count mismatch
            if (c1 != c2) return false;
            // Compare edges
            for (int i = 0; i < Math.Min(c1, c2); i++)
            {
                if (!Edges[i].EqualTo(other.Edges[i], context)) return false;
            }
            // Equal
            return true;
        }
    
        /// <summary>Calculate hash-code</summary>
        public int GetHashCode(IGraphComparerContext context)
        {
            // Is already hashed
            if (!context.Add(this)) return 0;
            // Init
            int hash = unchecked((int)2166136261);
            // Hash in id
            hash ^= unchecked(Id);
            // Hash in edges
            foreach (Node n in Edges) hash = (hash * 16777619) ^ n.GetHashCode(context);
            // Return
            return hash;
        }
    }
    

    Create two cyclic object graphs.

    Cyclic queryCyclic query

    // Create graph 1
    Node graph1_1 = new Node(1);
    Node graph1_2 = new Node(2);
    Node graph1_3 = new Node(3);
    graph1_1.Edges.Add(graph1_2);
    graph1_2.Edges.Add(graph1_3);
    graph1_3.Edges.Add(graph1_1);
    
    // Create graph 2
    Node graph2_1 = new Node(1);
    Node graph2_2 = new Node(2);
    Node graph2_3 = new Node(3);
    graph2_1.Edges.Add(graph2_2);
    graph2_2.Edges.Add(graph2_3);
    graph2_3.Edges.Add(graph2_1);
    

    GraphComparer<T>.Implementation adapts IGraphComparable<T> to both IComparer<T> and IGraphComparer<T>.

    // Create graph comparer
    IComparer<Node> comparer = GraphComparer<Node>.Instance;
    // Compare 
    WriteLine(comparer.Compare(graph1_1, graph2_1)); // 0
    WriteLine(comparer.Compare(graph1_1, graph2_2)); // -1
    

    GraphEqualityComparer<T>.Implementation adapts IGraphEqualityComparable<T> to both IEqualityComparer<T> and IEqualityGraphComparer<T>.

    // Create graph comparer
    IEqualityComparer<Node> equalityComparer = GraphEqualityComparer<Node>.Instance;
    // Compare 
    WriteLine(equalityComparer.Equals(graph1_1, graph2_1)); // True
    WriteLine(equalityComparer.Equals(graph1_1, graph2_2)); // False
    

    Full Example

    Full example
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using Avalanche.Utilities;
    using static System.Console;
    
    class graphcomparable
    {
        public static void Run()
        {
            {
                // <01>
                // Create graph 1
                Node graph1_1 = new Node(1);
                Node graph1_2 = new Node(2);
                Node graph1_3 = new Node(3);
                graph1_1.Edges.Add(graph1_2);
                graph1_2.Edges.Add(graph1_3);
                graph1_3.Edges.Add(graph1_1);
    
                // Create graph 2
                Node graph2_1 = new Node(1);
                Node graph2_2 = new Node(2);
                Node graph2_3 = new Node(3);
                graph2_1.Edges.Add(graph2_2);
                graph2_2.Edges.Add(graph2_3);
                graph2_3.Edges.Add(graph2_1);
                // </01>
    
                // <02>
                // Create graph comparer
                IComparer<Node> comparer = GraphComparer<Node>.Instance;
                // Compare 
                WriteLine(comparer.Compare(graph1_1, graph2_1)); // 0
                WriteLine(comparer.Compare(graph1_1, graph2_2)); // -1
                // </02>
    
                // <03>
                // Create graph comparer
                IEqualityComparer<Node> equalityComparer = GraphEqualityComparer<Node>.Instance;
                // Compare 
                WriteLine(equalityComparer.Equals(graph1_1, graph2_1)); // True
                WriteLine(equalityComparer.Equals(graph1_1, graph2_2)); // False
                // </03>
            }
        }
    
        // <99>
        /// <summary>Graph node</summary>
        public class Node : IGraphComparable<Node>, IGraphEqualityComparable<Node>, ICyclical
        {
            /// <summary>Is possibly cyclical node.</summary>
            [IgnoreDataMember] public bool IsCyclical { get => Edges.Count > 0; set { } }
            /// <summary>Id</summary>
            public readonly int Id;
            /// <summary>Forward edges/summary>
            public readonly List<Node> Edges = new List<Node>();
    
            /// <summary>Create node</summary>
            public Node(int id) => Id = id;
    
            /// <summary>Compare order to <paramref name="other"/></summary>
            public int CompareTo(Node? other, IGraphComparerContext2 context)
            {
                // Same reference
                if (this == other) return 0;
                if (other == null) return -1;
                // Is already hashed
                if (!context.Add(this, other)) return 0;
                // Id
                if (Id < other.Id) return -1;
                if (Id > other.Id) return 1;
                // Get edge count
                int c1 = Edges.Count, c2 = other.Edges.Count;
                // Compare edges
                for (int i = 0; i < Math.Min(c1, c2); i++)
                {
                    int d = Edges[i].CompareTo(other.Edges[i], context);
                    if (d != 0) return d;
                }
                //
                if (c1 < c2) return -1;
                if (c1 > c2) return 1;
                // Equal
                return 0;
            }
    
            /// <summary>Compare equality to <paramref name="other"/>.</summary>
            public bool EqualTo(Node? other, IGraphComparerContext2 context)
            {
                // Same reference
                if (this == other) return true;
                if (other == null) return false;
                // Is already hashed
                if (!context.Add(this, other)) return true;
                // Id
                if (Id != other.Id) return false;
                // Get edge count
                int c1 = Edges.Count, c2 = other.Edges.Count;
                // Count mismatch
                if (c1 != c2) return false;
                // Compare edges
                for (int i = 0; i < Math.Min(c1, c2); i++)
                {
                    if (!Edges[i].EqualTo(other.Edges[i], context)) return false;
                }
                // Equal
                return true;
            }
    
            /// <summary>Calculate hash-code</summary>
            public int GetHashCode(IGraphComparerContext context)
            {
                // Is already hashed
                if (!context.Add(this)) return 0;
                // Init
                int hash = unchecked((int)2166136261);
                // Hash in id
                hash ^= unchecked(Id);
                // Hash in edges
                foreach (Node n in Edges) hash = (hash * 16777619) ^ n.GetHashCode(context);
                // Return
                return hash;
            }
        }
        // </99>
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen