/// <summary>
        ///
        /// </summary>
        /// <param name="numberOfBlocksToStore"></param>
        /// <returns></returns>
        /// <exception cref="OverflowException"></exception>
        public AddressingSystemBlockSizes GetSizesOfAddressingBlocksSufficientToStoreItems(int numberOfBlocksToStore)
        {
            MethodArgumentValidator.ThrowIfNegative(numberOfBlocksToStore, "numberOfBlocksToStore");

            if (numberOfBlocksToStore == 0)
            {
                return(new AddressingSystemBlockSizes(0, 0));
            }

            int lastSingleIndirectBlockSize;
            int firstBlockSize = Math.DivRem(numberOfBlocksToStore, _singleIndirectBlockCapacity, out lastSingleIndirectBlockSize);

            if (lastSingleIndirectBlockSize > 0)
            {
                firstBlockSize++;
            }

            if (lastSingleIndirectBlockSize == 0)
            {
                lastSingleIndirectBlockSize = _singleIndirectBlockCapacity;
            }

            if (firstBlockSize > _doubleIndirectBlockCapacity)
            {
                throw new OverflowException("Невозможно распределить указанное число блоков.");
            }

            return(new AddressingSystemBlockSizes(firstBlockSize, lastSingleIndirectBlockSize));
        }
        public AddressingBlockSizesCalculator(int doubleIndirectBlockCapacity, int singleIndirectBlockCapacity)
        {
            MethodArgumentValidator.ThrowIfNegative(doubleIndirectBlockCapacity, "doubleIndirectBlockCapacity");
            MethodArgumentValidator.ThrowIfNegative(singleIndirectBlockCapacity, "singleIndirectBlockCapacity");

            _doubleIndirectBlockCapacity = doubleIndirectBlockCapacity;
            _singleIndirectBlockCapacity = singleIndirectBlockCapacity;
        }
        public static void ThrowIfStringIsTooLong(string argument, int maximumStringLength, string argumentName)
        {
            MethodArgumentValidator.ThrowIfNegative(maximumStringLength, "maximumStringLength");
            MethodArgumentValidator.ThrowIfStringIsNullOrEmpty(argument, argumentName);

            if (argument.Length > maximumStringLength)
            {
                throw new ArgumentException("Принимаются только строки длиной не больше следующего числа символов: {0}".FormatWith(maximumStringLength), argumentName);
            }
        }
Exemple #4
0
        private void SetCapacitiesAndIndex(int initialValue, int firstIndexCapacity, int secondIndexCapacity, int thirdIndexCapacity)
        {
            MethodArgumentValidator.ThrowIfNegative(firstIndexCapacity, "firstIndexCapacity");
            MethodArgumentValidator.ThrowIfNegative(secondIndexCapacity, "secondIndexCapacity");
            MethodArgumentValidator.ThrowIfNegative(thirdIndexCapacity, "thirdIndexCapacity");

            FirstIndexCapacity  = firstIndexCapacity;
            SecondIndexCapacity = secondIndexCapacity;
            ThirdIndexCapacity  = thirdIndexCapacity;

            _compositeIndex = new CompositeIndex(initialValue, new[] { firstIndexCapacity, secondIndexCapacity, thirdIndexCapacity });
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="newInteger"></param>
        /// <exception cref="InvalidOperationException">Если размер набора целых чисел достиг максимума.</exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public void AddInteger(int newInteger)
        {
            MethodArgumentValidator.ThrowIfNegative(newInteger, "newInteger");

            if (_integers.Count == _maximumCountOfIntegers)
            {
                throw new InvalidOperationException("В списке чисел не может быть больше следующего числа элементов: {0}.".FormatWith(_maximumCountOfIntegers));
            }

            // Note: можно было бы тут же и сохранять, обернув класс декоратором, как я сделал в нескольких других местах.

            _integers.Add(newInteger);
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="numberOfItemsToDistribute"></param>
        /// <param name="firstBucketRemainingCapacity"></param>
        /// <param name="bucketCapacity"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static ReadOnlyCollection <BucketDistribution> Distribute(int numberOfItemsToDistribute, int firstBucketRemainingCapacity, int bucketCapacity)
        {
            MethodArgumentValidator.ThrowIfNegative(numberOfItemsToDistribute, "numberOfItemsToDistribute");
            MethodArgumentValidator.ThrowIfNegative(firstBucketRemainingCapacity, "firstBucketRemainingCapacity");
            MethodArgumentValidator.ThrowIfNegative(bucketCapacity, "bucketCapacity");

            if (firstBucketRemainingCapacity > bucketCapacity)
            {
                throw new ArgumentException("Первая из ячеек не может иметь места для еще {0} элемент(-а,-ов), так как каждая ячейка содержит, максимум, {1} элементов".FormatWith(firstBucketRemainingCapacity, bucketCapacity));
            }

            var distributionResult = new List <BucketDistribution>();
            int bucketIndex        = 0;

            if (firstBucketRemainingCapacity < numberOfItemsToDistribute)
            {
                if (firstBucketRemainingCapacity != 0)
                {
                    distributionResult.Add(new BucketDistribution(bucketIndex, bucketCapacity - firstBucketRemainingCapacity, firstBucketRemainingCapacity));
                    numberOfItemsToDistribute -= firstBucketRemainingCapacity;
                }
            }
            else
            {
                distributionResult.Add(new BucketDistribution(bucketIndex, bucketCapacity - firstBucketRemainingCapacity, numberOfItemsToDistribute));
                return(distributionResult.AsReadOnly());
            }

            int remainder;
            int fullyFilledBuckets = Math.DivRem(numberOfItemsToDistribute, bucketCapacity, out remainder);

            bucketIndex++;

            for (int i = 0; i < fullyFilledBuckets; i++)
            {
                distributionResult.Add(new BucketDistribution(bucketIndex, 0, bucketCapacity));
                bucketIndex++;
            }

            if (remainder > 0)
            {
                distributionResult.Add(new BucketDistribution(bucketIndex, 0, remainder));
            }

            return(distributionResult.AsReadOnly());
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public int this[int index]
        {
            get
            {
                return(_integers[index]);
            }
            set
            {
                MethodArgumentValidator.ThrowIfNegative(value, "value");

                if (index >= _integers.Count)
                {
                    throw new ArgumentOutOfRangeException("index");
                }

                _integers[index] = value;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="numberOfItemsToStore"></param>
        /// <param name="chunkSize"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static int GetNumberOfChunksNeededToStoreData(int numberOfItemsToStore, int chunkSize)
        {
            MethodArgumentValidator.ThrowIfNegative(numberOfItemsToStore, "numberOfItemsToStore");

            if (chunkSize <= 0)
            {
                throw new ArgumentOutOfRangeException("chunkSize", "Требуется положительное число");
            }

            int remainder;

            int numberOfBlocksNeeded = Math.DivRem(numberOfItemsToStore, chunkSize, out remainder);

            if (remainder > 0)
            {
                numberOfBlocksNeeded++;
            }

            return(numberOfBlocksNeeded);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="integersAsByteArrayLittleEndian"></param>
        /// <param name="currentCountOfIntegers"></param>
        /// <param name="maximumCountOfIntegers"></param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public IntegerListConstrained(byte[] integersAsByteArrayLittleEndian, int currentCountOfIntegers, int maximumCountOfIntegers)
        {
            MethodArgumentValidator.ThrowIfNegative(currentCountOfIntegers, "currentCountOfIntegers");
            MethodArgumentValidator.ThrowIfNegative(maximumCountOfIntegers, "maximumCountOfIntegers");
            MethodArgumentValidator.ThrowIfNull(integersAsByteArrayLittleEndian, "integersAsByteArrayLittleEndian");

            if (currentCountOfIntegers * IntegerSizeInBytes > integersAsByteArrayLittleEndian.Length)
            {
                throw new ArgumentException("Из массива байт не удастся прочитать следующее число целых: {0}. Проверьте аргументы.".FormatWith(currentCountOfIntegers), "currentCountOfIntegers");
            }

            if (maximumCountOfIntegers < currentCountOfIntegers)
            {
                throw new ArgumentException("Максимальное число целых в списке не может быть меньше текущего числа элементов.".FormatWith(currentCountOfIntegers), "currentCountOfIntegers, maximumCountOfIntegers");
            }

            this.FillInInternalListOfIntegers(integersAsByteArrayLittleEndian, currentCountOfIntegers);

            _maximumCountOfIntegers = maximumCountOfIntegers;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="newSize"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public ReadOnlyCollection <int> Shrink(int newSize)
        {
            MethodArgumentValidator.ThrowIfNegative(newSize, "newSize");

            if (newSize > _integers.Count)
            {
                throw new ArgumentOutOfRangeException("newSize", "Новый размер массива должен быть меньше текущего.");
            }

            var removedItems = new List <int>();

            while (_integers.Count != newSize)
            {
                int lastIntegerIndex = _integers.Count - 1;

                removedItems.Add(_integers[lastIntegerIndex]);
                _integers.RemoveAt(lastIntegerIndex);
            }

            return(removedItems.AsReadOnly());
        }
Exemple #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="firstIndex"></param>
        /// <param name="firstIndexCapacity"></param>
        /// <param name="secondIndex"></param>
        /// <param name="secondIndexCapacity"></param>
        /// <param name="thirdIndex"></param>
        /// <param name="thirdIndexCapacity"></param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public DoubleIndirectionCompositeIndex(int firstIndex, int firstIndexCapacity, int secondIndex, int secondIndexCapacity, int thirdIndex, int thirdIndexCapacity)
        {
            MethodArgumentValidator.ThrowIfNegative(firstIndex, "firstIndex");
            MethodArgumentValidator.ThrowIfNegative(secondIndex, "secondIndex");
            MethodArgumentValidator.ThrowIfNegative(thirdIndex, "thirdIndex");
            MethodArgumentValidator.ThrowIfNegative(firstIndexCapacity, "firstIndexCapacity");
            MethodArgumentValidator.ThrowIfNegative(secondIndexCapacity, "secondIndexCapacity");
            MethodArgumentValidator.ThrowIfNegative(thirdIndexCapacity, "thirdIndexCapacity");

            if (firstIndex >= firstIndexCapacity)
            {
                throw new ArgumentException("Первый индекс должен быть в пределах от 0 до {0} (не включая {0})".FormatWith(firstIndexCapacity));
            }

            if (secondIndex >= secondIndexCapacity)
            {
                throw new ArgumentException("Второй индекс должен быть в пределах от 0 до {0} (не включая {0})".FormatWith(secondIndexCapacity));
            }

            if (thirdIndex >= thirdIndexCapacity)
            {
                throw new ArgumentException("Третий индекс должен быть в пределах от 0 до {0} (не включая {0})".FormatWith(thirdIndexCapacity));
            }

            checked
            {
                try
                {
                    int initialValue = firstIndex * secondIndexCapacity * thirdIndexCapacity + secondIndex * thirdIndexCapacity +
                                       thirdIndex;

                    this.SetCapacitiesAndIndex(initialValue, firstIndexCapacity, secondIndexCapacity, thirdIndexCapacity);
                }
                catch (OverflowException)
                {
                    throw new ArgumentException("Заданная комбинация индексов образует число слишком большое для текущей версии.");
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="initialValue"></param>
        /// <param name="capacitiesOfIndexes"></param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public CompositeIndex(int initialValue, IEnumerable <int> capacitiesOfIndexes)
        {
            MethodArgumentValidator.ThrowIfNegative(initialValue, "initialValue");
            MethodArgumentValidator.ThrowIfNull(capacitiesOfIndexes, "capacitiesOfIndexes");

            if (capacitiesOfIndexes.Any(number => (number <= 0)))
            {
                throw new ArgumentException("Массив не должен содержать отрицательных чисел и нулей.", "capacitiesOfIndexes");
            }

            var ordersList = new List <int>(capacitiesOfIndexes);

            if (ordersList.Count < 1)
            {
                throw new ArgumentException("Набор должен быть непустым.", "capacitiesOfIndexes");
            }

            _capacitiesOfCompositeIndexes = ordersList.AsReadOnly();

            _maximumValue = GetMaximumCapacityForGivenSystemValidatingInput(capacitiesOfIndexes) - 1;
            _capacity     = GetMaximumCapacityForGivenSystemValidatingInput(capacitiesOfIndexes);

            this.AssignNewValue(initialValue);
        }
Exemple #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="initialValue"></param>
        /// <param name="firstIndexCapacity"></param>
        /// <param name="secondIndexCapacity"></param>
        /// <param name="thirdIndexCapacity"></param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public DoubleIndirectionCompositeIndex(int initialValue, int firstIndexCapacity, int secondIndexCapacity, int thirdIndexCapacity)
        {
            MethodArgumentValidator.ThrowIfNegative(initialValue, "initialValue");

            this.SetCapacitiesAndIndex(initialValue, firstIndexCapacity, secondIndexCapacity, thirdIndexCapacity);
        }