Пример #1
0
        /**
         * convert byte array to Hex String.
         *
         * @param info - the propmt String
         * @param buf - the byte array which will be converted
         * @param offset - the start position of buf
         * @param length - the converted length
         * @param isOneLine16 - if true 16 bytes one line, false all bytes in one line
         * @return Hex String
         */
        public static string buf2String(string info, byte[] buf, int offset,
			int length, bool oneLine16)
        {
            int i, index;

            StringBuffer sBuf = new StringBuffer();
            sBuf.Append(info);

            for (i = 0 + offset; i < length + offset; i++)
            {
                if (i % 16 == 0)
                {
                    if (oneLine16)
                    {
                        sBuf.Append(lineSeperate);
                    }
                } else if (i % 8 == 0)
                {
                    if (oneLine16)
                    {
                        sBuf.Append("   ");
                    }
                }
                index = buf[i] < 0 ? buf[i] + DEFAULT_TABLE_LENGTH : buf[i];
                sBuf.Append(convertTable[index]);
            }
            return sBuf.ToString();
        }
Пример #2
0
    public void IsExtendedTest(string path, bool expected)
    {
        StringBuffer sb = new StringBuffer();
        sb.Append(path);
        Assert.Equal(expected, PathInternal.IsExtended(sb));

        Assert.Equal(expected, PathInternal.IsExtended(path));
    }
Пример #3
0
        private static string ByteArrayToHexString(byte[] b)
        {
            StringBuffer resultSb = new StringBuffer();
            for (int i = 0; i < b.Length; i++)
                resultSb.Append(ByteToHexString(b[i]));

            return resultSb.ToString();
        }
		public void Test1()
		{
			StringBuffer buf = new StringBuffer(100);
			
			Assert.AreEqual(0, buf.Length);
			Assert.AreEqual("", buf.ToString());
			
			buf.Append('a');
			buf.Append('b');
			buf.Append('c');
			
			Assert.AreEqual(3, buf.Length);
			Assert.AreEqual("abc", buf.ToString());
			
			buf.Clear();
			
			Assert.AreEqual(0, buf.Length);
			Assert.AreEqual("", buf.ToString());
		}
Пример #5
0
        public static void FormatDouble(StringBuffer formatter, double value, StringView specifier, CachedCulture culture)
        {
            int digits;
            int precision = DoublePrecision;
            var fmt = ParseFormatSpecifier(specifier, out digits);

            // ANDing with 0xFFDF has the effect of uppercasing the character
            switch (fmt & 0xFFDF) {
                case 'G':
                    if (digits > 15)
                        precision = 17;
                    break;

                case 'E':
                    if (digits > 14)
                        precision = 17;
                    break;
            }

            var number = new Number();
            var buffer = stackalloc char[MaxFloatingDigits + 1];
            number.Digits = buffer;
            DoubleToNumber(value, precision, ref number);

            if (number.Scale == ScaleNaN) {
                formatter.Append(culture.NaN);
                return;
            }

            if (number.Scale == ScaleInf) {
                if (number.Sign > 0)
                    formatter.Append(culture.NegativeInfinity);
                else
                    formatter.Append(culture.PositiveInfinity);
                return;
            }

            if (fmt != 0)
                NumberToString(formatter, ref number, fmt, digits, culture);
            else
                NumberToCustomFormatString(formatter, ref number, specifier, culture);
        }
        string GetColourString()
        {
            int count = 0;
            for( int i = ' '; i <= '~'; i++ ) {
                if( i >= 'A' && i <= 'F' ) continue;
                if( game.Drawer2D.Colours[i].A > 0 ) count++;
            }

            StringBuffer buffer = new StringBuffer( count * 4 );
            int index = 0;
            for( int i = ' '; i <= '~'; i++ ) {
                if( i >= 'A' && i <= 'F' ) continue;
                if( game.Drawer2D.Colours[i].A == 0 ) continue;

                buffer.Append( ref index, '&' ).Append( ref index, (char)i )
                    .Append( ref index, '%' ).Append( ref index, (char)i );
            }
            return buffer.ToString();
        }
Пример #7
0
        /// <summary>
        /// Returns a human readable text of this entry
        /// </summary>
        /// <returns></returns>
        public unsafe StringBuffer ToStringBuffer()
        {
            var buf = new StringBuffer();

            buf.Append("0x");
            buf.Append((uint)MethodDefinition->Method, "X");
            buf.Append("+0x");
            buf.Append(Offset, "X");
            buf.Append(" ");

            var idx = MethodName.IndexOf(' ') + 1; //Skip return type
            buf.Append(MethodName, idx);
            return buf;
        }
Пример #8
0
 public static string toHexstring(byte[] abyte0, int beginIndex, int endIndex, bool spaceFlag)
 {
     if (null == abyte0)
         return null;
     if (0 == abyte0.Length)
         return "";
     StringBuffer sbuf = new StringBuffer ();
     AppendHex (sbuf, abyte0 [beginIndex]);
     for (int i = (beginIndex + 1); i < endIndex; i++) {
         if (spaceFlag)
             sbuf.Append (' ');
         AppendHex (sbuf, abyte0 [i]);
     }
     string returnstring = sbuf.ToString ();
     sbuf = null;
     return returnstring;
 }
Пример #9
0
 private static void AppendHex(StringBuffer stringbuffer, byte byte0)
 {
     stringbuffer.Append (toHexChar (byte0 >> 4));
     stringbuffer.Append (toHexChar (byte0));
 }
Пример #10
0
        /**
          * Method fill space , converted string length to LCD_WIDTH
          *
          * @param The string to be format.
          *
          */
        public static string fillShowSpace(string formatString)
        {
            if (null == formatString)
                return "";

            if (formatString.Length <= LCD_WIDTH) {
                int len = 8 - (formatString.Length / 2);
                StringBuffer sbuf = new StringBuffer ();
                sbuf.Append (space8, 0, len);
                sbuf.Append (formatString);
                sbuf.Append (space8, 0, len);
                sbuf.SetLength (LCD_WIDTH);

                string returnstring = sbuf.ToString ();
                sbuf = null;
                return returnstring;
            } else {
                return formatString.Substring (0, LCD_WIDTH);
            }
        }
Пример #11
0
        /*
           * Converts encoded &#92;uxxxx to unicode chars and changes special saved
           * chars to their original forms
           *
           * @param s
           *            the  byte arrary needing convert.
           * @param offset
           *            the offset of byte arrary
           * @param lengthFlag
           *            Whether add one byte of length in the result.
           *            <code>true</code> add one byte of length in the result
           * @return  the convert result of the byte arrary.
           */
        public static string loadConvert(byte[] s, int offset, bool lengthFlag)
        {
            if (null == s || (offset + (lengthFlag ? 1 : 0)) > s.Length)
                throw new IllegalArgumentException ("invalid byte arrary");

            char aChar;
            int len = (s.Length - offset);

            if (lengthFlag) {
                len = s [offset] & 0xFF;
                offset++;
            }

            StringBuffer outBuffer = new StringBuffer (len);

            for (int x = offset; x < (offset + len);) {
                aChar = (char)s [x++];
                if (aChar == '\\') {
                    aChar = (char)s [x++];
                    if (aChar == 'u') {
                        // Read the xxxx
                        int value = 0;
                        for (int i = 0; i < 4; i++) {
                            aChar = (char)s [x++];
                            switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException ("Malformed \\uxxxx encoding.");
                            }
                        }
                        outBuffer.Append ((char)value);
                    } else {
                        if (aChar == 't')
                            aChar = '\t';
                        else if (aChar == 'r')
                            aChar = '\r';
                        else if (aChar == 'n')
                            aChar = '\n';
                        else if (aChar == 'f')
                            aChar = '\f';
                        outBuffer.Append (aChar);
                    }
                } else
                    outBuffer.Append (aChar);
            }
            return outBuffer.ToString ();
        }
Пример #12
0
        public static string dump(byte[] abyte0, int beginIndex, int endIndex, bool spaceFlag, bool asciiFlag, bool lineNumberFlag, int linenumber)
        {
            byte[] cont = abyte0;
            if(abyte0 == null || cont.Length  == 0)
                return "";

            string outMsg = "";
            int totalLine = (endIndex - beginIndex) / 16;
            int lineNumber, q;
            int offset = beginIndex;
            byte byte0;
            StringBuffer stringbuffer = new StringBuffer(6 + (spaceFlag?48:32));
            StringBuffer asciibuffer = new StringBuffer();
            string printString;
            int stringcount;
            int asccicount;

            if (linenumber < 0)
                linenumber = 0;
            else
                linenumber = linenumber % 10000;

            for(int i = 0; i <= totalLine; i++, linenumber++)
            {
                if (offset < endIndex) {
                    stringcount = stringbuffer.Length();
                    asccicount = asciibuffer.Length();
                    stringbuffer.Delete(0, stringcount);
                    asciibuffer.Delete(0, asccicount);
                    if (lineNumberFlag) {
                        stringbuffer.Append("0000: ");
                        lineNumber = linenumber;
                        for(byte0 = 3; byte0 >=0; byte0--){
                            q = (lineNumber * 52429) >> (16+3);
                            stringbuffer.SetCharAt(byte0, toHexChar(lineNumber - ((q << 3) + (q << 1)))); // toHexChar(lineNumber-(q*10))
                            lineNumber = q;
                            if (0 == lineNumber) break;
                        }
                    }
                    for(int j = 0; j < 16; j++, offset++)
                    {
                        if (offset < endIndex) {
                            byte0 = abyte0[offset];
                            stringbuffer.Append(toHexChar(byte0 >> 4));
                            stringbuffer.Append(toHexChar(byte0));
                            if (spaceFlag)
                                stringbuffer.Append(' ');
                            if (asciiFlag) {
                                if (byte0 >= 0x20 && byte0 <= 0x7E)
                                    asciibuffer.Append((char)byte0);
                                else
                                    asciibuffer.Append('.');
                            }
                        } else {
                            stringbuffer.Append(' ');
                            stringbuffer.Append(' ');
                            if (spaceFlag)
                                stringbuffer.Append(' ');
                        }
                    }
                    if (asciiFlag)
                        printString = stringbuffer.ToString() + "; " + asciibuffer.ToString();
                    else
                        printString = stringbuffer.ToString();
                    //        printLine(printString);
                    outMsg =  outMsg + printString + "\n";
                } else {
                    break;
                }
            }
            printString = null;
            stringbuffer = asciibuffer = null;
            return outMsg;
        }
        void TabKey()
        {
            int pos = caretPos == -1 ? buffer.Length - 1 : caretPos;
            int start = pos;
            char[] value = buffer.value;

            while( start >= 0 && IsNameChar( value[start] ) )
                start--;
            start++;
            if( pos < 0 || start > pos ) return;

            string part = new String( value, start, pos + 1 - start );
            List<string> matches = new List<string>();
            game.Chat.Add( null, MessageType.ClientStatus5 );

            bool extList = game.Network.UsingExtPlayerList;
            CpeListInfo[] info = game.CpePlayersList;
            Player[] players = game.Players.Players;
            for( int i = 0; i < EntityList.MaxCount; i++ ) {
                if( extList && info[i] == null ) continue;
                if( !extList && players[i] == null ) continue;

                string rawName = extList ? info[i].PlayerName : players[i].DisplayName;
                string name = Utils.StripColours( rawName );
                if( name.StartsWith( part, StringComparison.OrdinalIgnoreCase ) )
                    matches.Add( name );
            }

            if( matches.Count == 1 ) {
                if( caretPos == -1 ) pos++;
                int len = pos - start;
                for( int i = 0; i < len; i++ )
                    buffer.DeleteAt( start );
                if( caretPos != -1 ) caretPos -= len;
                AppendText( matches[0] );
            } else if( matches.Count > 1 ) {
                StringBuffer sb = new StringBuffer( 64 );
                int index = 0;
                sb.Append( ref index, "&e" );
                sb.AppendNum( ref index, matches.Count );
                sb.Append( ref index, " matching names: " );

                foreach( string match in matches ) {
                    if( (match.Length + 1 + sb.Length) > LineLength ) break;
                    sb.Append( ref index, match );
                    sb.Append( ref index, ' ' );
                }
                game.Chat.Add( sb.ToString(), MessageType.ClientStatus5 );
            }
        }
Пример #14
0
 public static void AppendFloat2(this StringBuffer sb, float2 value)
 {
     sb.Append(value.x);
     sb.Append(',');
     sb.Append(value.y);
 }
Пример #15
0
        /// <summary>
        /// Called once an &amp; character is being seen.
        /// </summary>
        /// <returns>The entity token.</returns>
        private String CharacterReference()
        {
            var c       = GetNext();
            var start   = StringBuffer.Length;
            var hex     = false;
            var numeric = c == Symbols.Num;

            if (numeric)
            {
                c   = GetNext();
                hex = c == 'x' || c == 'X';

                if (hex)
                {
                    c = GetNext();

                    while (c.IsHex())
                    {
                        StringBuffer.Append(c);
                        c = GetNext();
                    }
                }
                else
                {
                    while (c.IsDigit())
                    {
                        StringBuffer.Append(c);
                        c = GetNext();
                    }
                }
            }
            else if (c.IsXmlNameStart())
            {
                do
                {
                    StringBuffer.Append(c);
                    c = GetNext();
                }while (c.IsXmlName());
            }

            var length = StringBuffer.Length - start;

            if (c == Symbols.Semicolon && length > 0)
            {
                if (numeric)
                {
                    var content = StringBuffer.ToString(start, length);
                    var number  = hex ? content.FromHex() : content.FromDec();

                    if (number.IsValidAsCharRef())
                    {
                        StringBuffer.Remove(start, length);
                        return(Char.ConvertFromUtf32(number));
                    }

                    StringBuffer.Append(c);
                }
                else
                {
                    var content = StringBuffer.Append(c).ToString(start, ++length);
                    var entity  = _resolver.GetSymbol(content);

                    if (!String.IsNullOrEmpty(entity))
                    {
                        StringBuffer.Remove(start, length);
                        return(entity);
                    }
                }

                if (!IsSuppressingErrors)
                {
                    throw XmlParseError.CharacterReferenceInvalidCode.At(_position);
                }
            }

            if (!IsSuppressingErrors)
            {
                throw XmlParseError.CharacterReferenceNotTerminated.At(GetCurrentPosition());
            }

            StringBuffer.Insert(start, Symbols.Ampersand);
            return(String.Empty);
        }
Пример #16
0
        /*
         * Converts unicodes to encoded &#92;uxxxx and writes out any of the
         * characters in specialSaveChars with a preceding slash
         *
         * @param theString
         *            the string needing convert.
         * @param dst
         *            Save of the result
         * @param offset
         *            the offset of result
         * @param escapeSpace
         *            if <code>true</code>, escape Space
         * @param lengthFlag
         *            Whether add one byte of length in the result.
         *            <code>true</code> add one byte of length in the result
         * @param getLengthFlag
         *            Calculate the length of result, if <code>true</code>, thestring length that return.
         * @return  if getLengthFlag = false, return offset of the result.
         *          if getLengthFlag = true, the length of the sequence of characters represented by this
         *          object.
         */
        public static int saveConvert(string theString, byte[] dst, int offset, bool escapeSpace, bool lengthFlag, bool getLengthFlag)
        {
            if (false == getLengthFlag &&
                (null == dst || dst.Length < (offset + (lengthFlag ? 1 : 0)) ||
                 dst.Length < 1 || offset < 0))
            {
                return(-1);
            }
            if (null == theString)
            {
                theString = "";
            }
            int length = theString.Length;

            StringBuffer outBuffer = new StringBuffer(length * 2);

            for (int x = 0; x < length; x++)
            {
                char aChar = theString [x];
                switch (aChar)
                {
                case ' ':
                    if (x == 0 || escapeSpace)
                    {
                        outBuffer.Append('\\');
                    }

                    outBuffer.Append(' ');
                    break;

                case '\\':
                    outBuffer.Append('\\');
                    break;

                case '\t':
                    outBuffer.Append('\\');
                    outBuffer.Append('t');
                    break;

                case '\n':
                    outBuffer.Append('\\');
                    outBuffer.Append('n');
                    break;

                case '\r':
                    outBuffer.Append('\\');
                    outBuffer.Append('r');
                    break;

                case '\f':
                    outBuffer.Append('\\');
                    outBuffer.Append('f');
                    break;

                default:
                    if ((aChar < 0x0020) || (aChar > 0x007e))
                    {
                        outBuffer.Append('\\');
                        outBuffer.Append('u');
                        outBuffer.Append(toHexChar((aChar >> 12) & 0xF));
                        outBuffer.Append(toHexChar((aChar >> 8) & 0xF));
                        outBuffer.Append(toHexChar((aChar >> 4) & 0xF));
                        outBuffer.Append(toHexChar(aChar & 0xF));
                    }
                    else
                    {
                        if (specialSaveChars.IndexOf(aChar) != -1)
                        {
                            outBuffer.Append('\\');
                        }
                        outBuffer.Append(aChar);
                    }
                    break;
                }
            }
            length = outBuffer.Length();
            if (length > 255)
            {
                length = 255;
            }
            if (!getLengthFlag)
            {
                if (dst.Length >= offset + length + (lengthFlag ? 1 : 0))
                {
                    if (lengthFlag)
                    {
                        dst [offset] = (byte)(length & 0xFF);
                        offset++;
                    }
                    for (int i = 0; i < length; i++)
                    {
                        dst [offset] = (byte)outBuffer.CharAt(i);
                        offset++;
                    }
                    length = offset;
                }
                else
                {
                    length = -1;
                }
            }
            else
            {
                if (lengthFlag)
                {
                    length = length + 1;
                }
            }

            outBuffer = null;

            return(length);
        }
Пример #17
0
 private static void AppendHex(StringBuffer stringbuffer, byte byte0)
 {
     stringbuffer.Append(toHexChar(byte0 >> 4));
     stringbuffer.Append(toHexChar(byte0));
 }
Пример #18
0
        /*
         * Converts encoded &#92;uxxxx to unicode chars and changes special saved
         * chars to their original forms
         *
         * @param s
         *            the  byte arrary needing convert.
         * @param offset
         *            the offset of byte arrary
         * @param lengthFlag
         *            Whether add one byte of length in the result.
         *            <code>true</code> add one byte of length in the result
         * @return  the convert result of the byte arrary.
         */
        public static string loadConvert(byte[] s, int offset, bool lengthFlag)
        {
            if (null == s || (offset + (lengthFlag ? 1 : 0)) > s.Length)
            {
                throw new IllegalArgumentException("invalid byte arrary");
            }

            char aChar;
            int  len = (s.Length - offset);

            if (lengthFlag)
            {
                len = s [offset] & 0xFF;
                offset++;
            }

            StringBuffer outBuffer = new StringBuffer(len);

            for (int x = offset; x < (offset + len);)
            {
                aChar = (char)s [x++];
                if (aChar == '\\')
                {
                    aChar = (char)s [x++];
                    if (aChar == 'u')
                    {
                        // Read the xxxx
                        int value = 0;
                        for (int i = 0; i < 4; i++)
                        {
                            aChar = (char)s [x++];
                            switch (aChar)
                            {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;

                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;

                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;

                            default:
                                throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
                            }
                        }
                        outBuffer.Append((char)value);
                    }
                    else
                    {
                        if (aChar == 't')
                        {
                            aChar = '\t';
                        }
                        else if (aChar == 'r')
                        {
                            aChar = '\r';
                        }
                        else if (aChar == 'n')
                        {
                            aChar = '\n';
                        }
                        else if (aChar == 'f')
                        {
                            aChar = '\f';
                        }
                        outBuffer.Append(aChar);
                    }
                }
                else
                {
                    outBuffer.Append(aChar);
                }
            }
            return(outBuffer.ToString());
        }
Пример #19
0
        public async Task Handle(SendHelpMessageCommand command)
        {
            var sb = new StringBuffer();

            sb.Append(StringContants.Help);
            sb.Append(StringContants.CommonCommands);
            sb.Append(string.Format("{0} - an excel export of all trades\n", TelegramCommands.CommonExcel));
            sb.Append(string.Format("{0} - profit information for pair\n", TelegramCommands.CommonPairProfit));

            if (_coinigyConfig.Enabled)
            {
                sb.Append(StringContants.CoinigyCommands);
                sb.Append(string.Format("{0} - coinigy accounts and their balance\n", TelegramCommands.CoinigyAccountList));
                sb.Append(string.Format("{0} - total balance from all acounts\n", TelegramCommands.CoinigyTotalBalance));
            }

            if (_bittrexConfig.Enabled)
            {
                sb.Append(StringContants.BittrexCommands);
                sb.Append(string.Format("{0} - upload bittrex order export\n", TelegramCommands.BittrexTradeExportUpload));
                sb.Append(string.Format("{0} - bittrex account summary\n", TelegramCommands.BittrexBalanceInfo));
            }
            if (_poloniexConfig.Enabled)
            {
                sb.Append(StringContants.PoloCommands);
                sb.Append(string.Format("{0} - poloniex account summary\n", TelegramCommands.PoloniexBalanceInfo));
                sb.Append(string.Format("{0} - reset trades database from poloniex\n", TelegramCommands.PoloniexTradeReset));
            }
            if (_binanceConfig.Enabled)
            {
                sb.Append(StringContants.BinanceCommands);
                sb.Append(string.Format("{0} - binance account summary\n", TelegramCommands.BinanceBalanceInfo));
            }

            _log.LogInformation("Sending help message");

            await _bus.SendAsync(new SendMessageCommand(sb));
        }
Пример #20
0
        /// <summary>
        /// Decodes a {@code application/x-www-form-urlencoded} string using a specific
        /// encoding scheme.
        /// The supplied encoding is used to determine
        /// what characters are represented by any consecutive sequences of the
        /// form "<i>{@code %xy}</i>".
        /// <para>
        /// <em><strong>Note:</strong> The <a href=
        /// "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
        /// World Wide Web Consortium Recommendation</a> states that
        /// UTF-8 should be used. Not doing so may introduce
        /// incompatibilities.</em>
        ///
        /// </para>
        /// </summary>
        /// <param name="s"> the {@code String} to decode </param>
        /// <param name="enc">   The name of a supported
        ///    <a href="../lang/package-summary.html#charenc">character
        ///    encoding</a>. </param>
        /// <returns> the newly decoded {@code String} </returns>
        /// <exception cref="UnsupportedEncodingException">
        ///             If character encoding needs to be consulted, but
        ///             named character encoding is not supported </exception>
        /// <seealso cref= URLEncoder#encode(java.lang.String, java.lang.String)
        /// @since 1.4 </seealso>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static String decode(String s, String enc) throws UnsupportedEncodingException
        public static String Decode(String s, String enc)
        {
            bool         needToChange = false;
            int          numChars     = s.Length();
            StringBuffer sb           = new StringBuffer(numChars > 500 ? numChars / 2 : numChars);
            int          i            = 0;

            if (enc.Length() == 0)
            {
                throw new UnsupportedEncodingException("URLDecoder: empty string enc parameter");
            }

            char c;

            sbyte[] bytes = null;
            while (i < numChars)
            {
                c = s.CharAt(i);
                switch (c)
                {
                case '+':
                    sb.Append(' ');
                    i++;
                    needToChange = true;
                    break;

                case '%':
                    /*
                     * Starting with this instance of %, process all
                     * consecutive substrings of the form %xy. Each
                     * substring %xy will yield a byte. Convert all
                     * consecutive  bytes obtained this way to whatever
                     * character(s) they represent in the provided
                     * encoding.
                     */

                    try
                    {
                        // (numChars-i)/3 is an upper bound for the number
                        // of remaining bytes
                        if (bytes == null)
                        {
                            bytes = new sbyte[(numChars - i) / 3];
                        }
                        int pos = 0;

                        while (((i + 2) < numChars) && (c == '%'))
                        {
                            int v = Convert.ToInt32(StringHelperClass.SubstringSpecial(s, i + 1, i + 3), 16);
                            if (v < 0)
                            {
                                throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value");
                            }
                            bytes[pos++] = (sbyte)v;
                            i           += 3;
                            if (i < numChars)
                            {
                                c = s.CharAt(i);
                            }
                        }

                        // A trailing, incomplete byte encoding such as
                        // "%x" will cause an exception to be thrown

                        if ((i < numChars) && (c == '%'))
                        {
                            throw new IllegalArgumentException("URLDecoder: Incomplete trailing escape (%) pattern");
                        }

                        sb.Append(StringHelperClass.NewString(bytes, 0, pos, enc));
                    }
                    catch (NumberFormatException e)
                    {
                        throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - " + e.Message);
                    }
                    needToChange = true;
                    break;

                default:
                    sb.Append(c);
                    i++;
                    break;
                }
            }

            return(needToChange? sb.ToString() : s);
        }
Пример #21
0
 private static void AppendUnregistered(StringBuffer buffer, byte *valuePtr, int size)
 {
     buffer.Append("Unmanaged(0x");
     HexUtils.AppendValueAsHex(buffer, valuePtr, size);
     buffer.Append(")");
 }
Пример #22
0
        static void Int64ToHexStr(StringBuffer formatter, ulong value, int hexBase, int digits)
        {
            var buffer = stackalloc char[100];
            char* ptr;
            if (High32(value) != 0) {
                Int32ToHexChars(buffer + 100, Low32(value), hexBase, 8);
                ptr = Int32ToHexChars(buffer + 100 - 8, High32(value), hexBase, digits - 8);
            }
            else {
                if (digits < 1)
                    digits = 1;
                ptr = Int32ToHexChars(buffer + 100, Low32(value), hexBase, digits);
            }

            formatter.Append(ptr, (int)(buffer + 100 - ptr));
        }
Пример #23
0
        /* Normalize the given pathname, whose length is len, starting at the given
         * offset; everything before this offset is already normal. */
        private String Normalize(String path, int len, int off)
        {
            if (len == 0)
            {
                return(path);
            }
            if (off < 3)             // Avoid fencepost cases with UNC pathnames
            {
                off = 0;
            }
            int          src;
            char         slash = this.Slash;
            StringBuffer sb    = new StringBuffer(len);

            if (off == 0)
            {
                /* Complete normalization, including prefix */
                src = NormalizePrefix(path, len, sb);
            }
            else
            {
                /* Partial normalization */
                src = off;
                sb.Append(path.Substring(0, off));
            }

            /* Remove redundant slashes from the remainder of the path, forcing all
             * slashes into the preferred slash */
            while (src < len)
            {
                char c = path.CharAt(src++);
                if (IsSlash(c))
                {
                    while ((src < len) && IsSlash(path.CharAt(src)))
                    {
                        src++;
                    }
                    if (src == len)
                    {
                        /* Check for trailing separator */
                        int sn = sb.Length();
                        if ((sn == 2) && (sb.CharAt(1) == ':'))
                        {
                            /* "z:\\" */
                            sb.Append(slash);
                            break;
                        }
                        if (sn == 0)
                        {
                            /* "\\" */
                            sb.Append(slash);
                            break;
                        }
                        if ((sn == 1) && (IsSlash(sb.CharAt(0))))
                        {
                            /* "\\\\" is not collapsed to "\\" because "\\\\" marks
                             * the beginning of a UNC pathname.  Even though it is
                             * not, by itself, a valid UNC pathname, we leave it as
                             * is in order to be consistent with the win32 APIs,
                             * which treat this case as an invalid UNC pathname
                             * rather than as an alias for the root directory of
                             * the current drive. */
                            sb.Append(slash);
                            break;
                        }

                        /* Path does not denote a root directory, so do not append
                         * trailing slash */
                        break;
                    }
                    else
                    {
                        sb.Append(slash);
                    }
                }
                else
                {
                    sb.Append(c);
                }
            }

            String rv = sb.ToString();

            return(rv);
        }
Пример #24
0
        static void NumberToString(StringBuffer formatter, ref Number number, char format, int maxDigits, CachedCulture culture, bool isDecimal = false)
        {
            // ANDing with 0xFFDF has the effect of uppercasing the character
            switch (format & 0xFFDF) {
                case 'C':
                    {
                        var cultureData = culture.CurrencyData;
                        var bufferSize = cultureData.GetBufferSize(ref maxDigits, number.Scale);
                        RoundNumber(ref number, number.Scale + maxDigits);

                        var buffer = stackalloc char[bufferSize];
                        var ptr = FormatCurrency(
                            buffer,
                            ref number,
                            maxDigits,
                            cultureData,
                            number.Sign > 0 ? culture.CurrencyNegativePattern : culture.CurrencyPositivePattern,
                            culture.CurrencySymbol
                        );

                        formatter.Append(buffer, (int)(ptr - buffer));
                        break;
                    }

                case 'F':
                    {
                        var cultureData = culture.FixedData;
                        var bufferSize = cultureData.GetBufferSize(ref maxDigits, number.Scale);
                        RoundNumber(ref number, number.Scale + maxDigits);

                        var buffer = stackalloc char[bufferSize];
                        var ptr = buffer;
                        if (number.Sign > 0)
                            AppendString(&ptr, cultureData.NegativeSign);

                        ptr = FormatFixed(ptr, ref number, maxDigits, cultureData);
                        formatter.Append(buffer, (int)(ptr - buffer));
                        break;
                    }

                case 'N':
                    {
                        var cultureData = culture.NumberData;
                        var bufferSize = cultureData.GetBufferSize(ref maxDigits, number.Scale);
                        RoundNumber(ref number, number.Scale + maxDigits);

                        var buffer = stackalloc char[bufferSize];
                        var ptr = FormatNumber(
                            buffer,
                            ref number,
                            maxDigits,
                            number.Sign > 0 ? culture.NumberNegativePattern : culture.NumberPositivePattern,
                            cultureData
                        );

                        formatter.Append(buffer, (int)(ptr - buffer));
                        break;
                    }

                case 'E':
                    {
                        var cultureData = culture.ScientificData;
                        var bufferSize = cultureData.GetBufferSize(ref maxDigits, number.Scale);
                        maxDigits++;

                        RoundNumber(ref number, maxDigits);

                        var buffer = stackalloc char[bufferSize];
                        var ptr = buffer;
                        if (number.Sign > 0)
                            AppendString(&ptr, cultureData.NegativeSign);

                        ptr = FormatScientific(
                            ptr,
                            ref number,
                            maxDigits,
                            format, // TODO: fix casing
                            cultureData.DecimalSeparator,
                            culture.PositiveSign,
                            culture.NegativeSign
                        );

                        formatter.Append(buffer, (int)(ptr - buffer));
                        break;
                    }

                case 'P':
                    {
                        number.Scale += 2;
                        var cultureData = culture.PercentData;
                        var bufferSize = cultureData.GetBufferSize(ref maxDigits, number.Scale);
                        RoundNumber(ref number, number.Scale + maxDigits);

                        var buffer = stackalloc char[bufferSize];
                        var ptr = FormatPercent(
                            buffer,
                            ref number,
                            maxDigits,
                            cultureData,
                            number.Sign > 0 ? culture.PercentNegativePattern : culture.PercentPositivePattern,
                            culture.PercentSymbol
                        );

                        formatter.Append(buffer, (int)(ptr - buffer));
                        break;
                    }

                case 'G':
                    {
                        var enableRounding = true;
                        if (maxDigits < 1) {
                            if (isDecimal && maxDigits == -1) {
                                // if we're formatting a decimal, default to 29 digits precision
                                // only for G formatting without a precision specifier
                                maxDigits = DecimalPrecision;
                                enableRounding = false;
                            }
                            else
                                maxDigits = number.Precision;
                        }

                        var bufferSize = maxDigits + culture.DecimalBufferSize;
                        var buffer = stackalloc char[bufferSize];
                        var ptr = buffer;

                        // round for G formatting only if a precision is given
                        // we need to handle the minus zero case also
                        if (enableRounding)
                            RoundNumber(ref number, maxDigits);
                        else if (isDecimal && number.Digits[0] == 0)
                            number.Sign = 0;

                        if (number.Sign > 0)
                            AppendString(&ptr, culture.NegativeSign);

                        ptr = FormatGeneral(
                            ptr,
                            ref number,
                            maxDigits,
                            (char)(format - ('G' - 'E')),
                            culture.NumberData.DecimalSeparator,
                            culture.PositiveSign,
                            culture.NegativeSign,
                            !enableRounding
                        );

                        formatter.Append(buffer, (int)(ptr - buffer));
                        break;
                    }

                default:
                    throw new FormatException(string.Format(SR.UnknownFormatSpecifier, format));
            }
        }
Пример #25
0
        public static byte[] decodeBitmap(Bitmap bmp)
        {
            int bmpWidth  = bmp.Width;
            int bmpHeight = bmp.Height;

            List <string> list = new List <string>(); //binaryString list
            StringBuffer  sb;


            int bitLen    = bmpWidth / 8;
            int zeroCount = bmpWidth % 8;

            string zeroStr = "";

            if (zeroCount > 0)
            {
                bitLen = bmpWidth / 8 + 1;
                for (int i = 0; i < (8 - zeroCount); i++)
                {
                    zeroStr = zeroStr + "0";
                }
            }

            for (int i = 0; i < bmpHeight; i++)
            {
                sb = new StringBuffer();
                for (int j = 0; j < bmpWidth; j++)
                {
                    int color = bmp.GetPixel(j, i);

                    int r = (color >> 16) & 0xff;
                    int g = (color >> 8) & 0xff;
                    int b = color & 0xff;

                    // if color close to white,bit='0', else bit='1'
                    if (r > 160 && g > 160 && b > 160)
                    {
                        sb.Append("0");
                    }
                    else
                    {
                        sb.Append("1");
                    }
                }
                if (zeroCount > 0)
                {
                    sb.Append(zeroStr);
                }
                list.Add(sb.ToString());
            }

            List <string> bmpHexList       = binaryListToHexStringList(list);
            string        commandHexString = "1D763000";
            string        widthHexString   = Integer
                                             .ToHexString(bmpWidth % 8 == 0 ? bmpWidth / 8
                            : (bmpWidth / 8 + 1));

            if (widthHexString.Length > 2)
            {
                //Log.e("decodeBitmap error", " width is too large");
                return(null);
            }
            else if (widthHexString.Length == 1)
            {
                widthHexString = "0" + widthHexString;
            }
            widthHexString = widthHexString + "00";

            string heightHexString = Integer.ToHexString(bmpHeight);

            if (heightHexString.Length > 2)
            {
                //Log.e("decodeBitmap error", " height is too large");
                return(null);
            }
            else if (heightHexString.Length == 1)
            {
                heightHexString = "0" + heightHexString;
            }
            heightHexString = heightHexString + "00";

            List <string> commandList = new List <string>();

            commandList.Add(commandHexString + widthHexString + heightHexString);
            commandList.AddRange(bmpHexList);

            return(hexList2Byte(commandList));
        }
Пример #26
0
 /// <summary>
 /// Read a line of characters from this reader.
 /// </summary>
 /// <returns></returns>
 public virtual string ReadLine()
 {
     var buffer = new StringBuffer();
     int ch;
     while (true)
     {
         ch = Read();
         if (ch < 0)
         {
             if (buffer.Length() == 0)
                 return null;
             return buffer.ToString();
         }
         if ((ch == (int)'\n') || (ch == (int)'\r'))
         {
             break;
         }
         buffer.Append((char) ch);
     }
     if ((ch == 13) && (Peek() == 10))
     {
         Read(); // Skip
     }
     return buffer.ToString();
 }
Пример #27
0
            public override StringBuffer Format(long value, StringBuffer stringBuffer, FieldPosition fieldPosition)
            {
                var l_hex = Int64.ToHexString(value);
                if (upperCase) l_hex = l_hex.ToUpper();
                int l_pad = numDigits - l_hex.Length;
                l_pad = (0 < l_pad) ? l_pad : 0;

                var l_extended = new StringBuffer();
                for (int i = 0; i < l_pad; i++)
                {
                    l_extended.Append('0');
                }
                l_extended.Append(l_hex);

                return l_extended;
            }
Пример #28
0
 /// <summary>
 /// Read the remainder of the reader and return it as string.
 /// </summary>
 public virtual string ReadToEnd()
 {
     var tmp = new char[4096];
     var buffer = new StringBuffer();
     int len;
     while ((len = Read(tmp, 0, tmp.Length)) > 0)
     {
         buffer.Append(tmp, 0, len);
     }
     return buffer.ToString();
 }
Пример #29
0
        /// <summary>
        /// Called once an &amp; character is being seen.
        /// </summary>
        /// <param name="c">The next character after the &amp; character.</param>
        /// <returns>The entity token.</returns>
        String CharacterReference(Char c)
        {
            var start   = StringBuffer.Length;
            var hex     = false;
            var numeric = c == Symbols.Num;

            if (numeric)
            {
                c   = GetNext();
                hex = c == 'x' || c == 'X';

                if (hex)
                {
                    c = GetNext();

                    while (c.IsHex())
                    {
                        StringBuffer.Append(c);
                        c = GetNext();
                    }
                }
                else
                {
                    while (c.IsDigit())
                    {
                        StringBuffer.Append(c);
                        c = GetNext();
                    }
                }
            }
            else if (c.IsXmlNameStart())
            {
                do
                {
                    StringBuffer.Append(c);
                    c = GetNext();
                }while (c.IsXmlName());
            }

            if (c == Symbols.Semicolon && StringBuffer.Length > start)
            {
                var length  = StringBuffer.Length - start;
                var content = StringBuffer.ToString(start, length);
                StringBuffer.Remove(start, length);

                if (numeric)
                {
                    var number = numeric ? content.FromHex() : content.FromDec();

                    if (!number.IsValidAsCharRef())
                    {
                        throw XmlParseError.CharacterReferenceInvalidNumber.At(_position);
                    }

                    return(number.ConvertFromUtf32());
                }
                else
                {
                    var entity = _resolver.GetSymbol(content);

                    if (String.IsNullOrEmpty(entity))
                    {
                        throw XmlParseError.CharacterReferenceInvalidCode.At(_position);
                    }

                    return(entity);
                }
            }

            throw XmlParseError.CharacterReferenceNotTerminated.At(GetCurrentPosition());
        }
Пример #30
0
        // ===== privates =====

        internal virtual void AddToBuffer(StringBuffer toAddTo, bool showExtension, bool showWhiteSpace, PatternEntry lastEntry)
        {
            if (showWhiteSpace && toAddTo.Length() > 0)
            {
                if (Strength_Renamed == Collator.PRIMARY || lastEntry != null)
                {
                    toAddTo.Append('\n');
                }
                else
                {
                    toAddTo.Append(' ');
                }
            }
            if (lastEntry != null)
            {
                toAddTo.Append('&');
                if (showWhiteSpace)
                {
                    toAddTo.Append(' ');
                }
                lastEntry.AppendQuotedChars(toAddTo);
                AppendQuotedExtension(toAddTo);
                if (showWhiteSpace)
                {
                    toAddTo.Append(' ');
                }
            }
            switch (Strength_Renamed)
            {
            case Collator.IDENTICAL:
                toAddTo.Append('=');
                break;

            case Collator.TERTIARY:
                toAddTo.Append(',');
                break;

            case Collator.SECONDARY:
                toAddTo.Append(';');
                break;

            case Collator.PRIMARY:
                toAddTo.Append('<');
                break;

            case RESET:
                toAddTo.Append('&');
                break;

            case UNSET:
                toAddTo.Append('?');
                break;
            }
            if (showWhiteSpace)
            {
                toAddTo.Append(' ');
            }
            AppendQuoted(Chars_Renamed, toAddTo);
            if (showExtension && Extension_Renamed.Length() != 0)
            {
                toAddTo.Append('/');
                AppendQuoted(Extension_Renamed, toAddTo);
            }
        }
Пример #31
0
        /**
          * Method fill string
          *
          * @param The string to be format.
          *
          */
        public static string fillstring(string formatString, int length, char fillChar, bool leftFillFlag)
        {
            if (null == formatString) {
                formatString = "";
            }
            int strLen = formatString.Length;
            if (strLen >= length) {
                if (true == leftFillFlag)  // left fill
                    return formatString.Substring (strLen - length, strLen);
                else
                    return formatString.Substring (0, length);
            } else {
                StringBuffer sbuf = new StringBuffer ();
                int fillLen = length - formatString.Length;
                for (int i = 0; i < fillLen; i++) {
                    sbuf.Append (fillChar);
                }

                if (true == leftFillFlag) {  // left fill
                    sbuf.Append (formatString);
                } else {
                    sbuf.Insert (0, formatString);
                }
                string returnstring = sbuf.ToString ();
                sbuf = null;
                return returnstring;
            }
        }
Пример #32
0
        private void AppendArgumentToStringBufferUnformatted(StringBuffer stringBuffer, ref byte *dataPointer)
        {
            var argument = *dataPointer;

            dataPointer += sizeof(ArgumentType);

            var argumentType = (ArgumentType)(argument & ArgumentTypeMask.ArgumentType);

            var hasFormatSpecifier = (argument & ArgumentTypeMask.FormatSpecifier) != 0;

            if (hasFormatSpecifier)
            {
                dataPointer += sizeof(byte); // Skip it
            }
            switch (argumentType)
            {
            case ArgumentType.String:
                stringBuffer.Append('"');
                stringBuffer.Append(_strings[*dataPointer]);
                stringBuffer.Append('"');
                dataPointer += sizeof(byte);
                break;

            case ArgumentType.AsciiString:
                var length = *(int *)dataPointer;
                dataPointer += sizeof(int);
                stringBuffer.Append('"');
                stringBuffer.Append(new AsciiString(dataPointer, length));
                stringBuffer.Append('"');
                dataPointer += length;
                break;

            case ArgumentType.Boolean:
                stringBuffer.Append(*(bool *)dataPointer);
                dataPointer += sizeof(bool);
                break;

            case ArgumentType.Byte:
                stringBuffer.Append(*dataPointer, StringView.Empty);
                dataPointer += sizeof(byte);
                break;

            case ArgumentType.Char:
                stringBuffer.Append('\'');
                stringBuffer.Append(*(char *)dataPointer);
                stringBuffer.Append('\'');
                dataPointer += sizeof(char);
                break;

            case ArgumentType.Int16:
                stringBuffer.Append(*(short *)dataPointer, StringView.Empty);
                dataPointer += sizeof(short);
                break;

            case ArgumentType.Int32:
                stringBuffer.Append(*(int *)dataPointer, StringView.Empty);
                dataPointer += sizeof(int);
                break;

            case ArgumentType.Int64:
                stringBuffer.Append(*(long *)dataPointer, StringView.Empty);
                dataPointer += sizeof(long);
                break;

            case ArgumentType.Single:
                stringBuffer.Append(*(float *)dataPointer, StringView.Empty);
                dataPointer += sizeof(float);
                break;

            case ArgumentType.Double:
                stringBuffer.Append(*(double *)dataPointer, StringView.Empty);
                dataPointer += sizeof(double);
                break;

            case ArgumentType.Decimal:
                stringBuffer.Append(*(decimal *)dataPointer, StringView.Empty);
                dataPointer += sizeof(decimal);
                break;

            case ArgumentType.Guid:
                stringBuffer.Append(*(Guid *)dataPointer, StringView.Empty);
                dataPointer += sizeof(Guid);
                break;

            case ArgumentType.DateTime:
                stringBuffer.Append(*(DateTime *)dataPointer, StringView.Empty);
                dataPointer += sizeof(DateTime);
                break;

            case ArgumentType.TimeSpan:
                stringBuffer.Append(*(TimeSpan *)dataPointer, StringView.Empty);
                dataPointer += sizeof(TimeSpan);
                break;

            case ArgumentType.FormatString:
                var formatStringIndex = *dataPointer;
                dataPointer += sizeof(byte) + sizeof(byte);
                stringBuffer.Append('"');
                stringBuffer.Append(_strings[formatStringIndex]);
                stringBuffer.Append('"');
                break;

            case ArgumentType.Enum:
                var enumArg = (EnumArg *)dataPointer;
                dataPointer += sizeof(EnumArg);
                enumArg->AppendTo(stringBuffer);
                break;

            case ArgumentType.Null:
                stringBuffer.Append(LogManager.Config.NullDisplayString);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #33
0
        /*
           * Converts unicodes to encoded &#92;uxxxx and writes out any of the
           * characters in specialSaveChars with a preceding slash
           *
           * @param theString
           *            the string needing convert.
           * @param dst
           *            Save of the result
           * @param offset
           *            the offset of result
           * @param escapeSpace
           *            if <code>true</code>, escape Space
           * @param lengthFlag
           *            Whether add one byte of length in the result.
           *            <code>true</code> add one byte of length in the result
           * @param getLengthFlag
           *            Calculate the length of result, if <code>true</code>, thestring length that return.
           * @return  if getLengthFlag = false, return offset of the result.
           *          if getLengthFlag = true, the length of the sequence of characters represented by this
           *          object.
           */
        public static int saveConvert(string theString, byte[] dst, int offset, bool escapeSpace, bool lengthFlag, bool getLengthFlag)
        {
            if (false == getLengthFlag
                && (null == dst || dst.Length < (offset + (lengthFlag ? 1 : 0))
                || dst.Length < 1 || offset < 0))
                return -1;
            if (null == theString)
                theString = "";
            int length = theString.Length;

            StringBuffer outBuffer = new StringBuffer (length * 2);

            for (int x = 0; x < length; x++) {
                char aChar = theString [x];
                switch (aChar) {
                case ' ':
                    if (x == 0 || escapeSpace)
                        outBuffer.Append ('\\');

                    outBuffer.Append (' ');
                    break;
                case '\\':
                    outBuffer.Append ('\\');
                    break;
                case '\t':
                    outBuffer.Append ('\\');
                    outBuffer.Append ('t');
                    break;
                case '\n':
                    outBuffer.Append ('\\');
                    outBuffer.Append ('n');
                    break;
                case '\r':
                    outBuffer.Append ('\\');
                    outBuffer.Append ('r');
                    break;
                case '\f':
                    outBuffer.Append ('\\');
                    outBuffer.Append ('f');
                    break;
                default:
                    if ((aChar < 0x0020) || (aChar > 0x007e)) {
                        outBuffer.Append ('\\');
                        outBuffer.Append ('u');
                        outBuffer.Append (toHexChar ((aChar >> 12) & 0xF));
                        outBuffer.Append (toHexChar ((aChar >> 8) & 0xF));
                        outBuffer.Append (toHexChar ((aChar >> 4) & 0xF));
                        outBuffer.Append (toHexChar (aChar & 0xF));
                    } else {
                        if (specialSaveChars.IndexOf (aChar) != -1)
                            outBuffer.Append ('\\');
                        outBuffer.Append (aChar);
                    }
                    break;
                }
            }
            length = outBuffer.Length ();
            if (length > 255)
                length = 255;
            if (!getLengthFlag) {
                if (dst.Length >= offset + length + (lengthFlag ? 1 : 0)) {
                    if (lengthFlag) {
                        dst [offset] = (byte)(length & 0xFF);
                        offset++;
                    }
                    for (int i = 0; i < length; i++) {
                        dst [offset] = (byte)outBuffer.CharAt (i);
                        offset++;
                    }
                    length = offset;
                } else {
                    length = -1;
                }
            } else {
                if (lengthFlag)
                    length = length + 1;
            }

            outBuffer = null;

            return length;
        }
Пример #34
0
        public static void DrawConsole(Single frac)
        {
            var width  = viddef.GetWidth();
            var height = viddef.GetHeight();
            var lines  = ( Int32 )(height * frac);

            if (lines <= 0)
            {
                return;
            }
            if (lines > height)
            {
                lines = height;
            }
            re.DrawStretchPic(0, -height + lines, width, height, "conback");
            SCR.AddDirtyPoint(0, 0);
            SCR.AddDirtyPoint(width - 1, lines - 1);
            var version = Com.Sprintf("v%4.2f", 1, VERSION);
            var x       = 0;

            for (x = 0; x < 5; x++)
            {
                re.DrawChar(width - 44 + x * 8, lines - 12, 128 + version[x]);
            }
            con.vislines = lines;
            var rows = (lines - 22) >> 3;
            var y    = lines - 30;

            if (con.display != con.current)
            {
                for (x = 0; x < con.linewidth; x += 4)
                {
                    re.DrawChar((x + 1) << 3, y, '^');
                }
                y -= 8;
                rows--;
            }

            Int32 i, j, n;

            x = 0;
            var row = con.display;

            for (i = 0; i < rows; i++, y -= 8, row--)
            {
                if (row < 0)
                {
                    break;
                }
                if (con.current - row >= con.totallines)
                {
                    break;
                }
                var first = (row % con.totallines) * con.linewidth;
                for (x = 0; x < con.linewidth; x++)
                {
                    re.DrawChar((x + 1) << 3, y, con.text[x + first]);
                }
            }

            if (cls.download != null)
            {
                Int32 text;
                if ((text = cls.downloadname.LastIndexOf('/')) != 0)
                {
                    text++;
                }
                else
                {
                    text = 0;
                }
                x = con.linewidth - ((con.linewidth * 7) / 40);
                y = x - (cls.downloadname.Length - text) - 8;
                i = con.linewidth / 3;
                StringBuffer dlbar = new StringBuffer(512);
                if (cls.downloadname.Length - text > i)
                {
                    y = x - i - 11;
                    var end = text + i - 1;
                    dlbar.Append(cls.downloadname.Substring(text, end));
                    dlbar.Append("...");
                }
                else
                {
                    dlbar.Append(cls.downloadname.Substring(text));
                }

                dlbar.Append(": ");
                dlbar.Append(( Char )0x80);
                if (cls.downloadpercent == 0)
                {
                    n = 0;
                }
                else
                {
                    n = y * cls.downloadpercent / 100;
                }
                for (j = 0; j < y; j++)
                {
                    if (j == n)
                    {
                        dlbar.Append(( Char )0x83);
                    }
                    else
                    {
                        dlbar.Append(( Char )0x81);
                    }
                }

                dlbar.Append(( Char )0x82);
                dlbar.Append((cls.downloadpercent < 10) ? " 0" : " ");
                dlbar.Append(cls.downloadpercent).Append('%');
                y = con.vislines - 12;
                for (i = 0; i < dlbar.Length; i++)
                {
                    re.DrawChar((i + 1) << 3, y, dlbar[i]);
                }
            }

            DrawInput();
        }
Пример #35
0
        /**
          * Method trim space
          *
          * @param The string to be format.
          *
          */
        public static string trimSpace(string oldString)
        {
            if (null == oldString)
                return null;
            if (0 == oldString.Length)
                return "";

            StringBuffer sbuf = new StringBuffer ();
            int oldLen = oldString.Length;
            for (int i = 0; i < oldLen; i++) {
                if (' ' != oldString [i])
                    sbuf.Append (oldString [i]);
            }
            string returnString = sbuf.ToString ();
            sbuf = null;
            return returnString;
        }
Пример #36
0
        private void ParseValue(string name, bool isAttribute)
        {
            _valStart = _idx;
            _valEnd   = -1;
            for (; _idx < _length; _idx++)
            {
                var c = _s[_idx];
                switch (c)
                {
                case ',':
                case ']':
                case '}':
                {
                    if (_valEnd >= 0)
                    {
                        _b.Append(_s, _valStart, (_valEnd - _valStart) + 1);
                    }

                    var item = isAttribute ? new StageAttribute(name, _b.Flush(), false) : new StageValue(name, _b.Flush(), false);
                    _curRoot.Add(item);
                    _idx--;
                    return;
                }

                case ' ':
                case '\t':
                case '\n':
                case '\r':
                case '\f':
                {
                    /* Skip white space */
                    if (_valEnd == -1)
                    {
                        _valStart++;
                    }

                    break;
                }

                default:
                {
                    _valEnd = _idx;
                    break;
                }
                }
            }
        }
Пример #37
0
        /**
         * Seperate String with str token
         *
         * @param str - the string which will be cut
         * @return cut string array
         */
        // @SuppressWarnings("unused")
        private static string[] seperateStr(string str)
        {
            bool doubleSpace = false;
            int wordCount = 0;
            StringBuffer sb = new StringBuffer();
            if (str == null || str.Length == 0)
            {
                return null;
            }
            for (int j = 0; j < str.Length; j++)
            {
                if (str[j] == ' ')
                {
                    if (!doubleSpace)
                        wordCount++;

                    doubleSpace = true;
                    continue;
                }
                doubleSpace = false;
            }
            string[] st = new string[wordCount + 1];

            int i = 0;

            doubleSpace = false;
            string ch = "";
            for (int j = 0; j < str.Length; j++)
            {
                if (str[j] == ' ')
                {
                    if (!doubleSpace)
                    {
                        st[i] = sb.ToString();
                        sb.Delete(0, sb.Length());
                        i++;
                    }
                    doubleSpace = true;
                    continue;
                } else
                {
                    sb.Append(str[j]);
                }
                doubleSpace = false;
            }

            st[i] = sb.ToString();
            ;
            return st;
        }
Пример #38
0
        private static unsafe Process StartProcessFromElf(ElfSections elf, string path, uint argumentBufferSize = 0)
        {
            var proc = CreateEmptyProcess(new ProcessCreateOptions()
            {
                User = true
            });

            KernelMessage.WriteLine("Create proc: {0}, PID: {1}", path, proc.ProcessID);
            proc.Path      = path;
            proc.PageTable = PageTable.CreateInstance();

            var allocator = new UserInitialPageAllocator()
            {
                DebugName = "UserInitial"
            };

            allocator.Setup(new MemoryRegion(500 * 1024 * 1024, 60 * 1024 * 1014), AddressSpaceKind.Virtual);
            proc.UserPageAllocator = allocator;

            // Setup User PageTable
            proc.PageTableAllocAddr = VirtualPageManager.AllocatePages(
                KMath.DivCeil(proc.PageTable.InitalMemoryAllocationSize, 4096),
                new AllocatePageOptions {
                Pool = PageAllocationPool.Identity
            });
            PageTable.KernelTable.SetWritable(proc.PageTableAllocAddr, proc.PageTable.InitalMemoryAllocationSize);
            proc.PageTable.UserProcSetup(proc.PageTableAllocAddr);
            proc.PageTable.Map(proc.PageTableAllocAddr, proc.PageTableAllocAddr, proc.PageTable.InitalMemoryAllocationSize);

            proc.PageTable.MapCopy(PageTable.KernelTable, BootInfoMemoryType.KernelTextSegment);
            proc.PageTable.SetExecutable(BootInfoMemoryType.KernelTextSegment);
            proc.PageTable.MapCopy(PageTable.KernelTable, Address.InterruptControlBlock, 4096);
            proc.PageTable.MapCopy(PageTable.KernelTable, KernelMemoryMapManager.Header->Used.GetMap(BootInfoMemoryType.GDT));
            proc.PageTable.MapCopy(PageTable.KernelTable, KernelMemoryMapManager.Header->Used.GetMap(BootInfoMemoryType.IDT));
            proc.PageTable.MapCopy(PageTable.KernelTable, KernelMemoryMapManager.Header->Used.GetMap(BootInfoMemoryType.TSS));

            var tmpKernelElfHeaders = SetupElfHeader(proc, elf);

            // Setup ELF Sections
            for (uint i = 0; i < elf.SectionHeaderCount; i++)
            {
                var section = elf.GetSectionHeader(i);
                var name    = elf.GeSectionName(section);

                var size     = section->Size;
                var virtAddr = section->Addr;
                var srcAddr  = elf.GetSectionPhysAddr(section);

                if (size == 0)
                {
                    continue;
                }

                if (virtAddr == Addr.Zero)
                {
                    var mem = allocator.AllocatePagesAddr(KMath.DivCeil(size, 4096));
                    tmpKernelElfHeaders[i].Addr = mem;
                    virtAddr = mem;
                }

                var sb = new StringBuffer();
                sb.Append("Map section ");
                sb.Append(name);
                sb.Append(" virt={0:X8} src={1:X8} size={2:X8}", virtAddr, srcAddr, size);
                KernelMessage.WriteLine(sb);
                //MemoryOperation.Copy4(elf.GetSectionPhysAddr(section), section->Addr, section->Size);

                // Map the Sections
                proc.PageTable.MapCopy(PageTable.KernelTable, srcAddr, virtAddr, size);
                if (name->Equals(".text"))
                {
                    proc.PageTable.SetExecutable(virtAddr, size);
                }
            }
            KernelMessage.WriteLine("proc sections are ready");

            // Detect Thread-Main
            var entryPoint = GetEntryPointFromElf(elf);

            KernelMessage.WriteLine("EntryPoint: {0:X8}", entryPoint);

            var mainThread = Scheduler.CreateThread(proc, new ThreadStartOptions(entryPoint)
            {
                ArgumentBufferSize  = argumentBufferSize,
                AllowUserModeIOPort = true,
                DebugName           = "UserProcMainThread",
            });

            KernelMessage.WriteLine("Starting {0} on Thread {1}", path, mainThread.ThreadID);
            proc.Start();

            return(proc);
        }
Пример #39
0
        private static string TryExpandShortFileName(ref StringBuffer outputBuffer, string originalPath)
        {
            // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To
            // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls.

            Debug.Assert(!PathInternal.IsPartiallyQualified(ref outputBuffer), "should have resolved by now");

            // We'll have one of a few cases by now (the normalized path will have already:
            //
            //  1. Dos path (C:\)
            //  2. Dos UNC (\\Server\Share)
            //  3. Dos device path (\\.\C:\, \\?\C:\)
            //
            // We want to put the extended syntax on the front if it doesn't already have it, which may mean switching from \\.\.
            //
            // Note that we will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is).

            int  rootLength = PathInternal.GetRootLength(ref outputBuffer);
            bool isDevice   = PathInternal.IsDevice(ref outputBuffer);

            StringBuffer inputBuffer = new StringBuffer(0);

            try
            {
                bool isDosUnc       = false;
                int  rootDifference = 0;
                bool wasDotDevice   = false;

                // Add the extended prefix before expanding to allow growth over MAX_PATH
                if (isDevice)
                {
                    // We have one of the following (\\?\ or \\.\)
                    inputBuffer.Append(ref outputBuffer);

                    if (outputBuffer[2] == '.')
                    {
                        wasDotDevice   = true;
                        inputBuffer[2] = '?';
                    }
                }
                else
                {
                    isDosUnc       = IsDosUnc(ref outputBuffer);
                    rootDifference = GetInputBuffer(ref outputBuffer, isDosUnc, ref inputBuffer);
                }

                rootLength += rootDifference;
                int inputLength = inputBuffer.Length;

                bool success    = false;
                int  foundIndex = inputBuffer.Length - 1;

                while (!success)
                {
                    uint result = Interop.mincore.GetLongPathNameW(inputBuffer.UnderlyingArray, outputBuffer.UnderlyingArray, (uint)outputBuffer.Capacity);

                    // Replace any temporary null we added
                    if (inputBuffer[foundIndex] == '\0')
                    {
                        inputBuffer[foundIndex] = '\\';
                    }

                    if (result == 0)
                    {
                        // Look to see if we couldn't find the file
                        int error = Marshal.GetLastWin32Error();
                        if (error != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND && error != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)
                        {
                            // Some other failure, give up
                            break;
                        }

                        // We couldn't find the path at the given index, start looking further back in the string.
                        foundIndex--;

                        for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--)
                        {
                            ;
                        }
                        if (foundIndex == rootLength)
                        {
                            // Can't trim the path back any further
                            break;
                        }
                        else
                        {
                            // Temporarily set a null in the string to get Windows to look further up the path
                            inputBuffer[foundIndex] = '\0';
                        }
                    }
                    else if (result > outputBuffer.Capacity)
                    {
                        // Not enough space. The result count for this API does not include the null terminator.
                        outputBuffer.EnsureCapacity(checked ((int)result));
                        result = Interop.mincore.GetLongPathNameW(inputBuffer.UnderlyingArray, outputBuffer.UnderlyingArray, (uint)outputBuffer.Capacity);
                    }
                    else
                    {
                        // Found the path
                        success             = true;
                        outputBuffer.Length = checked ((int)result);
                        if (foundIndex < inputLength - 1)
                        {
                            // It was a partial find, put the non-existent part of the path back
                            outputBuffer.Append(ref inputBuffer, foundIndex, inputBuffer.Length - foundIndex);
                        }
                    }
                }

                // Strip out the prefix and return the string
                ref StringBuffer bufferToUse = ref Choose(success, ref outputBuffer, ref inputBuffer);

                // Switch back from \\?\ to \\.\ if necessary
                if (wasDotDevice)
                {
                    bufferToUse[2] = '.';
                }

                string returnValue = null;

                int newLength = (int)(bufferToUse.Length - rootDifference);
                if (isDosUnc)
                {
                    // Need to go from \\?\UNC\ to \\?\UN\\
                    bufferToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\';
                }

                // We now need to strip out any added characters at the front of the string
                if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength))
                {
                    // Use the original path to avoid allocating
                    returnValue = originalPath;
                }
                else
                {
                    returnValue = bufferToUse.Substring(rootDifference, newLength);
                }

                return(returnValue);
            }
Пример #40
0
        void UpdateBlockInfoString(BlockID block)
        {
            if (selIndex < 27 && blocksTable[selIndex] != Block.Bedrock)
            {
                int index = 0;
                buffer.Clear();
                buffer.Append(ref index, "&f");
                string value = game.BlockInfo.Name[block];
                if (blocksTable[selIndex] != Block.Air)
                {
                    buffer.Append(ref index, value);
                }
                else
                {
                    if (!Mode.survivalinventory.iscrafting && !Mode.survivalinventory.ischest)
                    {
                        buffer.Append(ref index, "Inventory");
                    }
                    else if (Mode.survivalinventory.iscrafting && !Mode.survivalinventory.ischest)
                    {
                        buffer.Append(ref index, "Crafting");
                    }
                    else if (!Mode.survivalinventory.iscrafting && Mode.survivalinventory.ischest)
                    {
                        buffer.Append(ref index, "Chest");
                    }
                }


                if (blocksTable[selIndex] != Block.Air)
                {
                    if (!Mode.survivalinventory.iscrafting && !Mode.survivalinventory.ischest)
                    {
                        buffer.Append(ref index, " (Quantity: ");
                        buffer.Append(ref index, Mode.survivalinventory.inv2Count[selIndex + 1] + ")");

                        buffer.Append(ref index, " (Durability: ");
                        buffer.Append(ref index, Mode.survivalinventory.inv2durability[selIndex + 1] + ")");
                    }
                    else if (!Mode.survivalinventory.iscrafting && Mode.survivalinventory.ischest)
                    {
                        buffer.Append(ref index, " (Quantity: ");
                        buffer.Append(ref index, Mode.survivalinventory.chestCount[selIndex + 1] + ")");

                        buffer.Append(ref index, " (Durability: ");
                        buffer.Append(ref index, Mode.survivalinventory.chestdurability[selIndex + 1] + ")");
                    }
                    else if (Mode.survivalinventory.iscrafting && !Mode.survivalinventory.ischest)
                    {
                        int craftgrid3;
                        int craftgrid4;
                        int craftgrid5;
                        int craftgrid6;
                        int craftgrid7;
                        int craftgrid8;
                        int ix;
                        if (game.UseCPE)
                        {
                            ix         = Mode.survivalinventory.blocknb - Mode.survivalinventory.lessblocknbclassic;
                            craftgrid3 = 9;
                            craftgrid4 = 10;
                            craftgrid5 = 11;
                            craftgrid6 = 18;
                            craftgrid7 = 19;
                            craftgrid8 = 20;
                        }
                        else
                        {
                            ix         = Mode.survivalinventory.blocknb - Mode.survivalinventory.lessblocknbclassic;
                            craftgrid3 = 9;
                            craftgrid4 = 10;
                            craftgrid5 = 11;
                            craftgrid6 = 18;
                            craftgrid7 = 19;
                            craftgrid8 = 20;
                        }



                        if (selIndex == 0)
                        {
                            selIndex2 = ix + 1;
                        }
                        if (selIndex == 1)
                        {
                            selIndex2 = ix + 2;
                        }
                        if (selIndex == 2)
                        {
                            selIndex2 = ix + 3;
                        }
                        if (selIndex == craftgrid3)
                        {
                            selIndex2 = ix + 4;
                        }
                        if (selIndex == craftgrid4)
                        {
                            selIndex2 = ix + 5;
                        }
                        if (selIndex == craftgrid5)
                        {
                            selIndex2 = ix + 6;
                        }
                        if (selIndex == craftgrid6)
                        {
                            selIndex2 = ix + 7;
                        }
                        if (selIndex == craftgrid7)
                        {
                            selIndex2 = ix + 8;
                        }
                        if (selIndex == craftgrid8)
                        {
                            selIndex2 = ix + 9;
                        }
                        if (selIndex == craftgrid5 + 2)
                        {
                            selIndex2 = ix + 10;
                        }

                        buffer.Append(ref index, " (Quantity: ");
                        buffer.Append(ref index, Mode.survivalinventory.inv2Count[selIndex2] + ")");

                        buffer.Append(ref index, " (Durability: ");
                        buffer.Append(ref index, Mode.survivalinventory.inv2durability[selIndex2] + ")");
                    }
                }
            }
        }
Пример #41
0
        private static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath)
        {
            // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To
            // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls.

            Debug.Assert(!PathInternal.IsRelative(outputBuffer), "should have resolved by now");
            Debug.Assert(!PathInternal.IsExtended(outputBuffer), "expanding short names expects normal paths");

            // Add the extended prefix before expanding to allow growth over MAX_PATH
            StringBuffer inputBuffer = null;
            ulong        rootLength  = PathInternal.GetRootLength(outputBuffer);
            bool         isUnc       = IsUnc(outputBuffer);

            ulong rootDifference = GetInputBuffer(outputBuffer, isUnc, out inputBuffer);

            rootLength += rootDifference;
            ulong inputLength = inputBuffer.Length;

            bool  success    = false;
            ulong foundIndex = inputBuffer.Length - 1;

            while (!success)
            {
                uint result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), (uint)outputBuffer.CharCapacity);

                // Replace any temporary null we added
                if (inputBuffer[foundIndex] == '\0')
                {
                    inputBuffer[foundIndex] = '\\';
                }

                if (result == 0)
                {
                    // Look to see if we couldn't find the file
                    int error = Marshal.GetLastWin32Error();
                    if (error != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND && error != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)
                    {
                        // Some other failure, give up
                        break;
                    }

                    // We couldn't find the path at the given index, start looking further back in the string.
                    foundIndex--;

                    for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--)
                    {
                        ;
                    }
                    if (foundIndex == rootLength)
                    {
                        // Can't trim the path back any further
                        break;
                    }
                    else
                    {
                        // Temporarily set a null in the string to get Windows to look further up the path
                        inputBuffer[foundIndex] = '\0';
                    }
                }
                else if (result > outputBuffer.CharCapacity)
                {
                    // Not enough space. The result count for this API does not include the null terminator.
                    outputBuffer.EnsureCharCapacity(result);
                    result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), (uint)outputBuffer.CharCapacity);
                }
                else
                {
                    // Found the path
                    success             = true;
                    outputBuffer.Length = result;
                    if (foundIndex < inputLength - 1)
                    {
                        // It was a partial find, put the non-existant part of the path back
                        outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex);
                    }
                }
            }

            // Strip out the prefix and return the string
            StringBuffer bufferToUse = success ? outputBuffer : inputBuffer;
            string       returnValue = null;

            int newLength = (int)(bufferToUse.Length - rootDifference);

            if (isUnc)
            {
                // Need to go from \\?\UNC\ to \\?\UN\\
                bufferToUse[(ulong)PathInternal.UncExtendedPathPrefix.Length - 1] = '\\';
            }

            if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength))
            {
                // Use the original path to avoid allocating
                returnValue = originalPath;
            }
            else
            {
                returnValue = bufferToUse.Substring(rootDifference, newLength);
            }

            inputBuffer.Dispose();
            return(returnValue);
        }
Пример #42
0
 public void Format(StringBuffer buffer, StringView format)
 {
     buffer.Append("boom");
     throw new InvalidOperationException("Simulated failure");
 }
Пример #43
0
        void TabKey()
        {
            int pos   = caretPos == -1 ? buffer.Length - 1 : caretPos;
            int start = pos;

            char[] value = buffer.value;

            while (start >= 0 && IsNameChar(value[start]))
            {
                start--;
            }
            start++;
            if (pos < 0 || start > pos)
            {
                return;
            }

            string        part    = new String(value, start, pos + 1 - start);
            List <string> matches = new List <string>();

            game.Chat.Add(null, MessageType.ClientStatus5);

            TabListEntry[] entries = game.TabList.Entries;
            for (int i = 0; i < EntityList.MaxCount; i++)
            {
                if (entries[i] == null)
                {
                    continue;
                }

                string rawName = entries[i].PlayerName;
                string name    = Utils.StripColours(rawName);
                if (name.StartsWith(part, StringComparison.OrdinalIgnoreCase))
                {
                    matches.Add(name);
                }
            }

            if (matches.Count == 1)
            {
                if (caretPos == -1)
                {
                    pos++;
                }
                int len = pos - start;
                for (int i = 0; i < len; i++)
                {
                    buffer.DeleteAt(start);
                }
                if (caretPos != -1)
                {
                    caretPos -= len;
                }
                AppendText(matches[0]);
            }
            else if (matches.Count > 1)
            {
                StringBuffer sb    = new StringBuffer(64);
                int          index = 0;
                sb.Append(ref index, "&e");
                sb.AppendNum(ref index, matches.Count);
                sb.Append(ref index, " matching names: ");

                foreach (string match in matches)
                {
                    if ((match.Length + 1 + sb.Length) > LineLength)
                    {
                        break;
                    }
                    sb.Append(ref index, match);
                    sb.Append(ref index, ' ');
                }
                game.Chat.Add(sb.ToString(), MessageType.ClientStatus5);
            }
        }
Пример #44
0
 public static string hexString(byte[] b)
 {
     StringBuffer d = new StringBuffer(b.Length * 2);
     for (int i = 0; i < b.Length; i++) {
         char hi = Character.ForDigit((b[i] >> 4) & 0x0F, 16);
         char lo = Character.ForDigit(b[i] & 0x0F, 16);
         d.Append(Character.ToUpperCase(hi));
         d.Append(Character.ToUpperCase(lo));
     }
     return d.ToString();
 }
Пример #45
0
        void TabKey()
        {
            int pos   = caret == -1 ? Text.Length - 1 : caret;
            int start = pos;

            char[] value = Text.value;

            while (start >= 0 && IsNameChar(value[start]))
            {
                start--;
            }
            start++;
            if (pos < 0 || start > pos)
            {
                return;
            }

            string        part    = new String(value, start, pos + 1 - start);
            List <string> matches = new List <string>();

            game.Chat.Add(null, MessageType.ClientStatus3);

            TabListEntry[] entries = TabList.Entries;
            for (int i = 0; i < EntityList.MaxCount; i++)
            {
                if (entries[i] == null)
                {
                    continue;
                }
                string name = entries[i].PlayerName;
                if (Utils.CaselessStarts(name, part))
                {
                    matches.Add(name);
                }
            }

            if (matches.Count == 1)
            {
                if (caret == -1)
                {
                    pos++;
                }
                int len = pos - start;
                for (int i = 0; i < len; i++)
                {
                    Text.DeleteAt(start);
                }
                if (caret != -1)
                {
                    caret -= len;
                }
                Append(matches[0]);
            }
            else if (matches.Count > 1)
            {
                StringBuffer sb = new StringBuffer(Utils.StringLength);
                sb.Append("&e");
                sb.AppendNum(matches.Count);
                sb.Append(" matching names: ");

                for (int i = 0; i < matches.Count; i++)
                {
                    string match = matches[i];
                    if ((sb.Length + match.Length + 1) > sb.Capacity)
                    {
                        break;
                    }
                    sb.Append(match);
                    sb.Append(' ');
                }
                game.Chat.Add(sb.ToString(), MessageType.ClientStatus3);
            }
        }
Пример #46
0
    private string ToStringEx(ListDictionary sqlVarNames)
    {
      StringBuffer sb;
      int n;

      if (this is Cut)
        return "!";
      else if (!hasValue)
      {
        if (sqlVarNames == null)
        {
          if (this is NamedVar)
            return ((NamedVar)this).Name;
          else
            return ("_" + varNo);
        }
        else
        {
          string colName = (string)sqlVarNames[varNo];
          if (colName == null) PrologIO.Error("Unbound variable not allowed in where-part of persistent predicate call");
          return (colName);
        }
      }
      else if (isUnified)
        return LinkEnd.ToStringEx(sqlVarNames);
      else if (IsString)
      {
        if (sqlVarNames == null)
          return "\"" + functor + "\"";
        else // SQL
          return "'" + functor + "'";
      }
      else if (this == NULLLIST)
        return "[]";
      else if (IsList && arity == 2)
      {
        Term t;
        sb = new StringBuffer("[" + args[0].ToStringEx(sqlVarNames));
        t = args[1];
        while (t.Arity == 2 && t.IsList)
        {
          sb.Append("," + t.Arg(0).ToStringEx(sqlVarNames));
          t = t.Arg(1);
        }

        if (t.IsList)
          sb.Append("]");
        else
          sb.Append("|" + t.ToStringEx(sqlVarNames) + "]");
        return sb.ToString();
      }
      else if (functor == Parser.CURL)
      {
        if (arity == 0)
          return "{}";
        else
        {
          Term t;
          sb = new StringBuffer("{" + args[0].ToStringEx(sqlVarNames));
          t = args[1];
          while (t.Arity == 2)
          {
            sb.Append("," + t.Arg(0).ToStringEx(sqlVarNames));
            t = t.Arg(1);
          }
          sb.Append("}");
        }
      }
      else if (functor == NUMVAR && arity == 1 && Arg(0).IsInteger && (n = (int)Arg(0).ExprValue.AsNumber) >= 0)
      {
        int m = n / 26;
        n = n % 26;
        sb = new StringBuffer("ABCDEFGHIJKLMNOPQRSTUVWXYZ".Substring(n, 1) + ((m == 0) ? "" : m.ToString()));
      }
      else if (functor == Parser.COMMA && arity == 2)
        sb = new StringBuffer("(" + args[0].ToStringEx(sqlVarNames) + "," + args[1].ToStringEx(sqlVarNames) + ")");
      else
      {
        sb = new StringBuffer();

        if (arity == 0)
        {
          if (oDescr == null)
            sb.Append(functor);
          else // functors which are actually operators are parenthesized
            sb.Append("(" + functor + ")");
        }
        else
        {
          if (oType == OType.xfx || oType == OType.xfy || oType == OType.yfx)
          {
            if (precedence < args[0].Precedence ||
                 (precedence == args[0].Precedence && (oType == OType.xfx || oType == OType.yfx)))
              sb.AppendPackedTerm(args[0], sqlVarNames);
            else
              sb.AppendTerm(args[0], sqlVarNames);

            sb.Append(functor);

            if (precedence < args[1].Precedence ||
                 (precedence == args[1].Precedence && (oType == OType.xfx || oType == OType.yfx)))
              sb.AppendPackedTerm(args[1], sqlVarNames);
            else
              sb.AppendTerm(args[1], sqlVarNames);
          }
          else if (oType == OType.fx && arity <= 1)
          {
            sb.Append(functor);
            if (precedence <= args[0].Precedence)
              sb.AppendPackedTerm(args[0], sqlVarNames);
            else
              sb.AppendTerm(args[0], sqlVarNames);
          }
          else if (oType == OType.fy && arity <= 1)
          {
            sb.Append(functor);
            if (precedence < args[0].Precedence)
              sb.AppendPackedTerm(args[0], sqlVarNames);
            else
              sb.AppendTerm(args[0], sqlVarNames);
          }
          else if (oType == OType.xf)
          {
            if (precedence <= args[0].Precedence)
              sb.AppendPackedTerm(args[0], sqlVarNames);
            else
              sb.AppendTerm(args[0], sqlVarNames);
            sb.Append(functor);
          }
          else if (oType == OType.yf)
          {
            if (precedence < args[0].Precedence)
              sb.AppendPackedTerm(args[0], sqlVarNames);
            else
              sb.AppendTerm(args[0], sqlVarNames);
            sb.Append(functor);
          }
          else
          {
            sb.Append(functor);
            sb.Append("(");
            for (int i = 0; i < (arity - 1); i++)
              sb.Append(args[i].ToStringEx(sqlVarNames) + ",");
            sb.Append(args[arity - 1].ToStringEx(sqlVarNames));
            sb.Append(")");
          }
        }
      }
      return sb.ToString();
    }
Пример #47
0
 /// <summary>
 /// Read a file with given path and return a string with it's entire contents.
 /// </summary>
 public static string ReadAllText(string path)
 {
     if (path == null)
         throw new ArgumentNullException("path");
     var file = new JFile(path);
     if (!file.Exists() || !file.IsFile())
         throw new FileNotFoundException(path);
     if (!file.CanRead())
         throw new UnauthorizedAccessException(path);
     var reader = new FileReader(file);
     try
     {
         var array = new char[4096];
         var buffer = new StringBuffer();
         int len;
         while ((len = reader.Read(array, 0, array.Length)) > 0)
         {
             buffer.Append(array, 0, len);
         }
         return buffer.ToString();
     }
     finally
     {
         reader.Close();
     }
 }
Пример #48
0
 ///** 
 // * ���������Ϣ���ļ���
 // *
 // * @param ex
 // * @return  �����ļ�����,���ڽ��ļ����͵�������
 // */
 private string saveCrashInfo2File(Throwable ex)
 {
     StringBuffer sb = new StringBuffer();
     foreach (var info in infos)
     {
         string key = info.Key;
         string value = info.Value;
         sb.Append(key + "=" + value + "\n");
     }
     //for (Map.Entry<String, String> entry : infos.entrySet()) {
     //    String key = entry.getKey();
     //    String value = entry.getValue();
     //    sb.append(key + "=" + value + "\n");
     //}
     //Writer writer = new StringWriter();
     //PrintWriter printWriter = new PrintWriter(writer);
     //ex.printStackTrace(printWriter);
     //Throwable cause = ex.getCause();
     //while (cause != null) {
     //    cause.printStackTrace(printWriter);
     //    cause = cause.getCause();
     //}
     //printWriter.close();
     //String result = writer.toString();
     //sb.append(result);
     //try {
     //    long timestamp = System.currentTimeMillis();
     //    String time = formatter.format(new Date());
     //    String fileName = "crash-" + time + "-" + timestamp + ".log";
     //    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     //        String path = "/sdcard/crash/";
     //        File dir = new File(path);
     //        if (!dir.exists()) {
     //            dir.mkdirs();
     //        }
     //        FileOutputStream fos = new FileOutputStream(path + fileName);
     //        fos.write(sb.toString().getBytes());
     //        fos.close();
     //    }
     //    return fileName;
     //} catch (Exception e) {
     //    Log.e(TAG, "an error occured while writing file...", e);
     //}
     return null;
 }
Пример #49
0
        /**
         * convert byte array to Hex String.
         *
         * @param buf - the byte array which will be converted
         * @param offset - the start position of buf
         * @param length - the converted length
         * @return Hex String
         */
        public static string buf2StringWithoutSpace(byte[] buf, int offset,
			int length)
        {
            int i;
            StringBuffer sBuf = new StringBuffer();
            for (i = 0 + offset; i < length + offset; i++)
            {
                sBuf.Append(changeIntoHex(buf[i], false));
            }
            return sBuf.ToString();
        }
Пример #50
0
 public void AppendCharCountTests(string initialBuffer, char value, uint count, string expected)
 {
     using var buffer = new StringBuffer(initialBuffer);
     buffer.Append(value, count);
     buffer.ToString().Should().Be(expected);
 }
Пример #51
0
 /// <summary>
 /// Convert the numeric value of each array element to a hex string divided by '-'.
 /// </summary>
 public static string ToString(byte[] value, int index, int length)
 {
     if (value == null)
         throw new ArgumentNullException("value");
     if (index < 0)
         throw new ArgumentOutOfRangeException("index");
     if (length < 0)
         throw new ArgumentOutOfRangeException("length");
     if (index + length > value.Length)
         throw new ArgumentException("length");
     var buffer = new StringBuffer();
     for (var i = 0; i < length; i++)
     {
         if (i > 0)
             buffer.Append('-');
         var hex = int.ToHexString((int) value[index + i]);
         if (hex.Length == 1)
             buffer.Append('0');
         buffer.Append(hex);
     }
     return buffer.ToString();
 }
        /// <inheritdoc />
        public override void OnReceivedBytes(bool isNewConnection, ArraySegment <byte> receivedBytes)
        {
            receivedBytes.MustNotBeDefault(nameof(receivedBytes));

            // Clear receive buffer on new connections
            if (isNewConnection)
            {
                _receiveStringBuffer.Clear();
                _decoder.Reset();
            }

            // Parse characters
            if (receivedBytes.Count == 0)
            {
                return;
            }
            var addedChars = _receiveStringBuffer.Append(receivedBytes, _decoder);

            if (addedChars == 0)
            {
                return;
            }

            while (_receiveStringBuffer.Count > 0)
            {
                // Check for start symbol
                if (_receiveStringBuffer[0] != SYMBOL_START)
                {
                    throw new MessageRecognitionException($"Error during message recognition. Expected '{SYMBOL_START}' at the start of a message, got '{_receiveStringBuffer[0]}'!");
                }

                // Search delimiter
                var delimiterIndex = -1;
                for (var loop = 1; loop < _receiveStringBuffer.Count; loop++)
                {
                    if (_receiveStringBuffer[loop] == SYMBOL_DELIMITER)
                    {
                        delimiterIndex = loop;
                        break;
                    }

                    if (!TcpCommunicatorUtil.IsNumeric(_receiveStringBuffer[loop]))
                    {
                        throw new MessageRecognitionException($"Error during message recognition. Symbol in length field is not numeric (current index: {loop})!");
                    }
                    if (loop > 11)
                    {
                        throw new MessageRecognitionException($"Error during message recognition. Length field too long (current index: {loop})!");
                    }
                }
                if (delimiterIndex == -1)
                {
                    break;
                }

                // Parse message count
                int rawMessageLength;
                try
                {
                    rawMessageLength = TcpCommunicatorUtil.ParseInt32FromStringPart(
                        _receiveStringBuffer,
                        1, delimiterIndex - 1);
                }
                catch (Exception ex)
                {
                    throw new MessageRecognitionException($"Unable to parse message length: {ex.Message}");
                }

                // Look whether we've received the full message
                var fullMessageLength = delimiterIndex + rawMessageLength + 2;
                if (_receiveStringBuffer.Count < fullMessageLength)
                {
                    break;
                }

                // Check endsymbol
                if (_receiveStringBuffer[fullMessageLength - 1] != SYMBOL_END)
                {
                    throw new MessageRecognitionException($"Error during message recognition. Expected '{SYMBOL_END}' at the end of a message, got '{_receiveStringBuffer[fullMessageLength - 1]}'!");
                }

                // Raise found message
                base.NotifyRecognizedMessage(_receiveStringBuffer.GetPartReadOnly(
                                                 delimiterIndex + 1, rawMessageLength));

                // Remove the message with endsymbols from receive buffer
                _receiveStringBuffer.RemoveFromStart(fullMessageLength);
            }
        }
Пример #53
0
        private void ReadStringIntoBuffer()
        {
            int          charPos           = _charPos;
            int          initialPosition   = _charPos;
            int          lastWritePosition = _charPos;
            StringBuffer buffer            = null;

            while (true)
            {
                var charAt = _chars[charPos++];
                if ('\0' == charAt)
                {
                    if (_charsUsed == charPos - 1)
                    {
                        charPos--;

                        if (ReadData(true) == 0)
                        {
                            _charPos = charPos;
                            throw EdiReaderException.Create(this, "Unterminated string. Expected delimiter.");
                        }
                    }
                }
                // Make use of the release character. Identify escape sequence
                else if (Grammar.ReleaseCharacter == charAt)
                {
                    _charPos = charPos;
                    if (!EnsureChars(0, true))
                    {
                        _charPos = charPos;
                        throw EdiReaderException.Create(this, "Unterminated string. Expected delimiter.");
                    }

                    // start of escape sequence
                    int escapeStartPos = charPos - 1;

                    char currentChar = _chars[charPos];

                    char writeChar;

                    if (Grammar.IsSpecial(currentChar) || Grammar.ReleaseCharacter == currentChar)
                    {
                        charPos++;
                        writeChar = currentChar;
                    }
                    else
                    {
                        charPos++;
                        _charPos = charPos;
                        throw EdiReaderException.Create(this, "Bad EDI escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, Grammar.ReleaseCharacter + currentChar));
                    }

                    if (buffer == null)
                    {
                        buffer = GetBuffer();
                    }

                    WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos);

                    lastWritePosition = charPos;
                }
                else if (StringUtils.CarriageReturn == charAt)
                {
                    _charPos = charPos - 1;
                    ProcessCarriageReturn(true);
                    charPos = _charPos;
                }
                else if (StringUtils.LineFeed == charAt)
                {
                    _charPos = charPos - 1;
                    ProcessLineFeed();
                    charPos = _charPos;
                }
                else if (Grammar.IsSpecial(_chars[charPos - 1]))
                {
                    charPos--;
                    if (initialPosition == lastWritePosition)
                    {
                        _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition);
                    }
                    else
                    {
                        if (buffer == null)
                        {
                            buffer = GetBuffer();
                        }

                        if (charPos > lastWritePosition)
                        {
                            buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition);
                        }

                        _stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position);
                    }
                    _charPos = charPos;
                    return;
                }
            }
        }
Пример #54
0
        public override StringBuffer Format(Date date, StringBuffer toAppendTo, FieldPosition pos)
        {
            toAppendTo = base.Format(date, toAppendTo, pos);

            Calendar otherCalendar = Calendar;
            Calendar todayCalendar = Calendar.Instance;

            int hour = otherCalendar.Get(CalendarField.HourOfDay);

            string[] times      = toAppendTo.ToString().Split(' ');
            string   moment     = hour == 12 ? moments[0] : moments[hour / 6 + 1];
            string   timeFormat = moment + " " + times[2];
            string   dateFormat = times[1] + " " + timeFormat;
            string   yearFormat = times[0] + dateFormat;

            toAppendTo.Delete(0, toAppendTo.Length());

            bool yearTemp = todayCalendar.Get(CalendarField.Year) == otherCalendar.Get(CalendarField.Year);

            if (yearTemp)
            {
                int todayMonth = todayCalendar.Get(CalendarField.Month);
                int otherMonth = otherCalendar.Get(CalendarField.Month);
                if (todayMonth == otherMonth)
                {//表示是同一个月
                    int temp = todayCalendar.Get(CalendarField.Date) - otherCalendar.Get(CalendarField.Date);
                    switch (temp)
                    {
                    case 0:
                        toAppendTo.Append(timeFormat);
                        break;

                    case 1:
                        toAppendTo.Append("昨天 ");
                        toAppendTo.Append(timeFormat);
                        break;

                    case 2:
                        toAppendTo.Append("前天 ");
                        toAppendTo.Append(timeFormat);
                        break;

                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        int dayOfMonth   = otherCalendar.Get(CalendarField.WeekOfMonth);
                        int todayOfMonth = todayCalendar.Get(CalendarField.WeekOfMonth);
                        if (dayOfMonth == todayOfMonth)
                        {    //表示是同一周
                            int dayOfWeek = otherCalendar.Get(CalendarField.DayOfWeek);
                            if (dayOfWeek != 1)
                            {    //判断当前是不是星期日     如想显示为:周日 12:09 可去掉此判断
                                toAppendTo.Append(weeks[otherCalendar.Get(CalendarField.DayOfWeek) - 1]);
                                toAppendTo.Append(' ');
                                toAppendTo.Append(timeFormat);
                            }
                            else
                            {
                                toAppendTo.Append(dateFormat);
                            }
                        }
                        else
                        {
                            toAppendTo.Append(dateFormat);
                        }
                        break;

                    default:
                        toAppendTo.Append(dateFormat);
                        break;
                    }
                }
                else
                {
                    toAppendTo.Append(dateFormat);
                }
            }
            else
            {
                toAppendTo.Append(yearFormat);
            }

            int length = toAppendTo.Length();

            toAppendTo.Append(Java.Lang.String.Format(locale, mFormat, toAppendTo.ToString()));
            toAppendTo.Delete(0, length);
            return(toAppendTo);
        }
Пример #55
0
 public static unsafe StringBuffer CreateFromNullTerminatedString(byte* start)
 {
     var buf = new StringBuffer();
     while (*start != 0)
     {
         buf.Append((char)*start++);
     }
     return buf;
 }
Пример #56
0
        private unsafe static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath)
        {
            // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To
            // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls.

            Contract.Assert(!PathInternal.IsPartiallyQualified(outputBuffer), "should have resolved by now");

            using (StringBuffer inputBuffer = new StringBuffer(outputBuffer))
            {
                bool success    = false;
                uint lastIndex  = outputBuffer.Length - 1;
                uint foundIndex = lastIndex;
                uint rootLength = PathInternal.GetRootLength(outputBuffer);

                while (!success)
                {
                    uint result = Win32Native.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity);

                    // Replace any temporary null we added
                    if (inputBuffer[foundIndex] == '\0')
                    {
                        inputBuffer[foundIndex] = '\\';
                    }

                    if (result == 0)
                    {
                        // Look to see if we couldn't find the file
                        int error = Marshal.GetLastWin32Error();
                        if (error != Win32Native.ERROR_FILE_NOT_FOUND && error != Win32Native.ERROR_PATH_NOT_FOUND)
                        {
                            // Some other failure, give up
                            break;
                        }

                        // We couldn't find the path at the given index, start looking further back in the string.
                        foundIndex--;

                        for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--)
                        {
                            ;
                        }
                        if (foundIndex == rootLength)
                        {
                            // Can't trim the path back any further
                            break;
                        }
                        else
                        {
                            // Temporarily set a null in the string to get Windows to look further up the path
                            inputBuffer[foundIndex] = '\0';
                        }
                    }
                    else if (result > outputBuffer.CharCapacity)
                    {
                        // Not enough space. The result count for this API does not include the null terminator.
                        outputBuffer.EnsureCharCapacity(result);
                    }
                    else
                    {
                        // Found the path
                        success             = true;
                        outputBuffer.Length = result;
                        if (foundIndex < lastIndex)
                        {
                            // It was a partial find, put the non-existant part of the path back
                            outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex);
                        }
                    }
                }

                StringBuffer bufferToUse = success ? outputBuffer : inputBuffer;

                if (bufferToUse.SubstringEquals(originalPath))
                {
                    // Use the original path to avoid allocating
                    return(originalPath);
                }

                return(bufferToUse.ToString());
            }
        }
Пример #57
0
    private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition)
    {
      if (writeToPosition > lastWritePosition)
      {
        buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition);
      }

      buffer.Append(writeChar);
    }
Пример #58
0
        /// <summary>
        /// Returns a formatted string describing the parameters.
        /// </summary>
        /// <returns> a formatted string describing the parameters. </returns>
        public override String ToString()
        {
            StringBuffer sb = new StringBuffer();

            sb.Append("[\n");

            /* start with trusted anchor info */
            if (UnmodTrustAnchors != null)
            {
                sb.Append("  Trust Anchors: " + UnmodTrustAnchors.ToString() + "\n");
            }

            /* now, append initial state information */
            if (UnmodInitialPolicies != null)
            {
                if (UnmodInitialPolicies.Count == 0)
                {
                    sb.Append("  Initial Policy OIDs: any\n");
                }
                else
                {
                    sb.Append("  Initial Policy OIDs: [" + UnmodInitialPolicies.ToString() + "]\n");
                }
            }

            /* now, append constraints on all certificates in the path */
            sb.Append("  Validity Date: " + Convert.ToString(Date_Renamed) + "\n");
            sb.Append("  Signature Provider: " + Convert.ToString(SigProvider_Renamed) + "\n");
            sb.Append("  Default Revocation Enabled: " + RevocationEnabled_Renamed + "\n");
            sb.Append("  Explicit Policy Required: " + ExplicitPolicyRequired_Renamed + "\n");
            sb.Append("  Policy Mapping Inhibited: " + PolicyMappingInhibited_Renamed + "\n");
            sb.Append("  Any Policy Inhibited: " + AnyPolicyInhibited_Renamed + "\n");
            sb.Append("  Policy Qualifiers Rejected: " + PolicyQualifiersRejected_Renamed + "\n");

            /* now, append target cert requirements */
            sb.Append("  Target Cert Constraints: " + Convert.ToString(CertSelector) + "\n");

            /* finally, append miscellaneous parameters */
            if (CertPathCheckers_Renamed != null)
            {
                sb.Append("  Certification Path Checkers: [" + CertPathCheckers_Renamed.ToString() + "]\n");
            }
            if (CertStores_Renamed != null)
            {
                sb.Append("  CertStores: [" + CertStores_Renamed.ToString() + "]\n");
            }
            sb.Append("]");
            return(sb.ToString());
        }