示例#1
1
        public static void RentAndReturnManyOfTheSameSize_NoneAreSame(ArrayPool<byte> pool)
        {
            foreach (int length in new[] { 1, 16, 32, 64, 127, 4096, 4097 })
            {
                for (int iter = 0; iter < 2; iter++)
                {
                    var buffers = new HashSet<byte[]>();
                    for (int i = 0; i < 100; i++)
                    {
                        buffers.Add(pool.Rent(length));
                    }

                    Assert.Equal(100, buffers.Count);

                    foreach (byte[] buffer in buffers)
                    {
                        pool.Return(buffer);
                    }
                }
            }
        }
示例#2
0
        /// <summary>
        /// Creates a new <see cref="JsonResultExecutor"/>.
        /// </summary>
        /// <param name="writerFactory">The <see cref="IHttpResponseStreamWriterFactory"/>.</param>
        /// <param name="logger">The <see cref="ILogger{JsonResultExecutor}"/>.</param>
        /// <param name="options">The <see cref="IOptions{MvcJsonOptions}"/>.</param>
        /// <param name="charPool">The <see cref="ArrayPool{Char}"/> for creating <see cref="T:char[]"/> buffers.</param>
        public JsonResultExecutor(
            IHttpResponseStreamWriterFactory writerFactory,
            ILogger<JsonResultExecutor> logger,
            IOptions<MvcJsonOptions> options,
            ArrayPool<char> charPool)
        {
            if (writerFactory == null)
            {
                throw new ArgumentNullException(nameof(writerFactory));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (charPool == null)
            {
                throw new ArgumentNullException(nameof(charPool));
            }

            WriterFactory = writerFactory;
            Logger = logger;
            Options = options.Value;
            _charPool = new JsonArrayPool<char>(charPool);
        }
        public FileBufferingReadStream(
            Stream inner,
            int memoryThreshold,
            long? bufferLimit,
            Func<string> tempFileDirectoryAccessor,
            ArrayPool<byte> bytePool)
        {
            if (inner == null)
            {
                throw new ArgumentNullException(nameof(inner));
            }

            if (tempFileDirectoryAccessor == null)
            {
                throw new ArgumentNullException(nameof(tempFileDirectoryAccessor));
            }

            _bytePool = bytePool;
            if (memoryThreshold < _maxRentedBufferSize)
            {
                _rentedBuffer = bytePool.Rent(memoryThreshold);
                _buffer = new MemoryStream(_rentedBuffer);
                _buffer.SetLength(0);
            }
            else
            {
                _buffer = new MemoryStream();
            }

            _inner = inner;
            _memoryThreshold = memoryThreshold;
            _bufferLimit = bufferLimit;
            _tempFileDirectoryAccessor = tempFileDirectoryAccessor;
        }
        public ReusableTempWriter(ArrayPool<byte> bufferPool, ObjectPool<ReusableTempWriter> memStreamPool)
        {
            _memoryStream = new MemoryStreamSlim(bufferPool, AmqpPrimitivesWriter.BufferSize);

            _innerWriter = new InternalBigEndianWriter(_memoryStream);

            _writer2 = new AmqpPrimitivesWriter(_innerWriter, bufferPool, memStreamPool);
        }
 public ArrayPoolMemoryStream(int capacity, ArrayPool<byte> arrayPool = null)
 {
     _arrayPool = arrayPool ?? ArrayPool<byte>.Shared;
     _buffer = RequestBuffer(capacity);
     _capacity = capacity;
     _expandable = true;
     _writable = true;
     _exposable = false; // true;
     _origin = 0; // Must be 0 for byte[]'s created by MemoryStream
     _isOpen = true;
 }
示例#6
0
 public StreamFormatter(Stream stream, EncodingData encoding, ArrayPool<byte> pool, int bufferSize = 256)
 {
     _pool = pool;
     _buffer = null;
     if (bufferSize > 0)
     {
         _buffer = _pool.Rent(bufferSize);
     }
     _encoding = encoding;
     _stream = stream;
 }
        public JsonPatchInputFormatter(
            ILogger logger,
            JsonSerializerSettings serializerSettings,
            ArrayPool<char> charPool)
            : base(logger, serializerSettings, charPool)
        {
            // Clear all values and only include json-patch+json value.
            SupportedMediaTypes.Clear();

            SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJsonPatch);
        }
示例#8
0
 public StreamFormatter(Stream stream, FormattingData formattingData, ArrayPool<byte> pool, int bufferSize = 256)
 {
     _pool = pool;
     _buffer = null;
     if (bufferSize > 0)
     {
         _buffer = _pool.Rent(bufferSize);
     }
     _formattingData = formattingData;
     _stream = stream;
 }
示例#9
0
 public BufferFormatter(int capacity, FormattingData formattingData, ArrayPool<byte> pool = null)
 {
     _formattingData = formattingData;
     _count = 0;
     _pool = pool;
     if(_pool == null)
     {
         _pool = ArrayPool<byte>.Shared;
     }
     _buffer = _pool.Rent(capacity);
 }
示例#10
0
        public FormReader(string data, ArrayPool<char> charPool)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            _buffer = charPool.Rent(_rentedCharPoolLength);
            _charPool = charPool;
            _reader = new StringReader(data);
        }
示例#11
0
		public void TestCase ()
		{
			ArrayPool<byte> pool = new ArrayPool<byte> ();
			byte[] buffer; 
			bool isNewArray = pool.Take (10, out buffer);
			Assert.IsTrue (isNewArray);
			pool.Release (buffer);
			byte[] second;
			isNewArray = pool.Take (5, out second);			
			Assert.IsFalse (isNewArray);
			Assert.AreSame (buffer, second);
		}
 public HalInputFormatter(
     ILogger logger, 
     JsonSerializerSettings serializerSettings, 
     ArrayPool<char> charPool, 
     ObjectPoolProvider objectPoolProvider)
     : base(
           logger, 
           HalJsonSerializerSettingsProvider.AppendHalConverters(serializerSettings), 
           charPool, 
           objectPoolProvider)
 {
     SupportedMediaTypes.Add(new MediaTypeHeaderValue(HalJsonSerializerSettingsProvider.HalMediaType));
 }
示例#13
0
文件: JsonHelper.cs 项目: ymd1223/Mvc
        /// <summary>
        /// Initializes a new instance of <see cref="JsonHelper"/> that is backed by <paramref name="jsonOutputFormatter"/>.
        /// </summary>
        /// <param name="jsonOutputFormatter">The <see cref="JsonOutputFormatter"/> used to serialize JSON.</param>
        /// <param name="charPool">
        /// The <see cref="ArrayPool{Char}"/> for use with custom <see cref="JsonSerializerSettings"/> (see
        /// <see cref="Serialize(object, JsonSerializerSettings)"/>).
        /// </param>
        public JsonHelper(JsonOutputFormatter jsonOutputFormatter, ArrayPool<char> charPool)
        {
            if (jsonOutputFormatter == null)
            {
                throw new ArgumentNullException(nameof(jsonOutputFormatter));
            }
            if (charPool == null)
            {
                throw new ArgumentNullException(nameof(charPool));
            }

            _jsonOutputFormatter = jsonOutputFormatter;
            _charPool = charPool;
        }
示例#14
0
        public FormReader(Stream stream, Encoding encoding, ArrayPool<char> charPool)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            _buffer = charPool.Rent(_rentedCharPoolLength);
            _charPool = charPool;
            _reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024 * 2, leaveOpen: true);
        }
        public AmqpPrimitivesWriter(InternalBigEndianWriter writer, ArrayPool<byte> bufferPool,
									ObjectPool<ReusableTempWriter> memStreamPool)
        {
            _writer = writer;

            _bufferPool = bufferPool ?? new DefaultArrayPool<byte>(BufferSize, 5);
            if (memStreamPool == null)
            {
                memStreamPool = new ObjectPool<ReusableTempWriter>(() =>
                {
                    Console.WriteLine("Creating new writer...");
                    return new ReusableTempWriter(new DefaultArrayPool<byte>(BufferSize, 5), _memStreamPool);
                }, 6);
            }
            _memStreamPool = memStreamPool;
        }
        /// <summary>
        /// Creates a stream that reads until it reaches the given boundary pattern.
        /// </summary>
        /// <param name="stream">The <see cref="BufferedReadStream"/>.</param>
        /// <param name="boundary">The boundary pattern to use.</param>
        /// <param name="bytePool">The ArrayPool pool to use for temporary byte arrays.</param>
        public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary boundary, ArrayPool<byte> bytePool)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (boundary == null)
            {
                throw new ArgumentNullException(nameof(boundary));
            }

            _bytePool = bytePool;
            _innerStream = stream;
            _innerOffset = _innerStream.CanSeek ? _innerStream.Position : 0;
            _boundary = boundary;
        }
        /// <summary>
        /// Creates a new <see cref="MemoryPoolHttpResponseStreamWriterFactory"/>.
        /// </summary>
        /// <param name="bytePool">
        /// The <see cref="ArrayPool{Byte}"/> for creating <see cref="byte"/> buffers.
        /// </param>
        /// <param name="charPool">
        /// The <see cref="ArrayPool{Char}"/> for creating <see cref="char"/> buffers.
        /// </param>
        public MemoryPoolHttpResponseStreamWriterFactory(
            ArrayPool<byte> bytePool,
            ArrayPool<char> charPool)
        {
            if (bytePool == null)
            {
                throw new ArgumentNullException(nameof(bytePool));
            }

            if (charPool == null)
            {
                throw new ArgumentNullException(nameof(charPool));
            }

            _bytePool = bytePool;
            _charPool = charPool;
        }
示例#18
0
        public JsonOutputFormatter(JsonSerializerSettings serializerSettings, ArrayPool<char> charPool)
        {
            if (serializerSettings == null)
            {
                throw new ArgumentNullException(nameof(serializerSettings));
            }

            if (charPool == null)
            {
                throw new ArgumentNullException(nameof(charPool));
            }

            _serializerSettings = serializerSettings;
            _charPool = new JsonArrayPool<char>(charPool);

            SupportedEncodings.Add(Encoding.UTF8);
            SupportedEncodings.Add(Encoding.Unicode);
            SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson);
            SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson);
        }
示例#19
0
        public JsonInputFormatter(ILogger logger, JsonSerializerSettings serializerSettings, ArrayPool<char> charPool)
        {
            if (serializerSettings == null)
            {
                throw new ArgumentNullException(nameof(serializerSettings));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _logger = logger;
            _serializerSettings = serializerSettings;
            _charPool = new JsonArrayPool<char>(charPool);

            SupportedEncodings.Add(UTF8EncodingWithoutBOM);
            SupportedEncodings.Add(UTF16EncodingLittleEndian);

            SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson);
            SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson);
        }
示例#20
0
 /// <summary>
 /// Constructs a new instance of <see cref="ArrayBuilder{T}"/>.
 /// </summary>
 public ArrayBuilder(int minCapacity = 32, ArrayPool <T> arrayPool = null)
 {
     _arrayPool   = arrayPool ?? ArrayPool <T> .Shared;
     _minCapacity = minCapacity;
     _items       = Empty;
 }
示例#21
0
 public static void CallingReturnWithoutClearingDoesNotClearTheBuffer(ArrayPool<byte> pool)
 {
     byte[] buffer = pool.Rent(4);
     FillArray(buffer);
     pool.Return(buffer, clearArray: false);
     CheckFilledArray(buffer, (byte b1, byte b2) => Assert.Equal(b1, b2));
 }
示例#22
0
 private BytesPool()
 {
     _arrayPool  = ArrayPool <byte> .Shared;
     _memoryPool = MemoryPool <byte> .Shared;
 }
示例#23
0
 public StreamFormatter(Stream stream, ArrayPool<byte> pool) : this(stream, FormattingData.InvariantUtf16, pool)
 {
 }
 public PagedBufferedTextWriter(ArrayPool <char> pool, TextWriter inner)
 {
     _charBuffer = new PagedCharBuffer(new ArrayPoolBufferSource(pool));
     _inner      = inner;
 }
示例#25
0
 public Lease(ArrayPool <T> pool) => _pool = pool;
 public ManagedByteBuffer(byte[] data, int length, ArrayPool <byte> sourcePool)
     : base(data, length, sourcePool)
 {
 }
示例#27
0
 public static void RentingWithInvalidLengthThrows(ArrayPool<byte> pool)
 {
     Assert.Throws<ArgumentOutOfRangeException>("minimumLength", () => pool.Rent(-1));
 }
        public HttpResponseStreamWriter(
            Stream stream,
            Encoding encoding,
            int bufferSize,
            ArrayPool <byte> bytePool,
            ArrayPool <char> charPool)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanWrite)
            {
                throw new ArgumentException(Resources.HttpResponseStreamWriter_StreamNotWritable, nameof(stream));
            }

            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            if (bytePool == null)
            {
                throw new ArgumentNullException(nameof(bytePool));
            }

            if (charPool == null)
            {
                throw new ArgumentNullException(nameof(charPool));
            }

            _stream         = stream;
            Encoding        = encoding;
            _charBufferSize = bufferSize;

            _encoder  = encoding.GetEncoder();
            _bytePool = bytePool;
            _charPool = charPool;

            _charBuffer = charPool.Rent(bufferSize);

            try
            {
                var requiredLength = encoding.GetMaxByteCount(bufferSize);
                _byteBuffer = bytePool.Rent(requiredLength);
            }
            catch
            {
                charPool.Return(_charBuffer);
                _charBuffer = null;

                if (_byteBuffer != null)
                {
                    bytePool.Return(_byteBuffer);
                    _byteBuffer = null;
                }

                throw;
            }
        }
 public Buffer(byte[] data, int length, ArrayPool <byte> sourcePool)
 {
     this.Data   = data;
     this.length = length;
     this.sourcePoolReference = new WeakReference <ArrayPool <byte> >(sourcePool);
 }
示例#30
0
 public ArrayPoolAllocator(ArrayPool <T> pool, bool cleanBuffers) => (_pool, _cleanBuffers) = (pool, cleanBuffers);
示例#31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Sequence{T}"/> class.
 /// </summary>
 /// <param name="arrayPool">The pool to use for recycling backing arrays.</param>
 public Sequence(ArrayPool <T> arrayPool)
 {
     Requires.NotNull(arrayPool, nameof(arrayPool));
     this.arrayPool = arrayPool;
 }
示例#32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Sequence{T}"/> class
 /// that uses a private <see cref="ArrayPool{T}"/> for recycling arrays.
 /// </summary>
 public Sequence()
     : this(ArrayPool <T> .Create())
 {
 }
示例#33
0
 public static void CanRentManySizedBuffers(ArrayPool<byte> pool)
 {
     for (int i = 1; i < 10000; i++)
     {
         byte[] buffer = pool.Rent(i);
         Assert.Equal(i <= 16 ? 16 : RoundUpToPowerOf2(i), buffer.Length);
         pool.Return(buffer);
     }
 }
示例#34
0
        /// <summary>
        /// Returns an array of values with the specified field count.
        /// </summary>
        /// <param name="record">The reader to get column names from.</param>
        /// <param name="minimumArrayLength">The minimum size of the resultant array.</param>
        /// <param name="arrayPool">The array pool to acquire buffers from.</param>
        /// <returns>The array of values.</returns>
        public static object?[] GetValues(this IDataRecord record, int minimumArrayLength, ArrayPool <object?> arrayPool)
        {
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record));
            }
            if (arrayPool is null)
            {
                throw new ArgumentNullException(nameof(arrayPool));
            }

            Contract.EndContractBlock();
            var result = arrayPool.Rent(minimumArrayLength);

            record.GetValues(result);
            return(result);
        }
 public HalOutputFormatter(JsonSerializerSettings serializerSettings, ArrayPool <char> charPool)
     : base(HalJsonSerializerSettingsProvider.AppendHalConverters(serializerSettings), charPool)
 {
     SupportedMediaTypes.Add(new MediaTypeHeaderValue(HalJsonSerializerSettingsProvider.HalMediaType));
 }
示例#36
0
 private PooledArray(int minimumLength, ArrayPool <T> pool) =>
 (_array, _pool, Length, _disposed) = (pool.Rent(minimumLength), pool, minimumLength, false);
示例#37
0
 public StreamFormatter(Stream stream, ArrayPool <byte> pool) : this(stream, EncodingData.InvariantUtf16, pool)
 {
 }
示例#38
0
 static BufferPool()
 {
     _lock     = new object();
     _bytePool = new ArrayPool <byte>();
 }
 /// <summary>
 /// Creates a new instance of the <see cref="CsvSyncStreamInput"/> class as a copy of this
 /// one, using the given <see cref="ArrayPool{T}"/> to provide temporary buffers for the
 /// <see cref="Stream"/> to read into.
 /// </summary>
 /// <param name="readBufferPool">
 /// The <see cref="ArrayPool{T}"/> to provide temporary buffers for the <see cref="Stream"/>
 /// to read into, or <see langword="null"/> if the temporary buffers should be allocated
 /// directly on the managed heap.
 /// </param>
 /// <returns>
 /// A new instance of the <see cref="CsvSyncStreamInput"/> class as a copy of this one,
 /// using the given <see cref="ArrayPool{T}"/> to provide temporary buffers for the
 /// <see cref="Stream"/> to read into.
 /// </returns>
 /// <exception cref="InvalidOperationException">
 /// Thrown when <see cref="CsvSyncInputBase.Process"/> has already been called.
 /// </exception>
 public CsvSyncStreamInput WithReadBufferPool(ArrayPool <byte> readBufferPool)
 {
     ThrowIfProcessingHasAlreadyStarted();
     return(new CsvSyncStreamInput(_delimiter, _csvStream, _minReadBufferByteCount, readBufferPool, _ignoreUTF8ByteOrderMark));
 }
示例#40
0
 public static void RentingAValidSizeArraySucceeds()
 {
     Assert.NotNull(ArrayPool <byte> .Create().Rent(100));
 }
示例#41
0
 public NatsMemoryPool(ArrayPool <byte>?pool = null)
 {
     _pool = pool ?? ArrayPool <byte> .Create(1024 * 1024, 256);
 }
示例#42
0
 public TestRPCJsonOutputFormatter(JsonSerializerSettings serializerSettings, ArrayPool <char> charPool) : base(serializerSettings, charPool)
 {
 }
示例#43
0
 public ArrayBufferPool(ArrayPool<byte> pool)
 {
     _pool = pool;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SelectFieldJsonOutputFormatter"/> class.
 /// </summary>
 /// <param name="serializerSettings">
 /// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
 /// (<see cref="Microsoft.AspNetCore.Mvc.MvcJsonOptions.SerializerSettings"/>) or an instance
 /// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
 /// </param>
 /// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
 public SelectFieldJsonOutputFormatter(JsonSerializerSettings serializerSettings, ArrayPool <char> charPool)
     : base(serializerSettings, charPool)
 {
 }
示例#45
0
 static NullArrayPool()
 {
     Instance = new NullArrayPoolInstance();
 }
 public static void NullInputsInConstructor_ExpectArgumentNullException(Stream stream, Encoding encoding, ArrayPool <byte> bytePool, ArrayPool <char> charPool)
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         var httpRequestStreamReader = new HttpRequestStreamReader(stream, encoding, 1, bytePool, charPool);
     });
 }
示例#47
0
 public static void CallingReturnBufferWithNullBufferThrows(ArrayPool<byte> pool)
 {
     Assert.Throws<ArgumentNullException>("array", () => pool.Return(null));
 }
示例#48
0
        public static void RentingMultipleArraysGivesBackDifferentInstances()
        {
            ArrayPool <byte> instance = ArrayPool <byte> .Create(maxArraysPerBucket : 2, maxArrayLength : 16);

            Assert.NotSame(instance.Rent(100), instance.Rent(100));
        }
示例#49
0
        public static void CallingReturnWithClearingDoesClearTheBuffer(ArrayPool<byte> pool)
        {
            byte[] buffer = pool.Rent(4);
            FillArray(buffer);

            // Note - yes this is bad to hold on to the old instance but we need to validate the contract
            pool.Return(buffer, clearArray: true);
            CheckFilledArray(buffer, (byte b1, byte b2) => Assert.Equal(b1, default(byte)));
        }
示例#50
0
        protected List <HookMethod> FindHooks(string name, object[] args)
        {
            // Get the full name of the hook `name(argument type 1, argument type 2, ..., argument type x)`

            // Check the cache if we already found a match for this hook
            List <HookMethod> methods = HooksCache.GetHookMethod(name, args, out HookCache cache);

            if (methods != null)
            {
                return(methods);
            }
            List <HookMethod> matches = new List <HookMethod>();

            // Get all hook methods that could match, return an empty list if none match
            if (!Hooks.TryGetValue(name, out methods))
            {
                return(matches);
            }

            // Find matching hooks
            HookMethod exactMatch      = null;
            HookMethod overloadedMatch = null;

            foreach (HookMethod h in methods)
            {
                // A base hook should always have a matching signature either directly or through inheritance
                // and should always be called as core functionality depends on it.
                if (h.IsBaseHook)
                {
                    matches.Add(h);
                    continue;
                }

                // Check if this method matches the hook arguments passed if it isn't a base hook
                object[] hookArgs;
                int      received = args?.Length ?? 0;

                bool pooledArray = false;

                if (received != h.Parameters.Length)
                {
                    // The call argument count is different to the declared callback methods argument count
                    hookArgs    = ArrayPool.Get(h.Parameters.Length);
                    pooledArray = true;

                    if (received > 0 && hookArgs.Length > 0)
                    {
                        // Remove any additional arguments which the callback method does not declare
                        Array.Copy(args, hookArgs, Math.Min(received, hookArgs.Length));
                    }

                    if (hookArgs.Length > received)
                    {
                        // Create additional parameters for arguments excluded in this hook call
                        for (int n = received; n < hookArgs.Length; n++)
                        {
                            ParameterInfo parameter = h.Parameters[n];
                            if (parameter.DefaultValue != null && parameter.DefaultValue != DBNull.Value)
                            {
                                // Use the default value that was provided by the method definition
                                hookArgs[n] = parameter.DefaultValue;
                            }
                            else if (parameter.ParameterType.IsValueType)
                            {
                                // Use the default value for value types
                                hookArgs[n] = Activator.CreateInstance(parameter.ParameterType);
                            }
                        }
                    }
                }
                else
                {
                    hookArgs = args;
                }

                if (h.HasMatchingSignature(hookArgs, out bool isExactMatch))
                {
                    if (isExactMatch)
                    {
                        exactMatch = h;
                        break;
                    }

                    // Should we determine the level and call the closest overloaded match? Performance impact?
                    overloadedMatch = h;
                }

                if (pooledArray)
                {
                    ArrayPool.Free(hookArgs);
                }
            }

            if (exactMatch != null)
            {
                matches.Add(exactMatch);
            }
            else
            {
                if (overloadedMatch != null)
                {
                    matches.Add(overloadedMatch);
                }
            }

            cache.SetupMethods(matches);

            return(matches);
        }
示例#51
0
 public static void ReturningANonPooledBufferOfDifferentSizeToThePoolThrows(ArrayPool<byte> pool)
 {
     Assert.Throws<ArgumentException>("array", () => pool.Return(new byte[1]));
 }
示例#52
0
 static JT808ArrayPool()
 {
     ArrayPool = ArrayPool <byte> .Create();
 }
示例#53
0
 public static void UsePoolInParallel(ArrayPool<byte> pool)
 {
     int[] sizes = new int[] { 16, 32, 64, 128 };
     Parallel.For(0, 250000, i =>
     {
         foreach (int size in sizes)
         {
             byte[] array = pool.Rent(size);
             Assert.NotNull(array);
             Assert.InRange(array.Length, size, int.MaxValue);
             pool.Return(array);
         }
     });
 }
 internal CsvSyncStreamInput(byte delimiter, Stream csvStream, int minReadBufferByteCount, ArrayPool <byte> readBufferPool, bool ignoreUTF8ByteOrderMark)
 {
     _delimiter = delimiter;
     _csvStream = csvStream;
     _minReadBufferByteCount  = minReadBufferByteCount;
     _readBufferPool          = readBufferPool;
     _ignoreUTF8ByteOrderMark = ignoreUTF8ByteOrderMark;
 }
示例#55
0
        public static void Renting0LengthArrayReturnsSingleton(ArrayPool<byte> pool)
        {
            byte[] zero0 = pool.Rent(0);
            byte[] zero1 = pool.Rent(0);
            byte[] zero2 = pool.Rent(0);
            byte[] one = pool.Rent(1);

            Assert.Same(zero0, zero1);
            Assert.Same(zero1, zero2);
            Assert.NotSame(zero2, one);

            pool.Return(zero0);
            pool.Return(zero1);
            pool.Return(zero2);
            pool.Return(one);

            Assert.Same(zero0, pool.Rent(0));
        }
示例#56
0
 public static IArrayOwner <T> RentAsOwner <T>(this ArrayPool <T> pool, int size)
 {
     return(new ArrayPoolBuffer <T>(pool, size));
 }
示例#57
0
        // whitespace processing needs to happen in two phases. the first is where we collapse whitespace and handle new lines
        // the second is what to do with trailing space and wrapping.
        public static int ProcessWhitespace(WhitespaceMode whitespaceMode, ref char[] buffer, char[] input, int inputSize = -1)
        {
            if (inputSize < 0)
            {
                inputSize = input.Length;
            }

            if (inputSize == 0)
            {
                return(0);
            }

            bool collapseSpaceAndTab = (whitespaceMode & WhitespaceMode.CollapseWhitespace) != 0;
            bool preserveNewLine     = (whitespaceMode & WhitespaceMode.PreserveNewLines) != 0;
            bool trimStart           = (whitespaceMode & WhitespaceMode.TrimStart) != 0;
            bool trimEnd             = (whitespaceMode & WhitespaceMode.TrimEnd) != 0;

            bool collapsing = false;

            if (buffer == null)
            {
                buffer = ArrayPool <char> .GetMinSize(inputSize);
            }

            if (buffer.Length < inputSize)
            {
                ArrayPool <char> .Resize(ref buffer, inputSize);
            }

            int writeIndex = 0;
            int start      = 0;
            int end        = inputSize;

            if (trimStart)
            {
                for (int i = 0; i < end; i++)
                {
                    char c = input[i];

                    bool isWhiteSpace = c == ' ' || c >= '\t' && c <= '\r' || (c == ' ' || c == '\x0085');

                    if (!isWhiteSpace)
                    {
                        start = i;
                        break;
                    }
                }
            }

            if (trimEnd)
            {
                for (int i = end - 1; i >= start; i--)
                {
                    char c = input[i];

                    bool isWhiteSpace = c == ' ' || c >= '\t' && c <= '\r' || (c == ' ' || c == '\x0085');

                    if (!isWhiteSpace)
                    {
                        end = i + 1;
                        break;
                    }
                }
            }

            for (int i = start; i < end; i++)
            {
                char c = input[i];

                if (c == '\n' && !preserveNewLine)
                {
                    continue;
                }

                bool isWhiteSpace = c == ' ' || c >= '\t' && c <= '\r' || (c == ' ' || c == '\x0085');

                if (c == '\n')
                {
                    if (preserveNewLine)
                    {
                        buffer[writeIndex++] = c;
                        continue;
                    }
                }

                if (collapsing)
                {
                    if (!isWhiteSpace)
                    {
                        buffer[writeIndex++] = c;
                        collapsing           = false;
                    }
                }
                else if (isWhiteSpace)
                {
                    collapsing           = collapseSpaceAndTab;
                    buffer[writeIndex++] = ' ';
                }
                else
                {
                    buffer[writeIndex++] = c;
                }
            }


            return(writeIndex);
        }
示例#58
0
        /// <summary>
        /// Calls the specified hook on this plugin
        /// </summary>
        /// <param name="name"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected sealed override object OnCallHook(string name, object[] args)
        {
            object returnvalue = null;
            bool   pooledArray = false;

            // Call all hooks that match the signature
            foreach (HookMethod h in FindHooks(name, args))
            {
                int      received = args?.Length ?? 0;
                object[] hookArgs;

                if (received != h.Parameters.Length)
                {
                    // The call argument count is different to the declared callback methods argument count
                    hookArgs    = ArrayPool.Get(h.Parameters.Length);
                    pooledArray = true;

                    if (received > 0 && hookArgs.Length > 0)
                    {
                        // Remove any additional arguments which the callback method does not declare
                        Array.Copy(args, hookArgs, Math.Min(received, hookArgs.Length));
                    }

                    if (hookArgs.Length > received)
                    {
                        // Create additional parameters for arguments excluded in this hook call
                        for (int n = received; n < hookArgs.Length; n++)
                        {
                            ParameterInfo parameter = h.Parameters[n];
                            if (parameter.DefaultValue != null && parameter.DefaultValue != DBNull.Value)
                            {
                                // Use the default value that was provided by the method definition
                                hookArgs[n] = parameter.DefaultValue;
                            }
                            else if (parameter.ParameterType.IsValueType)
                            {
                                // Use the default value for value types
                                hookArgs[n] = Activator.CreateInstance(parameter.ParameterType);
                            }
                        }
                    }
                }
                else
                {
                    hookArgs = args;
                }

                try
                {
                    returnvalue = InvokeMethod(h, hookArgs);
                }
                catch (TargetInvocationException ex)
                {
                    if (pooledArray)
                    {
                        ArrayPool.Free(hookArgs);
                    }
                    throw ex.InnerException ?? ex;
                }

                if (received != h.Parameters.Length)
                {
                    // A copy of the call arguments was used for this method call
                    for (int n = 0; n < h.Parameters.Length; n++)
                    {
                        // Copy output values for out and by reference arguments back to the calling args
                        if (h.Parameters[n].IsOut || h.Parameters[n].ParameterType.IsByRef)
                        {
                            args[n] = hookArgs[n];
                        }
                    }
                }

                if (pooledArray)
                {
                    ArrayPool.Free(hookArgs);
                }
            }

            return(returnvalue);
        }
 public MemoryStreamSlim(ArrayPool<byte> pool, int arrayMinSize)
 {
     _pool = pool;
     _arraySize = arrayMinSize;
 }
示例#60
0
        public static void RentingWithInvalidLengthThrows(int length)
        {
            ArrayPool <byte> pool = ArrayPool <byte> .Create();

            Assert.Throws <ArgumentOutOfRangeException>("minimumLength", () => pool.Rent(length));
        }