public void SerializeStack()
        {
            ImmutableStack <string> l = ImmutableStack.CreateRange(new List <string>
            {
                "One",
                "II",
                "3"
            });

            string json = JsonConvert.SerializeObject(l, Formatting.Indented);

            Assert.AreEqual(@"[
  ""3"",
  ""II"",
  ""One""
]", json);
        }
        public async Task WritePrimitiveIImmutableStackT()
        {
            IImmutableStack <int> input = ImmutableStack.CreateRange(new List <int> {
                1, 2
            });

            string json = await Serializer.SerializeWrapper(input);

            Assert.Equal("[2,1]", json);

            StringIImmutableStackWrapper input2 = new StringIImmutableStackWrapper(new List <string> {
                "1", "2"
            });

            json = await Serializer.SerializeWrapper(input2);

            Assert.Equal(@"[""2"",""1""]", json);
        }
Beispiel #3
0
        private static GameEvent ExchangeDeadCard(GameState state, int playerIdx, Card deadCard)
        {
            if (playerIdx == -1)
            {
                throw new ExchangeDeadCardFailedException(ExchangeDeadCardError.PlayerIsNotInGame);
            }

            var playerId = state.PlayerIdByIdx[playerIdx];

            if (!playerId.Equals(state.CurrentPlayerId))
            {
                throw new ExchangeDeadCardFailedException(ExchangeDeadCardError.PlayerIsNotCurrentPlayer);
            }

            if (!state.PlayerHandByIdx[playerIdx].Contains(deadCard))
            {
                throw new ExchangeDeadCardFailedException(ExchangeDeadCardError.PlayerDoesNotHaveCard);
            }

            if (!state.DeadCards.Contains(deadCard))
            {
                throw new ExchangeDeadCardFailedException(ExchangeDeadCardError.CardIsNotDead);
            }

            if (state.HasExchangedDeadCard)
            {
                throw new ExchangeDeadCardFailedException(ExchangeDeadCardError.PlayerHasAlreadyExchangedDeadCard);
            }

            var deck = ImmutableStack.CreateRange(state.Deck);

            return(new GameEvent
            {
                ByPlayerId = playerId,
                CardDrawn = deck.Peek(),
                CardUsed = deadCard,
                Coord = new Coord(-1, -1),
                Index = state.Version + 1,
                NextPlayerId = playerId,
                Sequences = Array.Empty <Seq>(),
            });
        }
Beispiel #4
0
        public void CanSerializeImmutableCollectionsReferencedThroughInterfaceInFields()
        {
            var expected = new TestClass(
                dictionary: ImmutableDictionary.CreateRange(new[]
            {
                new KeyValuePair <int, int>(2, 1),
                new KeyValuePair <int, int>(3, 2),
            }),
                list: ImmutableList.CreateRange(new[] { "c", "d" }),
                queue: ImmutableQueue.CreateRange(new[] { "e", "f" }),
                sortedSet: ImmutableSortedSet.CreateRange(new[] { "g", "h" }),
                hashSet: ImmutableHashSet.CreateRange(new[] { "i", "j" }),
                stack: ImmutableStack.CreateRange(new[] { "k", "l" }));

            Serialize(expected);
            Reset();
            var actual = Deserialize <TestClass>();

            Assert.Equal(expected, actual);
        }
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            DelegateDirective?delegateDirective = context.Field
                                                  .Directives[DirectiveNames.Delegate]
                                                  .FirstOrDefault()?.ToObject <DelegateDirective>();

            if (delegateDirective != null)
            {
                IImmutableStack <SelectionPathComponent> path;
                IImmutableStack <SelectionPathComponent> reversePath;

                if (delegateDirective.Path is null)
                {
                    path        = ImmutableStack <SelectionPathComponent> .Empty;
                    reversePath = ImmutableStack <SelectionPathComponent> .Empty;
                }
                else
                {
                    path        = SelectionPathParser.Parse(delegateDirective.Path);
                    reversePath = ImmutableStack.CreateRange(path);
                }

                IReadOnlyQueryRequest request =
                    CreateQuery(context, delegateDirective.Schema, path, reversePath);

                IReadOnlyQueryResult result = await ExecuteQueryAsync(
                    context, request, delegateDirective.Schema)
                                              .ConfigureAwait(false);

                UpdateContextData(context, result, delegateDirective);

                object?value = ExtractData(result.Data, reversePath, context.ResponseName);
                context.Result = new SerializedData(value);
                if (result.Errors is not null)
                {
                    ReportErrors(delegateDirective.Schema, context, result.Errors);
                }
            }

            await _next.Invoke(context).ConfigureAwait(false);
        }
        public void Create()
        {
            ImmutableStack <int> queue = ImmutableStack.Create <int>();

            Assert.True(queue.IsEmpty);

            queue = ImmutableStack.Create(1);
            Assert.False(queue.IsEmpty);
            Assert.Equal(new[] { 1 }, queue);

            queue = ImmutableStack.Create(1, 2);
            Assert.False(queue.IsEmpty);
            Assert.Equal(new[] { 2, 1 }, queue);

            queue = ImmutableStack.CreateRange((IEnumerable <int>) new[] { 1, 2 });
            Assert.False(queue.IsEmpty);
            Assert.Equal(new[] { 2, 1 }, queue);

            Assert.Throws <ArgumentNullException>(() => ImmutableStack.CreateRange((IEnumerable <int>)null));
            Assert.Throws <ArgumentNullException>(() => ImmutableStack.Create((int[])null));
        }
        public void Create()
        {
            ImmutableStack <int> stack = ImmutableStack.Create <int>();

            Assert.True(stack.IsEmpty);

            stack = ImmutableStack.Create(1);
            Assert.False(stack.IsEmpty);
            Assert.Equal(new[] { 1 }, stack);

            stack = ImmutableStack.Create(1, 2);
            Assert.False(stack.IsEmpty);
            Assert.Equal(new[] { 2, 1 }, stack);

            stack = ImmutableStack.CreateRange((IEnumerable <int>) new[] { 1, 2 });
            Assert.False(stack.IsEmpty);
            Assert.Equal(new[] { 2, 1 }, stack);

            Assert.Throws <ArgumentNullException>("items", () => ImmutableStack.CreateRange((IEnumerable <int>)null));
            Assert.Throws <ArgumentNullException>("items", () => ImmutableStack.Create((int[])null));
        }
Beispiel #8
0
 private static object GetPopulatedCollection <TElement>(Type type, int stringLength)
 {
     if (type == typeof(TElement[]))
     {
         return(GetArr_TypedElements <TElement>(stringLength));
     }
     else if (type == typeof(ImmutableList <TElement>))
     {
         return(ImmutableList.CreateRange(GetArr_TypedElements <TElement>(stringLength)));
     }
     else if (type == typeof(ImmutableStack <TElement>))
     {
         return(ImmutableStack.CreateRange(GetArr_TypedElements <TElement>(stringLength)));
     }
     else if (type == typeof(ImmutableDictionary <string, TElement>))
     {
         return(ImmutableDictionary.CreateRange(GetDict_TypedElements <TElement>(stringLength)));
     }
     else if (type == typeof(KeyValuePair <TElement, TElement>))
     {
         TElement item = GetCollectionElement <TElement>(stringLength);
         return(new KeyValuePair <TElement, TElement>(item, item));
     }
     else if (
         typeof(IDictionary <string, TElement>).IsAssignableFrom(type) ||
         typeof(IReadOnlyDictionary <string, TElement>).IsAssignableFrom(type) ||
         typeof(IDictionary).IsAssignableFrom(type))
     {
         return(Activator.CreateInstance(type, new object[] { GetDict_TypedElements <TElement>(stringLength) }));
     }
     else if (typeof(IEnumerable <TElement>).IsAssignableFrom(type))
     {
         return(Activator.CreateInstance(type, new object[] { GetArr_TypedElements <TElement>(stringLength) }));
     }
     else
     {
         return(Activator.CreateInstance(type, new object[] { GetArr_BoxedElements <TElement>(stringLength) }));
     }
 }
Beispiel #9
0
 private static object GetEmptyCollection <TElement>(Type type)
 {
     if (type == typeof(TElement[]))
     {
         return(Array.Empty <TElement>());
     }
     else if (type == typeof(ImmutableList <TElement>))
     {
         return(ImmutableList.CreateRange(Array.Empty <TElement>()));
     }
     else if (type == typeof(ImmutableStack <TElement>))
     {
         return(ImmutableStack.CreateRange(Array.Empty <TElement>()));
     }
     else if (type == typeof(ImmutableDictionary <string, TElement>))
     {
         return(ImmutableDictionary.CreateRange(new Dictionary <string, TElement>()));
     }
     else
     {
         return(Activator.CreateInstance(type));
     }
 }
Beispiel #10
0
        public void CanSerializeImmutableStack()
        {
            var expected = ImmutableStack.CreateRange(new[]
            {
                new Something
                {
                    BoolProp = true,
                    Else     = new Else
                    {
                        Name = "Yoho"
                    },
                    Int32Prop  = 999,
                    StringProp = "Yesbox!"
                },
                new Something(),
                new Something()
            });

            Serialize(expected);
            Reset();
            var actual = Deserialize <ImmutableStack <Something> >();

            Assert.Equal(expected.ToList(), actual.ToList());
        }
 public StringIImmutableStackWrapper(List <string> items)
 {
     _stack = ImmutableStack.CreateRange(items);
 }
        public static CompositionConfiguration Create(ComposableCatalog catalog)
        {
            Requires.NotNull(catalog, nameof(catalog));

            // We consider all the parts in the catalog, plus the specially synthesized ones
            // that should always be applied.
            var customizedCatalog = catalog.AddParts(AlwaysBundledParts);

            // Construct our part builders, initialized with all their imports satisfied.
            // We explicitly use reference equality because ComposablePartDefinition.Equals is too slow, and unnecessary for this.
            var partBuilders = new Dictionary <ComposablePartDefinition, PartBuilder>(ReferenceEquality <ComposablePartDefinition> .Default);

            foreach (ComposablePartDefinition partDefinition in customizedCatalog.Parts)
            {
                var satisfyingImports = partDefinition.Imports.ToImmutableDictionary(i => i, i => customizedCatalog.GetExports(i.ImportDefinition));
                partBuilders.Add(partDefinition, new PartBuilder(partDefinition, satisfyingImports));
            }

            // Create a lookup table that gets all immediate importers for each part.
            foreach (PartBuilder partBuilder in partBuilders.Values)
            {
                // We want to understand who imports each part so we can properly propagate sharing boundaries
                // for MEFv1 attributed parts. ExportFactory's that create sharing boundaries are an exception
                // because if a part has a factory that creates new sharing boundaries, the requirement for
                // that sharing boundary of the child scope shouldn't be interpreted as a requirement for that
                // same boundary by the parent part.
                // However, if the ExportFactory does not create sharing boundaries, it does in fact need all
                // the same sharing boundaries as the parts it constructs.
                var importedPartsExcludingFactoriesWithSharingBoundaries =
                    (from entry in partBuilder.SatisfyingExports
                     where !entry.Key.IsExportFactory || entry.Key.ImportDefinition.ExportFactorySharingBoundaries.Count == 0
                     from export in entry.Value
                     select export.PartDefinition).Distinct(ReferenceEquality <ComposablePartDefinition> .Default);
                foreach (var importedPartDefinition in importedPartsExcludingFactoriesWithSharingBoundaries)
                {
                    var importedPartBuilder = partBuilders[importedPartDefinition];
                    importedPartBuilder.ReportImportingPart(partBuilder);
                }
            }

            // Propagate sharing boundaries defined on parts to all importers (transitive closure).
            foreach (PartBuilder partBuilder in partBuilders.Values)
            {
                partBuilder.ApplySharingBoundary();
            }

            var sharingBoundaryOverrides = ComputeInferredSharingBoundaries(partBuilders.Values);

            // Build up our set of composed parts.
            var partsBuilder = ImmutableHashSet.CreateBuilder <ComposedPart>();

            foreach (var partBuilder in partBuilders.Values)
            {
                var composedPart = new ComposedPart(partBuilder.PartDefinition, partBuilder.SatisfyingExports, partBuilder.RequiredSharingBoundaries.ToImmutableHashSet());
                partsBuilder.Add(composedPart);
            }

            var parts = partsBuilder.ToImmutable();

            // Determine which metadata views to use for each applicable import.
            var metadataViewsAndProviders = GetMetadataViewProvidersMap(customizedCatalog);

            // Validate configuration.
            var errors = new List <ComposedPartDiagnostic>();

            foreach (var part in parts)
            {
                errors.AddRange(part.Validate(metadataViewsAndProviders));
            }

            // Detect loops of all non-shared parts.
            errors.AddRange(FindLoops(parts));

            // If errors are found, re-validate the salvaged parts in case there are parts whose dependencies are affected by the initial errors
            if (errors.Count > 0)
            {
                // Set salvaged parts to current catalog in case there are no errors
                var salvagedParts           = parts;
                var salvagedPartDefinitions = catalog.Parts;

                List <ComposedPartDiagnostic> previousErrors = errors;
                Stack <IReadOnlyCollection <ComposedPartDiagnostic> > stackedErrors = new Stack <IReadOnlyCollection <ComposedPartDiagnostic> >();

                // While we still find errors we validate the exports so that we remove all dependency failures
                while (previousErrors.Count > 0)
                {
                    stackedErrors.Push(previousErrors);

                    // Get the salvaged parts
                    var invalidParts = previousErrors.SelectMany(error => error.Parts).ToList();

                    if (invalidParts.Count == 0)
                    {
                        // If we can't identify the faulty parts but we still have errors, we have to just throw.
                        throw new CompositionFailedException(Strings.FailStableComposition, ImmutableStack.Create <IReadOnlyCollection <ComposedPartDiagnostic> >(errors));
                    }

                    salvagedParts = salvagedParts.Except(invalidParts);
                    var invalidPartDefinitionsSet = new HashSet <ComposablePartDefinition>(invalidParts.Select(p => p.Definition));
                    salvagedPartDefinitions = salvagedPartDefinitions.Except(invalidPartDefinitionsSet);

                    // Empty the list so that we create a new one only with the new set of errors
                    previousErrors = new List <ComposedPartDiagnostic>();

                    foreach (var part in salvagedParts)
                    {
                        previousErrors.AddRange(part.RemoveSatisfyingExports(invalidPartDefinitionsSet));
                    }
                }

                var finalCatalog = ComposableCatalog.Create(catalog.Resolver).AddParts(salvagedPartDefinitions);

                // We want the first found errors to come out of the stack first, so we need to invert the current stack.
                var compositionErrors = ImmutableStack.CreateRange(stackedErrors);

                var configuration = new CompositionConfiguration(
                    finalCatalog,
                    salvagedParts,
                    metadataViewsAndProviders,
                    compositionErrors,
                    sharingBoundaryOverrides);

                return(configuration);
            }

            return(new CompositionConfiguration(
                       catalog,
                       parts,
                       metadataViewsAndProviders,
                       ImmutableStack <IReadOnlyCollection <ComposedPartDiagnostic> > .Empty,
                       sharingBoundaryOverrides));
        }
        public override void Initialize()
        {
            base.Initialize();

            MyInt16Array        = new short[] { 1 };
            MyInt32Array        = new int[] { 2 };
            MyInt64Array        = new long[] { 3 };
            MyUInt16Array       = new ushort[] { 4 };
            MyUInt32Array       = new uint[] { 5 };
            MyUInt64Array       = new ulong[] { 6 };
            MyByteArray         = new byte[] { 7 };
            MySByteArray        = new sbyte[] { 8 };
            MyCharArray         = new char[] { 'a' };
            MyStringArray       = new string[] { "Hello" };
            MyBooleanTrueArray  = new bool[] { true };
            MyBooleanFalseArray = new bool[] { false };
            MySingleArray       = new float[] { 1.1f };
            MyDoubleArray       = new double[] { 2.2d };
            MyDecimalArray      = new decimal[] { 3.3m };
            MyDateTimeArray     = new DateTime[] { new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc) };
            MyEnumArray         = new SampleEnum[] { SampleEnum.Two };

            MyStringList = new List <string>()
            {
                "Hello"
            };
            MyStringIEnumerableT         = new string[] { "Hello" };
            MyStringIListT               = new string[] { "Hello" };
            MyStringICollectionT         = new string[] { "Hello" };
            MyStringIReadOnlyCollectionT = new string[] { "Hello" };
            MyStringIReadOnlyListT       = new string[] { "Hello" };

            MyStringToStringDict = new Dictionary <string, string> {
                { "key", "value" }
            };
            MyStringToStringIDict = new Dictionary <string, string> {
                { "key", "value" }
            };
            MyStringToStringIReadOnlyDict = new Dictionary <string, string> {
                { "key", "value" }
            };

            MyStringToStringImmutableDict       = ImmutableDictionary.CreateRange((Dictionary <string, string>)MyStringToStringDict);
            MyStringToStringIImmutableDict      = ImmutableDictionary.CreateRange((Dictionary <string, string>)MyStringToStringDict);
            MyStringToStringImmutableSortedDict = ImmutableSortedDictionary.CreateRange((Dictionary <string, string>)MyStringToStringDict);

            MyStringStackT = new Stack <string>(new List <string>()
            {
                "Hello", "World"
            });
            MyStringQueueT = new Queue <string>(new List <string>()
            {
                "Hello", "World"
            });
            MyStringHashSetT = new HashSet <string>(new List <string>()
            {
                "Hello"
            });
            MyStringLinkedListT = new LinkedList <string>(new List <string>()
            {
                "Hello"
            });
            MyStringSortedSetT = new SortedSet <string>(new List <string>()
            {
                "Hello"
            });

            MyStringIImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableHashSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutablQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableSortedSetT = ImmutableSortedSet.CreateRange(new List <string> {
                "Hello"
            });
        }
Beispiel #14
0
        public static void ArrayAsRootObject()
        {
            const string ExpectedJson         = @"[1,true,{""City"":""MyCity""},null,""foo""]";
            const string ReversedExpectedJson = @"[""foo"",null,{""City"":""MyCity""},true,1]";

            string[] expectedObjects = { @"""foo""", @"null", @"{""City"":""MyCity""}", @"true", @"1" };

            var address = new Address();

            address.Initialize();

            var    array = new object[] { 1, true, address, null, "foo" };
            string json  = JsonSerializer.Serialize(array);

            Assert.Equal(ExpectedJson, json);

            var dictionary = new Dictionary <string, string> {
                { "City", "MyCity" }
            };
            var arrayWithDictionary = new object[] { 1, true, dictionary, null, "foo" };

            json = JsonSerializer.Serialize(arrayWithDictionary);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(array);
            Assert.Equal(ExpectedJson, json);

            List <object> list = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(list);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(list);
            Assert.Equal(ExpectedJson, json);

            IEnumerable ienumerable = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(ienumerable);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(ienumerable);
            Assert.Equal(ExpectedJson, json);

            IList ilist = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(ilist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(ilist);
            Assert.Equal(ExpectedJson, json);

            ICollection icollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(icollection);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(icollection);
            Assert.Equal(ExpectedJson, json);

            IEnumerable <object> genericIEnumerable = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIEnumerable);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIEnumerable);
            Assert.Equal(ExpectedJson, json);

            IList <object> genericIList = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIList);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIList);
            Assert.Equal(ExpectedJson, json);

            ICollection <object> genericICollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericICollection);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericICollection);
            Assert.Equal(ExpectedJson, json);

            IReadOnlyCollection <object> genericIReadOnlyCollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIReadOnlyCollection);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIReadOnlyCollection);
            Assert.Equal(ExpectedJson, json);

            IReadOnlyList <object> genericIReadonlyList = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIReadonlyList);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIReadonlyList);
            Assert.Equal(ExpectedJson, json);

            ISet <object> iset = new HashSet <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(iset);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iset);
            Assert.Equal(ExpectedJson, json);

            Stack <object> stack = new Stack <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(stack);
            Assert.Equal(ReversedExpectedJson, json);

            json = JsonSerializer.Serialize <object>(stack);
            Assert.Equal(ReversedExpectedJson, json);

            Queue <object> queue = new Queue <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(queue);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(queue);
            Assert.Equal(ExpectedJson, json);

            HashSet <object> hashset = new HashSet <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(hashset);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(hashset);
            Assert.Equal(ExpectedJson, json);

            LinkedList <object> linkedlist = new LinkedList <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(linkedlist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(linkedlist);
            Assert.Equal(ExpectedJson, json);

            ImmutableArray <object> immutablearray = ImmutableArray.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablearray);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablearray);
            Assert.Equal(ExpectedJson, json);

            IImmutableList <object> iimmutablelist = ImmutableList.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutablelist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iimmutablelist);
            Assert.Equal(ExpectedJson, json);

            IImmutableStack <object> iimmutablestack = ImmutableStack.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iimmutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            IImmutableQueue <object> iimmutablequeue = ImmutableQueue.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutablequeue);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iimmutablequeue);
            Assert.Equal(ExpectedJson, json);

            IImmutableSet <object> iimmutableset = ImmutableHashSet.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutableset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            json = JsonSerializer.Serialize <object>(iimmutableset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            ImmutableHashSet <object> immutablehashset = ImmutableHashSet.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablehashset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            json = JsonSerializer.Serialize <object>(immutablehashset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            ImmutableList <object> immutablelist = ImmutableList.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablelist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablelist);
            Assert.Equal(ExpectedJson, json);

            ImmutableStack <object> immutablestack = ImmutableStack.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            ImmutableQueue <object> immutablequeue = ImmutableQueue.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablequeue);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablequeue);
            Assert.Equal(ExpectedJson, json);
        }
Beispiel #15
0
 protected override IImmutableStack <T> Complete(T[] intermediateCollection)
 {
     return(ImmutableStack.CreateRange(intermediateCollection));
 }
Beispiel #16
0
        public void Initialize()
        {
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyIImmutableList = ImmutableList.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyIImmutableStack = ImmutableStack.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyIImmutableQueue = ImmutableQueue.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyIImmutableSet = ImmutableHashSet.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyImmutableHashSet = ImmutableHashSet.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyImmutableList = ImmutableList.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyImmutableStack = ImmutableStack.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
            {
                SimpleTestClass obj1 = new SimpleTestClass();
                obj1.Initialize();

                SimpleTestClass obj2 = new SimpleTestClass();
                obj2.Initialize();

                MyImmutableQueue = ImmutableQueue.CreateRange(new List <SimpleTestClass> {
                    obj1, obj2
                });
            }
        }
Beispiel #17
0
        public ObjectWithObjectProperties()
        {
            Address = new Address();
            ((Address)Address).Initialize();

            List = new List <string> {
                "Hello", "World"
            };
            Array       = new string[] { "Hello", "Again" };
            IEnumerable = new List <string> {
                "Hello", "World"
            };
            IList = new List <string> {
                "Hello", "World"
            };
            ICollection = new List <string> {
                "Hello", "World"
            };
            IEnumerableT = new List <string> {
                "Hello", "World"
            };
            IListT = new List <string> {
                "Hello", "World"
            };
            ICollectionT = new List <string> {
                "Hello", "World"
            };
            IReadOnlyCollectionT = new List <string> {
                "Hello", "World"
            };
            IReadOnlyListT = new List <string> {
                "Hello", "World"
            };
            ISetT = new HashSet <string> {
                "Hello", "World"
            };
            StackT = new Stack <string>(new List <string> {
                "Hello", "World"
            });
            QueueT = new Queue <string>(new List <string> {
                "Hello", "World"
            });
            HashSetT = new HashSet <string>(new List <string> {
                "Hello", "World"
            });
            LinkedListT = new LinkedList <string>(new List <string> {
                "Hello", "World"
            });
            SortedSetT = new SortedSet <string>(new List <string> {
                "Hello", "World"
            });
            ImmutableArrayT = ImmutableArray.CreateRange(new List <string> {
                "Hello", "World"
            });
            IImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello", "World"
            });
            IImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello", "World"
            });
            IImmutableQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello", "World"
            });
            IImmutableSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello", "World"
            });
            ImmutableHashSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello", "World"
            });
            ImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello", "World"
            });
            ImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello", "World"
            });
            ImmutableQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello", "World"
            });
            ImmutableSortedSetT = ImmutableSortedSet.CreateRange(new List <string> {
                "Hello", "World"
            });

            NullableInt      = new int?(42);
            Object           = new object();
            NullableIntArray = new int?[] { null, 42, null };
        }
        public void Initialize()
        {
            MyInt16          = 1;
            MyInt32          = 2;
            MyInt64          = 3;
            MyUInt16         = 4;
            MyUInt32         = 5;
            MyUInt64         = 6;
            MyByte           = 7;
            MySByte          = 8;
            MyChar           = 'a';
            MyString         = "Hello";
            MyBooleanTrue    = true;
            MyBooleanFalse   = false;
            MySingle         = 1.1f;
            MyDouble         = 2.2d;
            MyDecimal        = 3.3m;
            MyDateTime       = new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc);
            MyDateTimeOffset = new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0));
            MyEnum           = SampleEnum.Two;

            MyInt16Array          = new short[] { 1 };
            MyInt32Array          = new int[] { 2 };
            MyInt64Array          = new long[] { 3 };
            MyUInt16Array         = new ushort[] { 4 };
            MyUInt32Array         = new uint[] { 5 };
            MyUInt64Array         = new ulong[] { 6 };
            MyByteArray           = new byte[] { 7 };
            MySByteArray          = new sbyte[] { 8 };
            MyCharArray           = new char[] { 'a' };
            MyStringArray         = new string[] { "Hello" };
            MyBooleanTrueArray    = new bool[] { true };
            MyBooleanFalseArray   = new bool[] { false };
            MySingleArray         = new float[] { 1.1f };
            MyDoubleArray         = new double[] { 2.2d };
            MyDecimalArray        = new decimal[] { 3.3m };
            MyDateTimeArray       = new DateTime[] { new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc) };
            MyDateTimeOffsetArray = new DateTimeOffset[] { new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)) };
            MyEnumArray           = new SampleEnum[] { SampleEnum.Two };

            MyStringList = new List <string>()
            {
                "Hello"
            };
            MyStringIEnumerableT         = new string[] { "Hello" };
            MyStringIListT               = new string[] { "Hello" };
            MyStringICollectionT         = new string[] { "Hello" };
            MyStringIReadOnlyCollectionT = new string[] { "Hello" };
            MyStringIReadOnlyListT       = new string[] { "Hello" };

            MyStringToStringDict = new Dictionary <string, string> {
                { "key", "value" }
            };
            MyStringToStringIDict = new Dictionary <string, string> {
                { "key", "value" }
            };
            MyStringToStringIReadOnlyDict = new Dictionary <string, string> {
                { "key", "value" }
            };

            MyStringStackT = new Stack <string>(new List <string>()
            {
                "Hello", "World"
            });
            MyStringQueueT = new Queue <string>(new List <string>()
            {
                "Hello", "World"
            });
            MyStringHashSetT = new HashSet <string>(new List <string>()
            {
                "Hello"
            });
            MyStringLinkedListT = new LinkedList <string>(new List <string>()
            {
                "Hello"
            });
            MyStringSortedSetT = new SortedSet <string>(new List <string>()
            {
                "Hello"
            });

            MyStringIImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableHashSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutablQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableSortedSetT = ImmutableSortedSet.CreateRange(new List <string> {
                "Hello"
            });

            MyListOfNullString = new List <string> {
                null
            };
        }
 public void Deserialize(byte[] buffer, ref int offset, ref ImmutableStack <TItem> value)
 {
     TItem[] array = null;
     _itemsFormatter.Deserialize(buffer, ref offset, ref array);
     value = ImmutableStack.CreateRange(array.Reverse());
 }
Beispiel #20
0
 public void Replace(params T[] stack)
 {
     _stack.OnNext(ImmutableStack.CreateRange(stack));
 }
 /// <summary>
 /// Create an immutable stack
 /// </summary>
 public static IImmutableStack <T> toStack <T>(IEnumerable <T> items) =>
 ImmutableStack.CreateRange <T>(items);
Beispiel #22
0
 public static ImmutableStack <T> ImmutableStackFrom <T>(T first, T second, T third, params T[] values)
 {
     return(ImmutableStack.CreateRange(EnumerableUtils.GetEnumerableFrom(first, second, third, values)));
 }
Beispiel #23
0
        public void Initialize()
        {
            MyInt16          = 1;
            MyInt32          = 2;
            MyInt64          = 3;
            MyUInt16         = 4;
            MyUInt32         = 5;
            MyUInt64         = 6;
            MyByte           = 7;
            MySByte          = 8;
            MyChar           = 'a';
            MyString         = "Hello";
            MyBooleanTrue    = true;
            MyBooleanFalse   = false;
            MySingle         = 1.1f;
            MyDouble         = 2.2d;
            MyDecimal        = 3.3m;
            MyDateTime       = new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc);
            MyDateTimeOffset = new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0));
            MyEnum           = SampleEnum.Two;

            MyInt16Array          = new short[] { 1 };
            MyInt32Array          = new int[] { 2 };
            MyInt64Array          = new long[] { 3 };
            MyUInt16Array         = new ushort[] { 4 };
            MyUInt32Array         = new uint[] { 5 };
            MyUInt64Array         = new ulong[] { 6 };
            MyByteArray           = new byte[] { 7 };
            MySByteArray          = new sbyte[] { 8 };
            MyCharArray           = new char[] { 'a' };
            MyStringArray         = new string[] { "Hello" };
            MyBooleanTrueArray    = new bool[] { true };
            MyBooleanFalseArray   = new bool[] { false };
            MySingleArray         = new float[] { 1.1f };
            MyDoubleArray         = new double[] { 2.2d };
            MyDecimalArray        = new decimal[] { 3.3m };
            MyDateTimeArray       = new DateTime[] { new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc) };
            MyDateTimeOffsetArray = new DateTimeOffset[] { new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)) };
            MyEnumArray           = new SampleEnum[] { SampleEnum.Two };

            MyInt16TwoDimensionArray    = new int[2][];
            MyInt16TwoDimensionArray[0] = new int[] { 10, 11 };
            MyInt16TwoDimensionArray[1] = new int[] { 20, 21 };

            MyInt16TwoDimensionList = new List <List <int> >();
            MyInt16TwoDimensionList.Add(new List <int> {
                10, 11
            });
            MyInt16TwoDimensionList.Add(new List <int> {
                20, 21
            });

            MyInt16ThreeDimensionArray       = new int[2][][];
            MyInt16ThreeDimensionArray[0]    = new int[2][];
            MyInt16ThreeDimensionArray[1]    = new int[2][];
            MyInt16ThreeDimensionArray[0][0] = new int[] { 11, 12 };
            MyInt16ThreeDimensionArray[0][1] = new int[] { 13, 14 };
            MyInt16ThreeDimensionArray[1][0] = new int[] { 21, 22 };
            MyInt16ThreeDimensionArray[1][1] = new int[] { 23, 24 };

            MyInt16ThreeDimensionList = new List <List <List <int> > >();
            var list1 = new List <List <int> >();

            MyInt16ThreeDimensionList.Add(list1);
            list1.Add(new List <int> {
                11, 12
            });
            list1.Add(new List <int> {
                13, 14
            });
            var list2 = new List <List <int> >();

            MyInt16ThreeDimensionList.Add(list2);
            list2.Add(new List <int> {
                21, 22
            });
            list2.Add(new List <int> {
                23, 24
            });

            MyStringList = new List <string>()
            {
                "Hello"
            };

            MyStringIEnumerable = new string[] { "Hello" };
            MyStringIList       = new string[] { "Hello" };
            MyStringICollection = new string[] { "Hello" };

            MyStringIEnumerableT         = new string[] { "Hello" };
            MyStringIListT               = new string[] { "Hello" };
            MyStringICollectionT         = new string[] { "Hello" };
            MyStringIReadOnlyCollectionT = new string[] { "Hello" };
            MyStringIReadOnlyListT       = new string[] { "Hello" };
            MyStringISetT = new HashSet <string> {
                "Hello"
            };

            MyStringToStringKeyValuePair = new KeyValuePair <string, string>("myKey", "myValue");
            MyStringToStringIDict        = new Dictionary <string, string> {
                { "key", "value" }
            };

            MyStringToStringGenericDict = new Dictionary <string, string> {
                { "key", "value" }
            };
            MyStringToStringGenericIDict = new Dictionary <string, string> {
                { "key", "value" }
            };
            MyStringToStringGenericIReadOnlyDict = new Dictionary <string, string> {
                { "key", "value" }
            };

            MyStringToStringImmutableDict       = ImmutableDictionary.CreateRange(MyStringToStringGenericDict);
            MyStringToStringIImmutableDict      = ImmutableDictionary.CreateRange(MyStringToStringGenericDict);
            MyStringToStringImmutableSortedDict = ImmutableSortedDictionary.CreateRange(MyStringToStringGenericDict);

            MyStringStackT = new Stack <string>(new List <string>()
            {
                "Hello", "World"
            });
            MyStringQueueT = new Queue <string>(new List <string>()
            {
                "Hello", "World"
            });
            MyStringHashSetT = new HashSet <string>(new List <string>()
            {
                "Hello"
            });
            MyStringLinkedListT = new LinkedList <string>(new List <string>()
            {
                "Hello"
            });
            MyStringSortedSetT = new SortedSet <string>(new List <string>()
            {
                "Hello"
            });

            MyStringIImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello"
            });
            MyStringIImmutableSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableHashSetT = ImmutableHashSet.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableListT = ImmutableList.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableStackT = ImmutableStack.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutablQueueT = ImmutableQueue.CreateRange(new List <string> {
                "Hello"
            });
            MyStringImmutableSortedSetT = ImmutableSortedSet.CreateRange(new List <string> {
                "Hello"
            });

            MyListOfNullString = new List <string> {
                null
            };
        }
Beispiel #24
0
        private static GameEvent PlayCard(GameState state, int playerIdx, Card card, Coord coord)
        {
            if (playerIdx == -1)
            {
                throw new PlayCardFailedException(PlayCardError.PlayerIsNotInGame);
            }

            var playerId = state.PlayerIdByIdx[playerIdx];

            if (!playerId.Equals(state.CurrentPlayerId))
            {
                throw new PlayCardFailedException(PlayCardError.PlayerIsNotCurrentPlayer);
            }

            if (!state.PlayerHandByIdx[playerIdx].Contains(card))
            {
                throw new PlayCardFailedException(PlayCardError.PlayerDoesNotHaveCard);
            }

            var chips = state.Chips;
            var deck  = ImmutableStack.CreateRange(state.Deck);
            var team  = state.PlayerTeamByIdx[playerIdx];

            if (card.IsOneEyedJack())
            {
                if (!chips.ContainsKey(coord))
                {
                    throw new PlayCardFailedException(PlayCardError.CoordIsEmpty);
                }

                if (chips.TryGetValue(coord, out var chip) && chip == team)
                {
                    throw new PlayCardFailedException(PlayCardError.ChipBelongsToPlayerTeam);
                }

                if (state.CoordsInSequence.Contains(coord))
                {
                    throw new PlayCardFailedException(PlayCardError.ChipIsPartOfSequence);
                }

                return(new GameEvent
                {
                    ByPlayerId = playerId,
                    CardDrawn = deck.Peek(),
                    CardUsed = card,
                    Coord = coord,
                    Index = state.Version + 1,
                    NextPlayerId = state.PlayerIdByIdx[(playerIdx + 1) % state.NumberOfPlayers],
                    Sequences = Array.Empty <Seq>(),
                });
            }
            else
            {
                if (chips.ContainsKey(coord))
                {
                    throw new PlayCardFailedException(PlayCardError.CoordIsOccupied);
                }

                var board = state.BoardType.Board;

                if (!board.Matches(coord, card))
                {
                    throw new PlayCardFailedException(PlayCardError.CardDoesNotMatchCoord);
                }

                var sequences = board.GetSequences(
                    chips: chips.Add(coord, team),
                    state.CoordsInSequence,
                    coord, team);

                Team?winnerTeam = null;

                if (sequences.Count > 0)
                {
                    // Test for win condition:
                    var numSequencesForTeam = state.Sequences
                                              .AddRange(sequences)
                                              .Count(seq => seq.Team == team);

                    if (numSequencesForTeam >= state.WinCondition)
                    {
                        winnerTeam = team;
                    }
                }

                var nextPlayerId = winnerTeam == null
                    ? state.PlayerIdByIdx[(playerIdx + 1) % state.NumberOfPlayers]
                    : null;

                return(new GameEvent
                {
                    ByPlayerId = playerId,
                    CardDrawn = deck.Peek(),
                    CardUsed = card,
                    Chip = team,
                    Coord = coord,
                    Index = state.Version + 1,
                    NextPlayerId = nextPlayerId,
                    Sequences = sequences.ToArray(),
                    Winner = winnerTeam
                });
            }
        }
Beispiel #25
0
 public static ImmutableStack <T> ImmutableStackFrom <T>(T value, params T[] values)
 {
     return(ImmutableStack.CreateRange(EnumerableUtils.GetEnumerableFrom(value, values)));
 }