Ejemplo n.º 1
0
        public static bool IsText(IByteBuffer buf, int index, int length, Encoding encoding)
        {
            if (buf is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buf);
            }
            if (encoding is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.encoding);
            }

            int maxIndex = buf.ReaderIndex + buf.ReadableBytes;

            if (index < 0 || length < 0 || index > maxIndex - length)
            {
                ThrowHelper.ThrowIndexOutOfRangeException_IsText(index, length);
            }
            switch (encoding.CodePage)
            {
            case TextEncodings.UTF8CodePage:
                return(IsUtf8(buf, index, length));

            case TextEncodings.ASCIICodePage:
                return(IsAscii(buf, index, length));

            default:
                try
                {
                    if (buf.IsSingleIoBuffer)
                    {
                        ArraySegment <byte> segment = buf.GetIoBuffer();
                        _ = encoding.GetChars(segment.Array, segment.Offset, segment.Count);
                    }
                    else
                    {
                        IByteBuffer heapBuffer = buf.Allocator.HeapBuffer(length);
                        try
                        {
                            _ = heapBuffer.WriteBytes(buf, index, length);
                            ArraySegment <byte> segment = heapBuffer.GetIoBuffer();
                            _ = encoding.GetChars(segment.Array, segment.Offset, segment.Count);
                        }
                        finally
                        {
                            _ = heapBuffer.Release();
                        }
                    }
                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }