public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException is not thrown when charCount is less than zero.");

        try
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            int charCount = -1;
            int maxByteCount = utf8.GetMaxByteCount(charCount);

            TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown when charCount is less than zero. ");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void NegTest1()
 {
     UTF8Encoding utf8 = new UTF8Encoding();
     int charCount = -1;
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         int maxByteCount = utf8.GetMaxByteCount(charCount);
     });
 }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetMaxByteCount");

        try
        {

            UTF8Encoding utf8 = new UTF8Encoding();
            int charCount = 0;
            int maxByteCount = utf8.GetMaxByteCount(charCount);

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void PosTest1()
 {
     UTF8Encoding utf8         = new UTF8Encoding();
     int          charCount    = 0;
     int          maxByteCount = utf8.GetMaxByteCount(charCount);
 }
 public void PosTest1()
 {
     UTF8Encoding utf8 = new UTF8Encoding();
     int charCount = 0;
     int maxByteCount = utf8.GetMaxByteCount(charCount);
 }
Beispiel #6
0
        internal static ArraySegment <byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
        {
            if (count < 4)
            {
                throw new XmlException(SR.UnexpectedEndOfFile);
            }

            try
            {
                int preserve;
                ArraySegment <byte> seg;

                SupportedEncoding expectedEnc = GetSupportedEncoding(encoding);
                SupportedEncoding declEnc     = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve);
                if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc)
                {
                    ThrowExpectedEncodingMismatch(expectedEnc, declEnc);
                }

                offset += 4 - preserve;
                count  -= 4 - preserve;

                // Fastpath: UTF-8
                char[]   chars;
                byte[]   bytes;
                Encoding localEnc;
                if (declEnc == SupportedEncoding.UTF8)
                {
                    // Fastpath: No declaration
                    if (buffer[offset + 1] != '?' || buffer[offset] != '<')
                    {
                        seg = new ArraySegment <byte>(buffer, offset, count);
                        return(seg);
                    }

                    CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc);
                    seg = new ArraySegment <byte>(buffer, offset, count);
                    return(seg);
                }

                // Convert to UTF-8
                localEnc = GetSafeEncoding(declEnc);
                int inputCount = Math.Min(count, BufferLength * 2);
                chars = new char[localEnc.GetMaxCharCount(inputCount)];
                int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0);
                bytes = new byte[s_validatingUTF8.GetMaxByteCount(ccount)];
                int bcount = s_validatingUTF8.GetBytes(chars, 0, ccount, bytes, 0);

                // Check for declaration
                if (bytes[1] == '?' && bytes[0] == '<')
                {
                    CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc);
                }
                else
                {
                    // Declaration required if no out-of-band encoding
                    if (expectedEnc == SupportedEncoding.None)
                    {
                        throw new XmlException(SR.XmlDeclarationRequired);
                    }
                }

                seg = new ArraySegment <byte>(s_validatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count)));
                return(seg);
            }
            catch (DecoderFallbackException e)
            {
                throw new XmlException(SR.XmlInvalidBytes, e);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Writes an error to a stream.
        /// </summary>
        protected static void WriteErrorMessageBody(BinaryEncoder encoder, ServiceResult error)
        {
            string reason = (error.LocalizedText != null) ? error.LocalizedText.Text : null;

            // check that length is not exceeded.
            if (reason != null)
            {
                UTF8Encoding encoding = new UTF8Encoding();

                if (encoding.GetByteCount(reason) > TcpMessageLimits.MaxErrorReasonLength)
                {
                    reason = reason.Substring(0, TcpMessageLimits.MaxErrorReasonLength / encoding.GetMaxByteCount(1));
                }
            }

            encoder.WriteStatusCode(null, error.StatusCode);
            encoder.WriteString(null, reason);
        }
Beispiel #8
0
        public static ByteStringContext.InternalScope GetLowerIdSliceAndStorageKey <TTransaction>(
            TransactionOperationContext <TTransaction> context, string str, out Slice lowerIdSlice, out Slice idSlice)
            where TTransaction : RavenTransaction
        {
            // Because we need to also store escape positions for the key when we store it
            // we need to store it as a lazy string value.
            // But lazy string value has two lengths, one is the string length, and the other
            // is the actual data size with the escape positions

            // In order to resolve this, we process the key to find escape positions, then store it
            // in the table using the following format:
            //
            // [var int - string len, string bytes, number of escape positions, escape positions]
            //
            // The total length of the string is stored in the actual table (and include the var int size
            // prefix.

            if (_jsonParserState == null)
            {
                _jsonParserState = new JsonParserState();
            }

            _jsonParserState.Reset();

            int originalStrLength = str.Length;
            int strLength         = originalStrLength;

            if (strLength > MaxIdSize)
            {
                ThrowDocumentIdTooBig(str);
            }

            int maxStrSize = Encoding.GetMaxByteCount(strLength);

            int idSize = JsonParserState.VariableSizeIntSize(strLength);

            int escapePositionsSize = JsonParserState.FindEscapePositionsMaxSize(str);

            var scope = context.Allocator.Allocate(maxStrSize   // lower key
                                                   + idSize     // the size of var int for the len of the key
                                                   + maxStrSize // actual key
                                                   + escapePositionsSize, out ByteString buffer);


            byte *ptr = buffer.Ptr;

            fixed(char *pChars = str)
            {
                for (var i = 0; i < strLength; i++)
                {
                    uint ch = pChars[i];

                    // PERF: Trick to avoid multiple compare instructions on hot loops.
                    //       This is the same as (ch >= 65 && ch <= 90)
                    if (ch - 65 <= 90 - 65)
                    {
                        ptr[i] = (byte)(ch | 0x20);
                    }
                    else
                    {
                        if (ch > 127) // not ASCII, use slower mode
                        {
                            goto UnlikelyUnicode;
                        }

                        ptr[i] = (byte)ch;
                    }

                    ptr[i + idSize + maxStrSize] = (byte)ch;
                }

                _jsonParserState.FindEscapePositionsIn(ptr, ref strLength, escapePositionsSize);
                if (strLength != originalStrLength)
                {
                    var anotherStrLength = originalStrLength;
                    _jsonParserState.FindEscapePositionsIn(ptr + idSize + maxStrSize, ref anotherStrLength, escapePositionsSize);

#if DEBUG
                    if (strLength != anotherStrLength)
                    {
                        throw new InvalidOperationException($"String length mismatch between Id ({str}) and it's lowercased counterpart after finding escape positions. Original: {anotherStrLength}. Lowercased: {strLength}");
                    }
#endif
                }
            }

            var writePos = ptr + maxStrSize;

            JsonParserState.WriteVariableSizeInt(ref writePos, strLength);
            escapePositionsSize = _jsonParserState.WriteEscapePositionsTo(writePos + strLength);
            idSize = escapePositionsSize + strLength + idSize;

            Slice.External(context.Allocator, ptr + maxStrSize, idSize, out idSlice);
            Slice.External(context.Allocator, ptr, strLength, out lowerIdSlice);
            return(scope);

UnlikelyUnicode:
            scope.Dispose();
            return(UnicodeGetLowerIdAndStorageKey(context, str, out lowerIdSlice, out idSlice, maxStrSize, escapePositionsSize));
        }
Beispiel #9
0
 /// <summary>
 /// Returns true if the specified string can certainly be represented using
 /// a 16-bit unsigned integer length prefix.
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public bool IsShortString(string value)
 {
     return(utf8Encoding.GetMaxByteCount(value.Length) <= UInt16.MaxValue);
 }
Beispiel #10
0
        // ------------------------------------------------------------------------------------

        /// <summary>
        /// Send message to Snarl.
        /// Will UTF8 encode the message before sending.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="replyTimeout">(Optional - default = 1000)</param>
        /// <returns>Return zero or positive on succes. Negative on error.</returns>
        static public Int32 DoRequest(String request, UInt32 replyTimeout)
        {
            Int32  nReturn            = -1;
            IntPtr nSendMessageResult = IntPtr.Zero;
            IntPtr ptrToUtf8Request   = IntPtr.Zero;
            IntPtr ptrToCds           = IntPtr.Zero;

            byte[] utf8Request = null;

            // Test if Snarl is running
            IntPtr hWnd = GetSnarlWindow();

            if (!IsWindow(hWnd))
            {
                return(-(Int32)SnarlStatus.ErrorNotRunning);
            }

            try
            {
                // Convert to UTF8
                // utf8Request = StringToUtf8(request);
                UTF8Encoding utf8 = new UTF8Encoding();
                utf8Request = new byte[utf8.GetMaxByteCount(request.Length)];
                int convertCount = utf8.GetBytes(request, 0, request.Length, utf8Request, 0);

                // Create interop struct
                COPYDATASTRUCT cds = new COPYDATASTRUCT();
                cds.dwData = (IntPtr)0x534E4C03; // "SNL",3
                cds.cbData = convertCount;

                // Create unmanaged byte[] and copy utf8Request into it
                ptrToUtf8Request = Marshal.AllocHGlobal(convertCount);
                Marshal.Copy(utf8Request, 0, ptrToUtf8Request, convertCount);
                cds.lpData = ptrToUtf8Request;

                // Create unmanaged pointer to COPYDATASTRUCT
                ptrToCds = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(COPYDATASTRUCT)));
                Marshal.StructureToPtr(cds, ptrToCds, false);

                if (SendMessageTimeout(hWnd,
                                       (uint)WindowsMessage.WM_COPYDATA,
                                       (IntPtr)GetCurrentProcessId(),
                                       ptrToCds,
                                       SendMessageTimeoutFlags.SMTO_ABORTIFHUNG | SendMessageTimeoutFlags.SMTO_NOTIMEOUTIFNOTHUNG,
                                       replyTimeout,
                                       out nSendMessageResult) == IntPtr.Zero)
                {
                    // Error
                    int nError = Marshal.GetLastWin32Error();
                    if (nError == ERROR_TIMEOUT)
                    {
                        nReturn = -(Int32)SnarlStatus.ErrorTimedOut;
                    }
                    else
                    {
                        nReturn = -(Int32)SnarlStatus.ErrorFailed;
                    }
                }
                else
                {
                    nReturn = unchecked ((Int32)nSendMessageResult.ToInt64()); // Avoid aritmetic overflow error
                }
            }
            finally
            {
                utf8Request = null;
                Marshal.FreeHGlobal(ptrToCds);
                Marshal.FreeHGlobal(ptrToUtf8Request);
            }

            return(nReturn);
        }