Пример #1
0
        public static double Det(MatrixExpression a)
        {
            var m = a.Evaluate();

            if (a is MatrixInput)
            {
                m = Copy(m);
            }
            var ipiv = Pool.Int.Rent(m.Rows);

            ThrowHelper.Check(Lapack.getrf(Layout.ColMajor, m.Rows, m.Rows, m.Array, m.Rows, ipiv));
            Pool.Int.Return(ipiv);
            double r = m[0, 0];

            for (int i = 1; i < m.Rows; i++)
            {
                r *= m[i, i];
            }
            m.Dispose();
            return(-r);
        }
Пример #2
0
        public TPool Get(TKey key)
        {
            if (key is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }

            if (!_map.TryGetValue(key, out TPool pool))
            {
                pool = NewPool(key);
                TPool old = _map.GetOrAdd(key, pool);
                if (!ReferenceEquals(old, pool))
                {
                    // We need to destroy the newly created pool as we not use it.
                    _    = PoolCloseAsyncIfSupported(pool);
                    pool = old;
                }
            }

            return(pool);
        }
Пример #3
0
        /// <summary>
        /// Draws an "invalid" icon that is centered within the specified <see
        /// cref="RegularPolygon"/>.</summary>
        /// <param name="context">
        /// The <see cref="DrawingContext"/> for the drawing.</param>
        /// <param name="brush">
        /// The <see cref="Brush"/> used to draw the <paramref name="polygon"/> outline.</param>
        /// <param name="target">
        /// The region within <paramref name="context"/> on which the copied "invalid" icon is
        /// centered.</param>
        /// <param name="polygon">
        /// The <see cref="RegularPolygon"/> whose <see cref="RegularPolygon.Vertices"/> provide the
        /// drawing size and black outline for the "invalid" icon.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> or <paramref name="polygon"/> is a null reference.
        /// </exception>
        /// <remarks>
        /// <b>DrawInvalidIcon</b> draws the icon returned by <see cref="Images.Invalid"/>,
        /// surrounded by an outline of the specified <paramref name="polygon"/> drawn using the
        /// specified <paramref name="brush"/>.</remarks>

        internal static void DrawInvalidIcon(DrawingContext context,
                                             Brush brush, Rect target, RegularPolygon polygon)
        {
            if (context == null)
            {
                ThrowHelper.ThrowArgumentNullException("context");
            }
            if (polygon == null)
            {
                ThrowHelper.ThrowArgumentNullException("polygon");
            }

            // compute scaled bounds for "invalid" icon
            double diameter = 1.6f * polygon.InnerRadius;
            double x        = target.X + (target.Width - diameter) / 2f;
            double y        = target.Y + (target.Height - diameter) / 2f;

            // draw icon with polygon outline
            context.DrawImage(Images.Invalid, new Rect(x, y, diameter, diameter));
            DrawOutline(context, brush, target, polygon);
        }
Пример #4
0
        public static Exception TestExceptionOnInit <TMember>(Specification <TMember> specification, Type expectedException)
        {
            ThrowHelper.NullArgument(specification, nameof(specification));
            ThrowHelper.NullArgument(expectedException, nameof(expectedException));

            try
            {
                Validator.Factory.Create(specification);
            }
            catch (Exception exception)
            {
                if (!expectedException.IsInstanceOfType(exception))
                {
                    throw new TestFailedException($"Exception of type {expectedException.FullName} was expected, but found {exception.GetType().FullName}.");
                }

                return(exception);
            }

            throw new TestFailedException($"Exception of type {expectedException.FullName} was expected, but no exception has been thrown.");
        }
Пример #5
0
        /// <summary>
        /// Gets or sets the <see cref="byte" /> at the specified index.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns><see cref="byte" />.</returns>
        public byte this[int index]
        {
            get
            {
                if (index < 0 || index >= Length)
                {
                    ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
                }

                return(Bytes[Offset + index]);
            }
            set
            {
                if (index < 0 || index >= Length)
                {
                    ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
                }

                Bytes[Offset + index] = value;
            }
        }
Пример #6
0
        /// <inheritsdoc />
        public override Jwk WrapKey(Jwk?staticKey, JwtObject header, Span <byte> destination)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            var         cek   = CreateSymmetricKey(EncryptionAlgorithm, staticKey);
            Span <byte> nonce = stackalloc byte[IVSize];
            Span <byte> tag   = stackalloc byte[TagSize];

            using (var aesGcm = new AesGcm(Key.AsSpan()))
            {
                aesGcm.Encrypt(nonce, cek.AsSpan(), destination, tag);

                header.Add(new JwtProperty(HeaderParameters.IVUtf8, Base64Url.Encode(nonce)));
                header.Add(new JwtProperty(HeaderParameters.TagUtf8, Base64Url.Encode(tag)));
            }

            return(cek);
        }
Пример #7
0
        /// <summary>
        ///     Returns the value of the system property with the specified
        ///     <c>key</c>, while falling back to the specified default value if
        ///     the property access fails.
        /// </summary>
        /// <returns>
        ///     the property value.
        ///     <c>def</c> if there's no such property or if an access to the
        ///     specified property is not allowed.
        /// </returns>
        public static string Get(string key, string def)
        {
            if (string.IsNullOrEmpty(key))
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }

            try
            {
                return(Environment.GetEnvironmentVariable(key) ?? def);
            }
            catch (Exception e)
            {
                if (!loggedException)
                {
                    Log("Unable to retrieve a system property '" + key + "'; default values will be used.", e);
                    loggedException = true;
                }
                return(def);
            }
        }
Пример #8
0
        /// <summary>
        /// Removes the item at the index specified.
        /// </summary>
        /// <param name="index">The zero-based index of the item to remove.</param>
        protected override void RemoveItem(int index)
        {
            if (this.Owner == null || string.IsNullOrEmpty(this.Owner.Path))
            {
                ThrowHelper.ThrowInvalidOperationException(Resources.Exception_PhoneBookNotOpened);
            }

            if (!this.IsInitializing)
            {
                RasEntry entry = this[index];
                if (entry != null)
                {
                    RasHelper.Instance.DeleteEntry(entry.Owner.Path, entry.Name);
                }
            }

            // Remove the entry from the lookup table.
            this._lookUpTable.RemoveAt(index);

            base.RemoveItem(index);
        }
Пример #9
0
        /// <summary>Sets the length of this stream to the given value.</summary>
        /// <param name="value">The new length of the stream.</param>
        public override void SetLength(long value)
        {
            if (value < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
            }
            else if (_strategy.IsClosed)
            {
                ThrowHelper.ThrowObjectDisposedException_FileClosed();
            }
            else if (!CanSeek)
            {
                ThrowHelper.ThrowNotSupportedException_UnseekableStream();
            }
            else if (!CanWrite)
            {
                ThrowHelper.ThrowNotSupportedException_UnwritableStream();
            }

            _strategy.SetLength(value);
        }
        public override void Read(JsonTokenType tokenType, JsonSerializerOptions options, ref ReadStack state, ref Utf8JsonReader reader)
        {
            Debug.Assert(ElementClassInfo == null);
            Debug.Assert(ShouldDeserialize);

            if (ValueConverter != null && ValueConverter.TryRead(s_underlyingType, ref reader, out TProperty value))
            {
                if (state.Current.ReturnValue == null)
                {
                    state.Current.ReturnValue = value;
                }
                else
                {
                    Set((TClass)state.Current.ReturnValue, value);
                }

                return;
            }

            ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(RuntimePropertyType, reader, state.PropertyPath);
        }
Пример #11
0
 public Block this[int index]
 {
     get
     {
         var array = children;
         if ((uint)index >= (uint)array.Length || index >= Count)
         {
             ThrowHelper.ThrowIndexOutOfRangeException();
             return(null);
         }
         return(array[index]);
     }
     set
     {
         if ((uint)index >= (uint)Count)
         {
             ThrowHelper.ThrowIndexOutOfRangeException();
         }
         children[index] = value;
     }
 }
Пример #12
0
        public bool TryMoveNext()
        {
            switch (_state)
            {
            case 0: ThrowHelper.ThrowUninitialized();
                goto case 2;

            case 1:
                if ((uint)index < (uint)_list._size)
                {
                    index++;
                    return(true);
                }
                _state = 2;
                goto case 2;

            case 2:
            default:
                return(false);
            }
        }
Пример #13
0
        public static unsafe IntPtr StringToCoTaskMemAnsi(string?s)
        {
            if (s is null)
            {
                return(IntPtr.Zero);
            }

            long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
            int  nb  = (int)lnb;

            // Overflow checking
            if (nb != lnb)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s);
            }

            IntPtr ptr = AllocCoTaskMem(nb);

            StringToAnsiString(s, (byte *)ptr, nb);
            return(ptr);
        }
Пример #14
0
        public IFile OpenFile(string path, OpenMode mode)
        {
            path = PathTools.Normalize(path);

            foreach (IFileSystem fs in Sources)
            {
                DirectoryEntryType type = fs.GetEntryType(path);

                if (type == DirectoryEntryType.File)
                {
                    return(fs.OpenFile(path, mode));
                }

                if (type == DirectoryEntryType.Directory)
                {
                    ThrowHelper.ThrowResult(ResultFs.PathNotFound);
                }
            }

            ThrowHelper.ThrowResult(ResultFs.PathNotFound);
            return(default);
Пример #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Span2D{T}"/> struct wrapping a layer in a 3D array.
        /// </summary>
        /// <param name="array">The given 3D array to wrap.</param>
        /// <param name="depth">The target layer to map within <paramref name="array"/>.</param>
        /// <exception cref="ArrayTypeMismatchException">
        /// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when a parameter is invalid.</exception>
        public Span2D(T[,,] array, int depth)
        {
            if (array.IsCovariant())
            {
                ThrowHelper.ThrowArrayTypeMismatchException();
            }

            if ((uint)depth >= (uint)array.GetLength(0))
            {
                ThrowHelper.ThrowArgumentOutOfRangeExceptionForDepth();
            }

#if SPAN_RUNTIME_SUPPORT
            this.span = MemoryMarshal.CreateSpan(ref array.DangerousGetReferenceAt(depth, 0, 0), array.GetLength(1));
#else
            this.Instance = array;
            this.Offset   = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, 0, 0));
            this.height   = array.GetLength(1);
#endif
            this.width = this.Stride = array.GetLength(2);
        }
Пример #16
0
 /// <summary>
 /// Ends the execute.
 /// </summary>
 /// <param name="asyncResult">The async result.</param>
 public void EndExecute(IAsyncResult asyncResult)
 {
     if (asyncResult == null)
     {
         ThrowHelper.ThrowArgumentNullException("asyncResult");
     }
     if (this.mExecutionDelegate == null)
     {
         ThrowHelper.ThrowArgumentException("Wrong async result or EndAccept called multiple times.", "asyncResult");
     }
     try
     {
         this.mExecutionDelegate.EndInvoke(asyncResult);
     }
     finally
     {
         this.mExecutionDelegate = null;
         this.mAsyncActiveExecutionEvent.Set();
         CloseAsyncActiveExecutionEvent(Interlocked.Decrement(ref mAsyncActiveExecutionCount));
     }
 }
Пример #17
0
        public static unsafe int WriteAsPtr <T>(this MemoryStream stream, T value)
        {
            var size = TypeHelper <T> .FixedSize;

            if (size <= 0)
            {
                ThrowHelper.ThrowInvalidOperationException("This method should only be used for writing fixed-size types to a stream");
            }

            long posInternal;

            if (stream is RecyclableMemoryStream rms && rms.IsSingleChunk && rms.CapacityInternal - (posInternal = rms.PositionInternal) > size)
            {
                WriteUnaligned(ref rms.SingleChunk.Span[checked ((int)posInternal)], value);
                if (posInternal + size > rms.LengthInternal)
                {
                    rms.SetLengthInternal(posInternal + size);
                }

                rms.PositionInternal = posInternal + size;
            }
Пример #18
0
        internal void AssignParent(JsonNode parent)
        {
            if (Parent != null)
            {
                ThrowHelper.ThrowInvalidOperationException_NodeAlreadyHasParent();
            }

            JsonNode?p = parent;

            while (p != null)
            {
                if (p == this)
                {
                    ThrowHelper.ThrowInvalidOperationException_NodeCycleDetected();
                }

                p = p.Parent;
            }

            Parent = parent;
        }
Пример #19
0
        public static void FromBytes(object value, byte[] buffer, int index = 0)
        {
            ThrowHelper.ArgumentNull((value == null), nameof(value));
            ThrowHelper.ArgumentNull((buffer == null), nameof(buffer));
            int size = Marshal.SizeOf(value);

            ThrowHelper.ArgumentIndexOutOfRange((index < 0), nameof(index));
            ThrowHelper.ArgumentIndexLengthOutOfArray(((index + size) > buffer.Length));

            IntPtr pointer = Marshal.AllocHGlobal(size);

            try
            {
                Marshal.Copy(buffer, index, pointer, size);
                Marshal.PtrToStructure(pointer, value);
            }
            finally
            {
                Marshal.FreeHGlobal(pointer);
            }
        }
Пример #20
0
        private static object ParseCore(string json, Type returnType, JsonSerializerOptions options = null)
        {
            if (options == null)
            {
                options = JsonSerializerOptions.s_defaultOptions;
            }

            // todo: use an array pool here for smaller requests to avoid the alloc?
            byte[] jsonBytes   = JsonReaderHelper.s_utf8Encoding.GetBytes(json);
            var    readerState = new JsonReaderState(options.GetReaderOptions());
            var    reader      = new Utf8JsonReader(jsonBytes, isFinalBlock: true, readerState);
            object result      = ReadCore(returnType, options, ref reader);

            if (reader.BytesConsumed != jsonBytes.Length)
            {
                ThrowHelper.ThrowJsonException_DeserializeDataRemaining(
                    jsonBytes.Length, jsonBytes.Length - reader.BytesConsumed);
            }

            return(result);
        }
Пример #21
0
        internal LagStepImpl(TCursor cursor, int width = 1, int step = 1, bool allowIncomplete = false) : this()
        {
            if (width <= 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(nameof(width));
            }
            if (step <= 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(nameof(step));
            }
            if (allowIncomplete && _step > 1)
            {
                ThrowHelper.ThrowNotImplementedException("TODO incomplete with step is not implemented");
            }

            _cursor = cursor;

            _width           = width;
            _step            = step;
            _allowIncomplete = allowIncomplete;
        }
Пример #22
0
        public static Span2D <T> DangerousCreate(ref T value, int height, int width, int pitch)
        {
            if (width < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth();
            }

            if (height < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight();
            }

            if (pitch < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeExceptionForPitch();
            }

            OverflowHelper.EnsureIsInNativeIntRange(height, width, pitch);

            return(new Span2D <T>(ref value, height, width, pitch));
        }
Пример #23
0
        public void ReadEntry(int blockIndex, out int next, out int previous, out int length)
        {
            int entryIndex = BlockToEntryIndex(blockIndex);

            Span <AllocationTableEntry> entries = stackalloc AllocationTableEntry[2];

            ReadEntries(entryIndex, entries);

            if (entries[0].IsSingleBlockSegment())
            {
                length = 1;

                if (entries[0].IsRangeEntry())
                {
                    ThrowHelper.ThrowResult(ResultFs.AllocationTableIteratedRangeEntryInternal.Value);
                }
            }
            else
            {
                length = entries[1].Next - entryIndex + 1;
            }

            if (entries[0].IsListEnd())
            {
                next = -1;
            }
            else
            {
                next = EntryIndexToBlock(entries[0].GetNext());
            }

            if (entries[0].IsListStart())
            {
                previous = -1;
            }
            else
            {
                previous = EntryIndexToBlock(entries[0].GetPrev());
            }
        }
Пример #24
0
        [MethodImpl(MethodImplOptions.NoInlining)] // NB NoInlining is important to speed-up MovePrevious
        public bool MoveLast()
        {
            if (State == CursorState.None)
            {
                ThrowHelper.ThrowInvalidOperationException($"ICursorSeries {GetType().Name} is not initialized as a cursor. Call the Initialize() method and *use* (as IDisposable) the returned value to access ICursor MoveXXX members.");
            }
            var wasMoving = State == CursorState.Moving;

            var moved = _cursor.MoveFirst();

            if (moved)
            {
                if (wasMoving)
                {
                    _laggedCursor.Dispose();
                }
                _laggedCursor = _cursor.Clone();

                _currentWidth = 1;
                while (_currentWidth < _width)
                {
                    moved = _laggedCursor.MovePrevious();
                    _currentWidth++;
                }

                // NB important to do inside if, first move must be true
                moved = moved || _allowIncomplete;
            }

            if (moved)
            {
                State = CursorState.Moving;
            }
            else if (State == CursorState.Moving)
            {
                // if cursor was moving that it must have had at least one value
                ThrowHelper.ThrowOutOfOrderKeyException(_cursor.CurrentKey);
            }
            return(moved);
        }
Пример #25
0
        public void Add(TKey key, TValue value)
        {
            if (key == null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }
            object @lock = this._lock;

            lock (@lock)
            {
                this.VerifyIntegrity();
                this._invalid = true;
                int num = this.FindEntry(key);
                if (num != -1)
                {
                    this._invalid = false;
                    ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
                }
                this.CreateEntry(key, value);
                this._invalid = false;
            }
        }
Пример #26
0
        public bool CanWrite(T item)
        {
            if (item == null)
            {
                ThrowHelper.ThrowArgumentNullException("item");
            }

            bool result = false;

            using (MemoryStream ms = new MemoryStream())
            {
                try
                {
                    this.mFormatter.Serialize(ms, item);
                    result = true;
                }
                catch (Exception)
                {
                }
            }
            return(result);
        }
Пример #27
0
        /// <summary>Adds the key and value if the key doesn't exist, or updates the existing key's value if it does exist.</summary>
        /// <param name="key">key to add or update. May not be null.</param>
        /// <param name="value">value to associate with key.</param>
        public void AddOrUpdate(TKey key, TValue value)
        {
            if (key is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }

            lock (_lock)
            {
                int entryIndex = _container.FindEntry(key, out _);

                // if we found a key we should just update, if no we should create a new entry.
                if (entryIndex != -1)
                {
                    _container.UpdateValue(entryIndex, value);
                }
                else
                {
                    CreateEntry(key, value);
                }
            }
        }
Пример #28
0
        /// <summary>
        /// Sets the value associated with the specified
        /// <paramref name="key"/>.</summary>
        /// <param name="key">The <typeparamref name="TKey"/>
        /// to look for.</param>
        /// <param name="value">The value to set the element,
        /// at the <paramref name="key"/> provided, to.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <see cref="MasterDictionaryEntry{TEntry}.Subordinate"/> in
        /// value is: null, or not a subordinate
        /// of the <see cref="MasterDictionaryBase{TKey, TValue}"/>,
        /// or tries to alter which subordinate the
        /// <paramref name="key"/> points to.
        /// </exception>
        protected override void OnSetThis(TKey key, MasterDictionaryEntry <TValue> value)
        {
            if (value.Subordinate == null)
            {
                throw ThrowHelper.ObtainArgumentException(ArgumentWithException.value, ExceptionMessageId.SubordinateNull);
            }
            if (!this.subordinates.Contains(value.Subordinate))
            {
                throw ThrowHelper.ObtainArgumentException(ArgumentWithException.value, ExceptionMessageId.SubordinateDoesNotExist);
            }
            if (base[key].Subordinate != value.Subordinate)
            {
                throw ThrowHelper.ObtainArgumentException(ArgumentWithException.value, ExceptionMessageId.SubordinateCannotChange);
            }

            /* *
             * This is the primary reason that
             * MasterDictionaryEntry<TEntry> contains
             * a 'value'.
             * */
            ((_ISubordinateDictionaryMasterPass)(this[key].Subordinate))[key] = value.Entry;
        }
Пример #29
0
        public static unsafe IntPtr StringToCoTaskMemUni(string?s)
        {
            if (s is null)
            {
                return(IntPtr.Zero);
            }

            int nb = (s.Length + 1) * 2;

            // Overflow checking
            if (nb < s.Length)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s);
            }

            IntPtr ptr = AllocCoTaskMem(nb);

            s.AsSpan().CopyTo(new Span <char>((char *)ptr, s.Length));
            ((char *)ptr)[s.Length] = '\0';

            return(ptr);
        }
Пример #30
0
        /// <summary>
        /// Adds a task to be run once at the end of next (or current) <c>eventloop</c> iteration.
        /// </summary>
        /// <param name="task"></param>
        public void ExecuteAfterEventLoopIteration(IRunnable task)
        {
            if (task is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.task);
            }

            if (IsShutdown)
            {
                Reject();
            }

            if (!_tailTasks.TryEnqueue(task))
            {
                Reject(task);
            }

            if (!(task is ILazyRunnable) && WakesUpForTask(task))
            {
                WakeUp(InEventLoop);
            }
        }