Пример #1
0
        public void SingleEntry()
        {
            var d = new DictionarySlim <ulong, int>();

            d.GetOrAddValueRef(7)++;
            d.GetOrAddValueRef(7) += 3;
            Assert.Equal(4, d.GetOrAddValueRef(7));
        }
Пример #2
0
        public void TryGetValue_Missing()
        {
            var d = new DictionarySlim <char, int>();

            d.GetOrAddValueRef('a') = 9;
            d.GetOrAddValueRef('b') = 11;
            d.Remove('b');
            Assert.Equal(false, d.TryGetValue('z', out int value));
            Assert.Equal(default, value);
Пример #3
0
        public void ContainKey()
        {
            var d = new DictionarySlim <ulong, int>();

            d.GetOrAddValueRef(7)  = 9;
            d.GetOrAddValueRef(10) = 10;
            Assert.True(d.ContainsKey(7));
            Assert.True(d.ContainsKey(10));
            Assert.False(d.ContainsKey(1));
        }
Пример #4
0
        public void TryGetValue_Present()
        {
            var d = new DictionarySlim <char, int>();

            d.GetOrAddValueRef('a') = 9;
            d.GetOrAddValueRef('b') = 11;
            Assert.Equal(true, d.TryGetValue('a', out int value));
            Assert.Equal(9, value);
            Assert.Equal(true, d.TryGetValue('b', out value));
            Assert.Equal(11, value);
        }
Пример #5
0
        internal static List <MethodInfo> GetAfterDeserializeMethods(Type type)
        {
            lock (_deserializeCacheLock)
            {
                ref var methods = ref _deserializeCache.GetOrAddValueRef(type);
                if (methods == null)
                {
                    var start = Enumerable.Empty <MethodInfo>();
                    while (type != null)
                    {
                        var newMethods = type.GetMethods(
                            BindingFlags.Instance
                            | BindingFlags.Static
                            | BindingFlags.Public
                            | BindingFlags.NonPublic
                            | BindingFlags.DeclaredOnly)
                                         .Where(x => x.CustomAttributes.Any(a => a.AttributeType == typeof(AfterDeserialization)) &&
                                                (
                                                    x.GetParameters().Length <= 1 && !x.IsStatic ||
                                                    x.GetParameters().Length <= 2 && x.GetParameters().Length >= 1 && x.IsStatic
                                                ));

                        start = start.Concat(newMethods);
                        type  = type.BaseType !;
                    }

                    methods = start.Reverse().ToList();
                }

                return(methods);
            }
Пример #6
0
        internal static List <FieldInfo> GetOrderedFields(Type type, ImmutableSettings settings)
        {
            var mustUseReflectionToSetReadonly = FieldInfoModifier.MustUseReflectionToSetReadonly(settings);

            lock (_cacheLock)
            {
                ref var fields = ref _orderedCache.GetOrAddValueRef(new OrderedTypeCacheKey {
                    Type = type, Flattened = settings.FlattenClassHierarchy
                });
                if (fields == null)
                {
                    var unorderedFields = settings.FlattenClassHierarchy ? GetFlattenedFields(type) : GetFields(type);
                    if (mustUseReflectionToSetReadonly)
                    {
                        fields = unorderedFields.OrderBy(x => IsPrimitive(x.FieldType) ? 0 : 1)
                                 .ThenBy(x => x.IsInitOnly ? 0 : 1)
                                 .ThenBy(x => x.FieldType == typeof(string) ? 0 : 1)
                                 .ThenBy(x => x.Name).ToList();
                    }
                    else
                    {
                        fields = unorderedFields.OrderBy(x => IsPrimitive(x.FieldType) ? 0 : 1)
                                 .ThenBy(x => x.FieldType == typeof(string) ? 0 : 1)
                                 .ThenBy(x => x.Name).ToList();
                    }
                }

                return(fields);
            }
Пример #7
0
 public void LoadDictionarySlim()
 {
     _dictSlim = new DictionarySlim <int, int>();
     for (int i = 0; i < Size; i++)
     {
         _dictSlim.GetOrAddValueRef(i * 7) = -i;
     }
 }
 public void LoadDictionarySlim()
 {
     for (int i = 0; i < _keys.Length; i++)
     {
         var k = _keys[i];
         _refDict.GetOrAddValueRef(k) += k.HashCode;
     }
 }
 private static void Check(DictionarySlim <long, int> dict, ref long rollingKey, byte nb, long mask)
 {
     if (nb == 255)
     {
         return;
     }
     rollingKey = ((rollingKey & mask) << 2) | nb;
     dict.GetOrAddValueRef(rollingKey)++;
 }
Пример #10
0
        // [Fact] // Test too slow
        public void ResizeToCapacity()
        {
            var d = new DictionarySlim <uint, byte>();

            Assert.Throws <InvalidOperationException>(() =>
            {
                for (uint i = 0; i < uint.MaxValue; i++)
                {
                    d.GetOrAddValueRef(i) = (byte)1;
                }
            });
        }
Пример #11
0
            static void AssignBots(IEnumerable <Assignment> assignments, DictionarySlim <int, Bot> bots, Logger logger)
            {
                foreach (var assignment in assignments)
                {
                    ref var bot = ref bots.GetOrAddValueRef(assignment.BotNumber);
                    if (bot is null)
                    {
                        bot = new Bot(assignment.BotNumber);
                    }

                    bot.Set(assignment.Value);
                    logger.AssignValue(bot.Number, assignment.Value);
                }
Пример #12
0
            public DictionarySlim <string, string> DictSlim_GetOrAddValueRef()
            {
                var map = new DictionarySlim <string, string>();

                for (var i = 0; i < Count; ++i)
                {
                    var a = i.ToString();
                    var v = a + Seed;
                    map.GetOrAddValueRef(v + a) = v;
                }

                return(map);
            }
Пример #13
0
        public static IEnumerable <IGrouping <TKey, TSource> > GroupByRef <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector) where TKey : IEquatable <TKey>
        {
            var dict = new DictionarySlim <TKey, Grouping <TKey, TSource> >();

            foreach (var t in source)
            {
                var     k = keySelector(t);
                ref var g = ref dict.GetOrAddValueRef(k);
                if (g == null)
                {
                    g = new Grouping <TKey, TSource>(k);
                }
                g.Add(t);
            }
Пример #14
0
        public void Precompile(Type type)
        {
            if (type.IsGenericTypeDefinition)
            {
                throw new ArgumentException("Cannot compile for a generic type definition", nameof(type));
            }

            lock (VirtualReadMethods)
            {
                ref var readMethod = ref VirtualReadMethods.GetOrAddValueRef(type);
                if (readMethod == null)
                {
                    readMethod = DynamicCode <TStream, Binary <TStream, TSettingGen> > .GenerateReadMethod <ReadObject>(type, Settings, true, false);
                }
            }
Пример #15
0
        public bool TryAdd(TKey key, TValue value)
        {
            if (value.StorageIndex != 0)
            {
                ThrowStorageIndexNonZero();
            }

            EnterWriteLock();
            try
            {
                var h = GCHandle.Alloc(value, GCHandleType.Weak);

                ref var hr    = ref _inner.GetOrAddValueRef(key);
                var     added = true;
                if (hr.IsAllocated)
                {
                    h.Free();
                    added = false;
                }
                else
                {
                    hr = h;
                    var idx = _counter++; // we are inside lock, do not need: Interlocked.Increment(ref _counter);
                    if (idx >= _index.Length)
                    {
                        if (_freeSlots.Count == 0)
                        {
                            GrowIndexArray();
                        }
                        else
                        {
                            idx = _freeSlots.Pop();
                            if (AdditionalCorrectnessChecks.Enabled)
                            {
                                if (_index[idx].IsAllocated)
                                {
                                    ThrowHelper.FailFast("Free slot is allocated");
                                }
                            }
                        }
                    }

                    value.StorageIndex = idx;
                    _index[idx]        = h;
                }

                return(added);
            }
Пример #16
0
        public void CompareSCGAndFastDictionaryWithInts()
        {
            var dictionary           = new Dictionary <long, long>();
            var dictionarySlim       = new DictionarySlim <long, long>();
            var fastDictionary       = new FastDictionary <long, long>();
            var concurrentDictionary = new ConcurrentDictionary <long, long>();

            var length = 10000;

            for (int i = 0; i < length; i++)
            {
                dictionary.Add(i, i);
                ref var x = ref dictionarySlim.GetOrAddValueRef(i);
                x = i;
                fastDictionary.Add(i, i);
                concurrentDictionary[i] = i;
            }
 private void FindAndResolveLabels(Match match) //when a label is found, substitutes all instances of this label with the equivalent 8085 memory address
 {
     if (labels.ContainsKey(match.Groups["label"].Value))
     {
         errors_list.Add(new AssembleError($"Label {match.Groups["label"].Value} was previously defined", line_number));
     }
     else
     {
         labels.GetOrAddValueRef(match.Groups["label"].Value) = counter;
         if (to_be_resolved.TryGetValue(match.Groups["label"].Value, out IReadOnlyCollection <KeyValuePair <ushort, int> > address_line))
         {
             byte[] address_bytes = BitConverter.GetBytes(counter);
             foreach (KeyValuePair <ushort, int> item in address_line)
             {
                 temp_memory[item.Key]     = address_bytes[0];
                 temp_memory[item.Key + 1] = address_bytes[1];
             }
             to_be_resolved.Remove(match.Groups["label"].Value);
         }
     }
 }
Пример #18
0
        public void Write <T>(T value, Stream outputStream)
        {
            _lastRefType = null;
            _stream.WriteTo(outputStream);

            WriteObjectEntry(value);

            _stream.Flush();

            if (Settings.SerializationMode == Mode.Graph)
            {
                _savedObjectLookup.Clear();
                if (_internedObjects.Count > 0)
                {
                    foreach (var o in _internedObjects)
                    {
                        _savedObjectLookup.GetOrAddValueRef(o) = _savedObjectLookup.Count;
                    }
                }
            }
            _savedTypeLookup.Clear();
        }
        public void Setup()
        {
            dictionary = new Dictionary <string, bool>(data.Length);
            foreach (var item in data)
            {
                dictionary.Add(item, true);
            }

            dictionarySlim = new DictionarySlim <string, bool>(data.Length);
            foreach (var item in data)
            {
                dictionarySlim.GetOrAddValueRef(item) = true;
            }

            hashset = new HashSet <string>();
            foreach (var item in data)
            {
                hashset.Add(item);
            }

            array[8] = 444;
        }
Пример #20
0
    static void Main(string[] args)
    {
        var counts = new DictionarySlim <string, int>();
        var buffer = new char[BufferSize];
        var offset = 0;

        while (true)
        {
            // Read from stdin in chars
            var bytesRead = Console.In.Read(buffer, offset, BufferSize - offset);
            if (bytesRead == 0)
            {
                break;
            }

            // Determine last delimiter position
            var bufferLength       = offset + bytesRead;
            var lastDelimiterIndex = -1;
            for (var k = bufferLength - 1; k >= 0; --k)
            {
                if (buffer[k] <= ' ')
                {
                    lastDelimiterIndex = k;
                    break;
                }
            }

            var count = lastDelimiterIndex >= 0 ? lastDelimiterIndex : bufferLength;
            var i     = 0;

            while (true)
            {
                // Skip whitespaces before each word
                for (; i < count; ++i)
                {
                    var c = buffer[i];
                    if (c > ' ')
                    {
                        break;
                    }
                }

                // Find word boundary and make it lowercase at the same time.
                var start = i;
                for (; i < count; ++i)
                {
                    var c = buffer[i];
                    if (c <= ' ')
                    {
                        break;
                    }

                    // Set 6th bit to make char lowercase
                    buffer[i] = (char)(buffer[i] | 0x20);
                }

                if (i <= start)
                {
                    break;
                }

                // Collect word statistics
                var     word     = new String(buffer, start, i - start);
                ref var curCount = ref counts.GetOrAddValueRef(word);
                curCount++;
            }

            // Copy remaining part to the beginning of the buffer.
            if (lastDelimiterIndex >= 0)
            {
                offset = (offset + bytesRead - 1) - lastDelimiterIndex;
                Array.Copy(buffer, lastDelimiterIndex + 1, buffer, 0, offset);
            }
            else
            {
                offset = 0;
            }
        }