Acquire() public static method

public static Acquire ( int capacity = 256 ) : StringBuilder
capacity int
return StringBuilder
Beispiel #1
0
        public static string Combine(params string[] paths)
        {
            if (paths == null)
            {
                throw new ArgumentNullException(nameof(paths));
            }

            int finalSize      = 0;
            int firstComponent = 0;

            // We have two passes, the first calculates how large a buffer to allocate and does some precondition
            // checks on the paths passed in.  The second actually does the combination.

            for (int i = 0; i < paths.Length; i++)
            {
                if (paths[i] == null)
                {
                    throw new ArgumentNullException(nameof(paths));
                }

                if (paths[i].Length == 0)
                {
                    continue;
                }

                if (IsPathRooted(paths[i]))
                {
                    firstComponent = i;
                    finalSize      = paths[i].Length;
                }
                else
                {
                    finalSize += paths[i].Length;
                }

                char ch = paths[i][paths[i].Length - 1];
                if (!PathInternal.IsDirectorySeparator(ch))
                {
                    finalSize++;
                }
            }

            StringBuilder finalPath = StringBuilderCache.Acquire(finalSize);

            for (int i = firstComponent; i < paths.Length; i++)
            {
                if (paths[i].Length == 0)
                {
                    continue;
                }

                if (finalPath.Length == 0)
                {
                    finalPath.Append(paths[i]);
                }
                else
                {
                    char ch = finalPath[finalPath.Length - 1];
                    if (!PathInternal.IsDirectorySeparator(ch))
                    {
                        finalPath.Append(PathInternal.DirectorySeparatorChar);
                    }

                    finalPath.Append(paths[i]);
                }
            }

            return(StringBuilderCache.GetStringAndRelease(finalPath));
        }
Beispiel #2
0
        public static async Task <string> GetDigestTokenForCredential(NetworkCredential credential, HttpRequestMessage request, DigestResponse digestResponse)
        {
            StringBuilder sb = StringBuilderCache.Acquire();

            // It is mandatory for servers to implement sha-256 per RFC 7616
            // Keep MD5 for backward compatibility.
            string algorithm;
            bool   isAlgorithmSpecified = digestResponse.Parameters.TryGetValue(Algorithm, out algorithm);

            if (isAlgorithmSpecified)
            {
                if (!algorithm.Equals(Sha256, StringComparison.OrdinalIgnoreCase) &&
                    !algorithm.Equals(Md5, StringComparison.OrdinalIgnoreCase) &&
                    !algorithm.Equals(Sha256Sess, StringComparison.OrdinalIgnoreCase) &&
                    !algorithm.Equals(MD5Sess, StringComparison.OrdinalIgnoreCase))
                {
                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Error(digestResponse, "Algorithm not supported: {algorithm}");
                    }
                    return(null);
                }
            }
            else
            {
                algorithm = Md5;
            }

            // Check if nonce is there in challenge
            string nonce;

            if (!digestResponse.Parameters.TryGetValue(Nonce, out nonce))
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(digestResponse, "Nonce missing");
                }
                return(null);
            }

            // opaque token may or may not exist
            string opaque;

            digestResponse.Parameters.TryGetValue(Opaque, out opaque);

            string realm;

            if (!digestResponse.Parameters.TryGetValue(Realm, out realm))
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(digestResponse, "Realm missing");
                }
                return(null);
            }

            // Add username
            string userhash;

            if (digestResponse.Parameters.TryGetValue(UserHash, out userhash) && userhash == "true")
            {
                sb.AppendKeyValue(Username, ComputeHash(credential.UserName + ":" + realm, algorithm));
                sb.AppendKeyValue(UserHash, userhash, includeQuotes: false);
            }
            else
            {
                if (HeaderUtilities.ContainsNonAscii(credential.UserName))
                {
                    string usernameStar = HeaderUtilities.Encode5987(credential.UserName);
                    sb.AppendKeyValue(UsernameStar, usernameStar, includeQuotes: false);
                }
                else
                {
                    sb.AppendKeyValue(Username, credential.UserName);
                }
            }

            // Add realm
            if (realm != string.Empty)
            {
                sb.AppendKeyValue(Realm, realm);
            }

            // Add nonce
            sb.AppendKeyValue(Nonce, nonce);

            // Add uri
            sb.AppendKeyValue(Uri, request.RequestUri.PathAndQuery);

            // Set qop, default is auth
            string qop            = Auth;
            bool   isQopSpecified = digestResponse.Parameters.ContainsKey(Qop);

            if (isQopSpecified)
            {
                // Check if auth-int present in qop string
                int index1 = digestResponse.Parameters[Qop].IndexOf(AuthInt, StringComparison.Ordinal);
                if (index1 != -1)
                {
                    // Get index of auth if present in qop string
                    int index2 = digestResponse.Parameters[Qop].IndexOf(Auth, StringComparison.Ordinal);

                    // If index2 < index1, auth option is available
                    // If index2 == index1, check if auth option available later in string after auth-int.
                    if (index2 == index1)
                    {
                        index2 = digestResponse.Parameters[Qop].IndexOf(Auth, index1 + AuthInt.Length, StringComparison.Ordinal);
                        if (index2 == -1)
                        {
                            qop = AuthInt;
                        }
                    }
                }
            }

            // Set cnonce
            string cnonce = GetRandomAlphaNumericString();

            // Calculate response
            string a1 = credential.UserName + ":" + realm + ":" + credential.Password;

            if (algorithm.EndsWith("sess", StringComparison.OrdinalIgnoreCase))
            {
                a1 = ComputeHash(a1, algorithm) + ":" + nonce + ":" + cnonce;
            }

            string a2 = request.Method.Method + ":" + request.RequestUri.PathAndQuery;

            if (qop == AuthInt)
            {
                string content = request.Content == null ? string.Empty : await request.Content.ReadAsStringAsync().ConfigureAwait(false);

                a2 = a2 + ":" + ComputeHash(content, algorithm);
            }

            string response;

            if (isQopSpecified)
            {
                response = ComputeHash(ComputeHash(a1, algorithm) + ":" +
                                       nonce + ":" +
                                       DigestResponse.NonceCount + ":" +
                                       cnonce + ":" +
                                       qop + ":" +
                                       ComputeHash(a2, algorithm), algorithm);
            }
            else
            {
                response = ComputeHash(ComputeHash(a1, algorithm) + ":" +
                                       nonce + ":" +
                                       ComputeHash(a2, algorithm), algorithm);
            }

            // Add response
            sb.AppendKeyValue(Response, response, includeComma: opaque != null || isAlgorithmSpecified || isQopSpecified);

            // Add opaque
            if (opaque != null)
            {
                sb.AppendKeyValue(Opaque, opaque, includeComma: isAlgorithmSpecified || isQopSpecified);
            }

            if (isAlgorithmSpecified)
            {
                // Add algorithm
                sb.AppendKeyValue(Algorithm, algorithm, includeQuotes: false, includeComma: isQopSpecified);
            }

            if (isQopSpecified)
            {
                // Add qop
                sb.AppendKeyValue(Qop, qop, includeQuotes: false);

                // Add nc
                sb.AppendKeyValue(NC, DigestResponse.NonceCount, includeQuotes: false);

                // Add cnonce
                sb.AppendKeyValue(CNonce, cnonce, includeComma: false);
            }

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #3
0
        // Three very similar algorithms appear below: replace (pattern),
        // replace (evaluator), and split.

        /// <summary>
        /// Replaces all occurrences of the regex in the string with the
        /// replacement pattern.
        ///
        /// Note that the special case of no matches is handled on its own:
        /// with no matches, the input string is returned unchanged.
        /// The right-to-left case is split out because StringBuilder
        /// doesn't handle right-to-left string building directly very well.
        /// </summary>
        public string Replace(Regex regex, string input, int count, int startat)
        {
            if (count < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
            }
            if (startat < 0 || startat > input.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
            }

            if (count == 0)
            {
                return(input);
            }

            Match match = regex.Match(input, startat);

            if (!match.Success)
            {
                return(input);
            }
            else
            {
                StringBuilder sb = StringBuilderCache.Acquire();

                if (!regex.RightToLeft)
                {
                    int prevat = 0;

                    do
                    {
                        if (match.Index != prevat)
                        {
                            sb.Append(input, prevat, match.Index - prevat);
                        }

                        prevat = match.Index + match.Length;
                        ReplacementImpl(sb, match);
                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat < input.Length)
                    {
                        sb.Append(input, prevat, input.Length - prevat);
                    }
                }
                else
                {
                    List <string> al     = new List <string>();
                    int           prevat = input.Length;

                    do
                    {
                        if (match.Index + match.Length != prevat)
                        {
                            al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length));
                        }

                        prevat = match.Index;
                        ReplacementImplRTL(al, match);
                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat > 0)
                    {
                        sb.Append(input, 0, prevat);
                    }

                    for (int i = al.Count - 1; i >= 0; i--)
                    {
                        sb.Append(al[i]);
                    }
                }

                return(StringBuilderCache.GetStringAndRelease(sb));
            }
        }
Beispiel #4
0
    private static string PrintVariable(IntPtr l, int i, int depth)
    {
        if (LuaDLL.lua_isstring(l, i) == 1)
        {
            return(LuaDLL.lua_tostring(l, i));
        }
        else if (LuaDLL.lua_isnil(l, i))
        {
            return("nil");
        }
        else if (LuaDLL.lua_isboolean(l, i))
        {
            return(LuaDLL.lua_toboolean(l, i) ? "true" : "false");
        }
        else if (LuaDLL.lua_istable(l, i))
        {
            if (depth > 3)
            {
                return("{...}");
            }

            var sb = StringBuilderCache.Acquire();
            sb.Append("{");

            int count = 0;
            LuaDLL.lua_pushvalue(l, i);
            LuaDLL.lua_pushnil(l);
            while (LuaDLL.lua_next(l, i) != 0)
            {
                LuaDLL.lua_pushvalue(l, -2);
                var key   = PrintVariable(l, -1, depth + 1);
                var value = PrintVariable(l, -2, depth + 1);
                if (count == 0)
                {
                    sb.AppendFormat("{0} = {1}", key, value);
                }
                else
                {
                    sb.AppendFormat(", {0} = {1}", key, value);
                }

                LuaDLL.lua_pop(l, 2);
                ++count;
            }

            LuaDLL.lua_pop(l, 1);
            sb.Append("}");
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
        else
        {
            var p = LuaDLL.lua_topointer(l, i);
            if (p == IntPtr.Zero)
            {
                return("nil");
            }
            else
            {
                return(string.Format(
                           "{0}:0x{1}",
                           LuaDLL.luaL_typename(l, i),
                           p.ToString("X")));
            }
        }
    }
Beispiel #5
0
        // Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL)
        private String UnescapeURL(String url)
        {
            StringBuilder intermediate = StringBuilderCache.Acquire(url.Length);
            int           Rindex       = 0; // index into temp that gives the rest of the string to be processed
            int           index;
            int           braIndex = -1;
            int           ketIndex = -1;

            braIndex = url.IndexOf('[', Rindex);
            if (braIndex != -1)
            {
                ketIndex = url.IndexOf(']', braIndex);
            }

            do
            {
                index = url.IndexOf('%', Rindex);

                if (index == -1)
                {
                    intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex));
                    break;
                }
                // if we hit a '%' in the middle of an IPv6 address, dont process that
                if (index > braIndex && index < ketIndex)
                {
                    intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex + 1));
                    Rindex       = ketIndex + 1;
                    continue;
                }

                if (url.Length - index < 2)     // Check that there is at least 1 char after the '%'
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUrl"));
                }

                if (url[index + 1] == 'u' || url[index + 1] == 'U')
                {
                    if (url.Length - index < 6)     // example: "%u004d" is 6 chars long
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUrl"));
                    }

                    // We have a unicode character specified in hex

                    try
                    {
                        char c = (char)(Hex.ConvertHexDigit(url[index + 2]) << 12 |
                                        Hex.ConvertHexDigit(url[index + 3]) << 8 |
                                        Hex.ConvertHexDigit(url[index + 4]) << 4 |
                                        Hex.ConvertHexDigit(url[index + 5]));
                        intermediate = intermediate.Append(url, Rindex, index - Rindex);
                        intermediate = intermediate.Append(c);
                    }
                    catch (ArgumentException)    // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUrl"));
                    }

                    Rindex = index + 6;      //update the 'seen' length
                }
                else
                {
                    // we have a hex character.

                    if (url.Length - index < 3)     // example: "%4d" is 3 chars long
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUrl"));
                    }

                    try
                    {
                        char c = (char)(Hex.ConvertHexDigit(url[index + 1]) << 4 | Hex.ConvertHexDigit(url[index + 2]));

                        intermediate = intermediate.Append(url, Rindex, index - Rindex);
                        intermediate = intermediate.Append(c);
                    }
                    catch (ArgumentException)    // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUrl"));
                    }

                    Rindex = index + 3;     // update the 'seen' length
                }
            }while (true);
            return(StringBuilderCache.GetStringAndRelease(intermediate));
        }
        private static string Serialize(ReadOnlyCollection <string>?payloadName, ReadOnlyCollection <object?>?payload, string?eventMessage)
        {
            if (payloadName == null || payload == null)
            {
                return(string.Empty);
            }

            if (payloadName.Count == 0 || payload.Count == 0)
            {
                return(string.Empty);
            }

            int eventDataCount = payloadName.Count;

            if (payloadName.Count != payload.Count)
            {
                eventDataCount = Math.Min(payloadName.Count, payload.Count);
            }

            var sb = StringBuilderCache.Acquire();

            sb.Append('{');

            // If the event has a message, send that as well as a pseudo-field
            if (!string.IsNullOrEmpty(eventMessage))
            {
                sb.Append("\\\"EventSource_Message\\\":\\\"");
                minimalJsonserializer(eventMessage, sb);
                sb.Append("\\\"");
                if (eventDataCount != 0)
                {
                    sb.Append(", ");
                }
            }

            for (int i = 0; i < eventDataCount; i++)
            {
                if (i != 0)
                {
                    sb.Append(", ");
                }

                var fieldstr = payloadName[i].ToString();

                sb.Append("\\\"");
                sb.Append(fieldstr);
                sb.Append("\\\"");
                sb.Append(':');

                switch (payload[i])
                {
                case string str:
                {
                    sb.Append("\\\"");
                    minimalJsonserializer(str, sb);
                    sb.Append("\\\"");
                    break;
                }

                case byte[] byteArr:
                {
                    sb.Append("\\\"");
                    AppendByteArrayAsHexString(sb, byteArr);
                    sb.Append("\\\"");
                    break;
                }

                default:
                {
                    if (payload[i] != null)
                    {
                        sb.Append(payload[i] !.ToString());    // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644)
                    }
                    break;
                }
                }
            }
            sb.Append('}');
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #7
0
        public static System.Func <string, string> CustomGetResourcesPath; // 自定义资源路径。。。

        /// <summary>
        /// 统一在字符串后加上.box, 取决于配置的AssetBundle后缀
        /// </summary>
        /// <param name="path"></param>
        /// <param name="formats"></param>
        /// <returns></returns>
        public static string GetAssetBundlePath(string path, params object[] formats)
        {
            var tmpFormat = StringBuilderCache.GetStringAndRelease(StringBuilderCache.Acquire().Append(path).Append(EngineConfig.instance.ABExtName));

            return(StringBuilderCache.GetStringAndRelease(StringBuilderCache.Acquire().AppendFormat(tmpFormat, formats)));
        }
        /// <summary>
        /// Format a numeric value following KSP date/time standards.  For KDT,
        /// we add one to the days column to mimic KSP behavior.
        /// </summary>
        /// <param name="formatSpecification"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string FormatMET(string formatSpecification, double value)
        {
            double hoursPerDay = KSPUtil.dateTimeFormatter.Day / 3600.0;
            double daysPerYear = KSPUtil.dateTimeFormatter.Year / KSPUtil.dateTimeFormatter.Day;

            // seconds...
            double timeBalance = (double.IsInfinity(value) || double.IsNaN(value)) ? 0.0 : Math.Abs(value);

            vals[0] = (int)(timeBalance % 60.0);
            // minutes...
            timeBalance /= 60.0;
            vals[1]      = (int)(timeBalance % 60.0);
            // hours...
            timeBalance /= 60.0;
            vals[2]      = (int)(timeBalance % hoursPerDay);
            // days...
            timeBalance /= hoursPerDay;
            vals[3]      = (int)(timeBalance % daysPerYear);
            // years...
            vals[4] = (int)(timeBalance / daysPerYear);

            char[] chars = formatSpecification.ToCharArray();

            bool calendarAdjust = (chars[1] == 'D');
            bool negativeValue  = (value < 0.0);

            bool activeFormatter = false;
            bool didSomething    = false;
            char activeChar      = ' ';
            int  charCount       = 0;
            int  parameterCount  = 0;
            int  numChars        = chars.Length;
            int  parameterLimit  = formatData.Length;

            for (int i = 0; i < parameterLimit; ++i)
            {
                formatData[i] = null;
            }

            StringBuilder sb = StringBuilderCache.Acquire();

            for (int i = 3; i < numChars && parameterCount < parameterLimit; ++i)
            {
                didSomething = false;
                if (activeFormatter)
                {
                    if (chars[i] == activeChar)
                    {
                        ++charCount;
                        didSomething = true;
                    }
                    else
                    {
                        // Changed format or ended format.  Update SB and format array
                        activeFormatter = false;
                        sb.Append('{');
                        sb.Append(parameterCount);
                        sb.Append(':');
                        sb.Append('0', charCount);
                        sb.Append('}');

                        switch (activeChar)
                        {
                        case 'Y':
                        // Fall through
                        case 'y':
                            formatData[parameterCount] = (vals[4] + (calendarAdjust ? 1 : 0));
                            break;

                        case 'D':
                            formatData[parameterCount] = (int)(vals[3] + daysPerYear * vals[4]);
                            break;

                        case 'd':
                            formatData[parameterCount] = (vals[3] + (calendarAdjust ? 1 : 0));
                            break;

                        case 'H':
                            formatData[parameterCount] = (int)(vals[2] + hoursPerDay * vals[3] + daysPerYear * vals[4]);
                            break;

                        case 'h':
                            formatData[parameterCount] = vals[2];
                            break;

                        case 'M':
                            formatData[parameterCount] = (int)(vals[1] + 60 * vals[2] + hoursPerDay * vals[3] + daysPerYear * vals[4]);
                            break;

                        case 'm':
                            formatData[parameterCount] = vals[1];
                            break;

                        case 'S':
                            formatData[parameterCount] = Math.Floor(Math.Abs(value));
                            break;

                        case 's':
                            formatData[parameterCount] = vals[0];
                            break;

                        case 'f':
                            double fracV = Math.Abs(value) - Math.Floor(Math.Abs(value));
                            fracV = fracV * Math.Pow(10.0, charCount);
                            formatData[parameterCount] = Math.Floor(fracV);
                            break;
                        }
                        ++parameterCount;
                        charCount = 0;
                    }
                }

                if (!didSomething)
                {
                    switch (chars[i])
                    {
                    case 'Y':
                    case 'y':
                    case 'D':
                    case 'd':
                    case 'H':
                    case 'h':
                    case 'M':
                    case 'm':
                    case 'S':
                    case 's':
                    case 'f':
                        activeChar      = chars[i];
                        activeFormatter = true;
                        charCount       = 1;
                        break;

                    case '+':
                        sb.Append((negativeValue) ? '-' : '+');
                        break;

                    case '-':
                        if (negativeValue)
                        {
                            sb.Append('-');
                        }
                        break;

                    default:
                        sb.Append(chars[i]);
                        break;
                    }
                }
            }

            if (activeFormatter && parameterCount < parameterLimit)
            {
                activeFormatter = false;
                sb.Append('{');
                sb.Append(parameterCount);
                sb.Append(':');
                sb.Append('0', charCount);
                sb.Append('}');

                switch (activeChar)
                {
                case 'Y':
                // Fall through
                case 'y':
                    formatData[parameterCount] = Math.Abs(vals[4]);
                    break;

                case 'D':
                    formatData[parameterCount] = Math.Abs(vals[3] + daysPerYear * vals[4]);
                    break;

                case 'd':
                    formatData[parameterCount] = Math.Abs(vals[3] + (calendarAdjust ? 1 : 0));
                    break;

                case 'H':
                    formatData[parameterCount] = Math.Abs(vals[2] + hoursPerDay * vals[3] + daysPerYear * vals[4]);
                    break;

                case 'h':
                    formatData[parameterCount] = Math.Abs(vals[2]);
                    break;

                case 'M':
                    formatData[parameterCount] = Math.Abs(vals[1] + 60 * vals[2] + hoursPerDay * vals[3] + daysPerYear * vals[4]);
                    break;

                case 'm':
                    formatData[parameterCount] = Math.Abs(vals[1]);
                    break;

                case 'S':
                    formatData[parameterCount] = Math.Floor(Math.Abs(value));
                    break;

                case 's':
                    formatData[parameterCount] = Math.Abs(vals[0]);
                    break;

                case 'f':
                    double fracV = Math.Abs(value) - Math.Floor(Math.Abs(value));
                    fracV = fracV * Math.Pow(10.0, charCount);
                    formatData[parameterCount] = Math.Floor(fracV);
                    break;
                }
                charCount = 0;
                ++parameterCount;
            }

            string result = string.Format(sb.ToStringAndRelease(), formatData);

            return(result);
        }
Beispiel #9
0
        private static void DumpConfigNode(ConfigNode node, int depth)
        {
            StringBuilder strb = StringBuilderCache.Acquire();

            strb.Remove(0, strb.Length);
            if (depth > 0)
            {
                strb.Append(' ', depth);
            }
            strb.Append('+');
            strb.Append(' ');
            strb.Append(node.name);
            if (!node.HasData)
            {
                strb.Append(" - has no data");
            }
            LogStaticMessage(strb.ToStringAndRelease());
            if (!node.HasData)
            {
                return;
            }

            var vals = node.values;

            if (vals.Count == 0)
            {
                strb = StringBuilderCache.Acquire();
                if (depth > 0)
                {
                    strb.Append(' ', depth);
                }
                strb.Append("- No values");
                LogStaticMessage(strb.ToStringAndRelease());
            }
            for (int i = 0; i < vals.Count; ++i)
            {
                strb = StringBuilderCache.Acquire();
                if (depth > 0)
                {
                    strb.Append(' ', depth);
                }
                strb.Append('-');
                strb.Append(' ');
                strb.Append(vals[i].name);
                strb.Append(" = ");
                strb.Append(vals[i].value);
                LogStaticMessage(strb.ToStringAndRelease());
            }

            var nodes = node.nodes;

            if (nodes.Count == 0)
            {
                strb = StringBuilderCache.Acquire();
                if (depth > 0)
                {
                    strb.Append(' ', depth);
                }
                strb.Append("- No child ConfigNode");
                LogStaticMessage(strb.ToStringAndRelease());
            }
            for (int i = 0; i < nodes.Count; ++i)
            {
                DumpConfigNode(nodes[i], depth + 1);
            }
        }
Beispiel #10
0
        public string ToFormatString(string newLineIndent)
        {
            var sb = StringBuilderCache.Acquire();

            sb.Append("UnitInfo{\r\n");
            var curIndent = newLineIndent + '\t';

            if (HasPlayerId())
            {
                sb.Append(",\r\n").Append(curIndent).Append("playerId = ");
                sb.Append(playerId);
            }
            if (HasUid())
            {
                sb.Append(",\r\n").Append(curIndent).Append("uid = ");
                sb.Append(uid);
            }
            if (HasName())
            {
                sb.Append(",\r\n").Append(curIndent).Append("name = ");
                sb.Append(name);
            }
            if (HasAppearance())
            {
                sb.Append(",\r\n").Append(curIndent).Append("appearance = ");
                sb.Append(appearance);
            }
            if (HasCategory())
            {
                sb.Append(",\r\n").Append(curIndent).Append("category = ");
                sb.Append(category);
            }
            if (HasType())
            {
                sb.Append(",\r\n").Append(curIndent).Append("type = ");
                sb.Append(type);
            }
            if (HasCamp())
            {
                sb.Append(",\r\n").Append(curIndent).Append("camp = ");
                sb.Append(camp);
            }
            if (HasLev())
            {
                sb.Append(",\r\n").Append(curIndent).Append("lev = ");
                sb.Append(lev);
            }
            if (HasX())
            {
                sb.Append(",\r\n").Append(curIndent).Append("x = ");
                sb.Append(x);
            }
            if (HasY())
            {
                sb.Append(",\r\n").Append(curIndent).Append("y = ");
                sb.Append(y);
            }
            if (HasZ())
            {
                sb.Append(",\r\n").Append(curIndent).Append("z = ");
                sb.Append(z);
            }
            if (HasFaceTo())
            {
                sb.Append(",\r\n").Append(curIndent).Append("faceTo = ");
                sb.Append(faceTo);
            }
            if (HasHpPercent())
            {
                sb.Append(",\r\n").Append(curIndent).Append("hpPercent = ");
                sb.Append(hpPercent);
            }
            if (HasMpPercent())
            {
                sb.Append(",\r\n").Append(curIndent).Append("mpPercent = ");
                sb.Append(mpPercent);
            }
            if (HasMoveSpeed())
            {
                sb.Append(",\r\n").Append(curIndent).Append("moveSpeed = ");
                sb.Append(moveSpeed);
            }
            if (HasActionState())
            {
                sb.Append(",\r\n").Append(curIndent).Append("actionState = ");
                sb.Append(actionState);
            }
            if (HasCurrentAnim())
            {
                sb.Append(",\r\n").Append(curIndent).Append("currentAnim = ");
                sb.Append(currentAnim);
            }
            if (HasEffectShow())
            {
                sb.Append(",\r\n").Append(curIndent).Append("effectShow = ");
                sb.Append(effectShow);
            }
            if (HasControlFlag())
            {
                sb.Append(",\r\n").Append(curIndent).Append("controlFlag = ");
                sb.Append(controlFlag);
            }
            if (HasBuffsData())
            {
                sb.Append(",\r\n").Append(curIndent).Append("buffsData = ");
                sb.Append(buffsData == null ? "null" : buffsData.ToFormatString(curIndent));
            }
            sb.Append("\r\n");
            sb.Append(newLineIndent).Append('}');
            return(StringBuilderCache.GetAndRelease(sb));
        }
        private static string Serialize(ReadOnlyCollection <string> payloadName, ReadOnlyCollection <object> payload, string eventMessage)
        {
            if (payloadName == null || payload == null)
            {
                return(String.Empty);
            }

            if (payloadName.Count == 0 || payload.Count == 0)
            {
                return(String.Empty);
            }

            int eventDataCount = payloadName.Count;

            if (payloadName.Count != payload.Count)
            {
                eventDataCount = Math.Min(payloadName.Count, payload.Count);
            }

            var sb = StringBuilderCache.Acquire();

            sb.Append('{');

            // If the event has a message, send that as well as a pseudo-field
            if (!string.IsNullOrEmpty(eventMessage))
            {
                sb.Append("\\\"EventSource_Message\\\":\\\"");
                minimalJsonserializer(eventMessage, sb);
                sb.Append("\\\"");
                if (eventDataCount != 0)
                {
                    sb.Append(", ");
                }
            }

            for (int i = 0; i < eventDataCount; i++)
            {
                if (i != 0)
                {
                    sb.Append(", ");
                }

                var fieldstr = payloadName[i].ToString();

                sb.Append("\\\"");
                sb.Append(fieldstr);
                sb.Append("\\\"");
                sb.Append(':');

                var valuestr = payload[i] as string;

                if (valuestr != null)
                {
                    sb.Append("\\\"");
                    minimalJsonserializer(valuestr, sb);
                    sb.Append("\\\"");
                }
                else
                {
                    sb.Append(payload[i].ToString());
                }
            }
            sb.Append('}');
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #12
0
        private static string _TryParseInterpretedString(string source, ref int index, out JsonValue value)
        {
            value = null;

            string errorMessage = null;
            var    builder      = StringBuilderCache.Acquire();
            var    complete     = false;

            while (index < source.Length)
            {
                var c = source[index++];
                if (c != '\\')
                {
                    if (c == '"')
                    {
                        complete = true;
                        break;
                    }

                    builder.Append(c);
                }
                else
                {
                    if (index >= source.Length)
                    {
                        return("Could not find end of string value.");
                    }

                    string append = null;
                    c = source[index++];
                    switch (c)
                    {
                    case 'b':
                        append = "\b";
                        break;

                    case 'f':
                        append = "\f";
                        break;

                    case 'n':
                        append = "\n";
                        break;

                    case 'r':
                        append = "\r";
                        break;

                    case 't':
                        append = "\t";
                        break;

                    case 'u':
                        var length = 4;
                        if (index + length >= source.Length)
                        {
                            errorMessage = $"Invalid escape sequence: '\\{c}{source.Substring(index)}'.";
                            break;
                        }

                        if (!_IsValidHex(source, index, 4) ||
                            !int.TryParse(source.Substring(index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int hex))
                        {
                            errorMessage = $"Invalid escape sequence: '\\{c}{source.Substring(index, length)}'.";
                            break;
                        }

                        if (index + length + 2 < source.Length &&
                            source.IndexOf("\\u", index + length, 2) == index + length)
                        {
                            // +2 from \u
                            // +4 from the next four hex chars
                            length += 6;

                            if (index + length >= source.Length)
                            {
                                errorMessage = $"Invalid escape sequence: '\\{c}{source.Substring(index)}'.";
                                break;
                            }

                            if (!_IsValidHex(source, index + 6, 4) ||
                                !int.TryParse(source.Substring(index + 6, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int hex2))
                            {
                                errorMessage = $"Invalid escape sequence: '\\{c}{source.Substring(index, length)}'.";
                                break;
                            }

                            var surrogatePairHex = StringExtensions.CalculateUtf32(hex, hex2);

                            if (surrogatePairHex.IsValidUtf32CodePoint())
                            {
                                hex = surrogatePairHex;
                            }
                            else
                            {
                                length -= 6;
                            }
                        }

                        append = char.ConvertFromUtf32(hex);
                        index += length;
                        break;

                    case '"':
                        append = "\"";
                        break;

                    case '\\':
                        append = "\\";
                        break;

                    // Is this correct?
                    case '/':
                        append = "/";
                        break;

                    default:
                        complete     = true;
                        errorMessage = $"Invalid escape sequence: '\\{c}'.";
                        break;
                    }

                    if (append == null)
                    {
                        break;
                    }

                    builder.Append(append);
                }
            }

            if (!complete || errorMessage != null)
            {
                value = null;
                StringBuilderCache.Release(builder);
                return(errorMessage ?? "Could not find end of string value.");
            }
            value = StringBuilderCache.GetStringAndRelease(builder);
            return(null);
        }
Beispiel #13
0
        internal string PeekUTF8NullTerminated(
            int offset,
            out int numberOfBytesRead
            )
        {
            if (checked (this.CurrentPointer - this.Buffer + offset) >= this.Length)
            {
                numberOfBytesRead = 0; return("");
            }
            byte *        pStart = this.CurrentPointer + offset;
            byte *        pEnd   = this.Buffer + this.Length;
            byte *        pIter  = pStart;
            StringBuilder sb     = StringBuilderCache.Acquire();
            byte          b      = 0;

            for (; ;)
            {
                b = *pIter++;
                if (b == 0 || pIter == pEnd)
                {
                    break;
                }
                if ((b & 0x80) == 0)
                {
                    sb.Append((char)b);
                    continue;
                }
                char ch;
                byte b1 = *pIter++;
                if (b1 == 0 || pIter == pEnd) //Dangling lead byte, do not decompose
                {
                    sb.Append((char)b);
                    break;
                }
                if ((b & 0x20) == 0)
                {
                    ch = (char)(((b & 0x1F) << 6) | (b1 & 0x3F));
                }
                else
                {
                    byte b2 = *pIter++;
                    if (b2 == 0 || pIter == pEnd) //Dangling lead bytes, do not decompose
                    {
                        sb.Append((char)((b << 8) | b1));
                        break;
                    }
                    uint ch32;
                    if ((b & 0x10) == 0)
                    {
                        ch32 = (uint)(((b & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F));
                    }
                    else
                    {
                        byte b3 = *pIter++;
                        if (b3 == 0 || pIter == pEnd) //Dangling lead bytes, do not decompose
                        {
                            sb.Append((char)((b << 8) | b1));
                            sb.Append((char)b2);
                            break;
                        }
                        ch32 = (uint)(((b & 0x07) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F));
                    }
                    if ((ch32 & 0xFFFF0000) == 0)
                    {
                        ch = (char)ch32;
                    }
                    else //break up into UTF16 surrogate pair
                    {
                        sb.Append((char)((ch32 >> 10) | 0xD800));
                        ch = (char)((ch32 & 0x3FF) | 0xDC00);
                    }
                }
                sb.Append(ch);
            }
            numberOfBytesRead = (int)(pIter - pStart);
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #14
0
        internal string ReadUTF8WithSize(
            int byteCount
            )
        {
            if (checked (this.CurrentPointer - this.Buffer + byteCount) > this.Length)
            {
                throw new ArgumentOutOfRangeException();
            }

            int           bytesToRead = byteCount;
            StringBuilder buffer      = StringBuilderCache.Acquire();
            byte *        pb          = this.CurrentPointer;

            while (bytesToRead > 0)
            {
                byte b = *pb++; bytesToRead--;
                if ((b & 0x80) == 0 || bytesToRead == 0)
                {
                    buffer.Append((char)b);
                    continue;
                }
                char ch;
                byte b1 = *pb++; bytesToRead--;
                if ((b & 0x20) == 0)
                {
                    ch = (char)(((b & 0x1F) << 6) | (b1 & 0x3F));
                }
                else
                {
                    if (bytesToRead == 0) //Dangling lead bytes, do not decompose
                    {
                        buffer.Append((char)((b << 8) | b1));
                        break;
                    }
                    byte b2 = *pb++; bytesToRead--;
                    uint ch32;
                    if ((b & 0x10) == 0)
                    {
                        ch32 = (uint)(((b & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F));
                    }
                    else
                    {
                        if (bytesToRead == 0) //Dangling lead bytes, do not decompose
                        {
                            buffer.Append((char)((b << 8) | b1));
                            buffer.Append((char)b2);
                            break;
                        }
                        byte b3 = *pb++; bytesToRead--;
                        ch32 = (uint)(((b & 0x07) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F));
                    }
                    if ((ch32 & 0xFFFF0000) == 0)
                    {
                        ch = (char)ch32;
                    }
                    else //break up into UTF16 surrogate pair
                    {
                        buffer.Append((char)((ch32 >> 10) | 0xD800));
                        ch = (char)((ch32 & 0x3FF) | 0xDC00);
                    }
                }
                buffer.Append(ch);
            }
            int j = buffer.Length;

            while (j > 0 && buffer[j - 1] == (char)0)
            {
                j--;
            }
            buffer.Length        = j;
            this.CurrentPointer += byteCount;
            return(StringBuilderCache.GetStringAndRelease(buffer));
        }
        /// <summary>Format the TimeSpan instance using the specified format.</summary>
        private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan <char> format, DateTimeFormatInfo dtfi, StringBuilder result)
        {
            Debug.Assert(dtfi != null);

            bool resultBuilderIsPooled = false;

            if (result == null)
            {
                result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
                resultBuilderIsPooled = true;
            }

            int  day  = (int)(value.Ticks / TimeSpan.TicksPerDay);
            long time = value.Ticks % TimeSpan.TicksPerDay;

            if (value.Ticks < 0)
            {
                day  = -day;
                time = -time;
            }
            int hours    = (int)(time / TimeSpan.TicksPerHour % 24);
            int minutes  = (int)(time / TimeSpan.TicksPerMinute % 60);
            int seconds  = (int)(time / TimeSpan.TicksPerSecond % 60);
            int fraction = (int)(time % TimeSpan.TicksPerSecond);

            long tmp = 0;
            int  i   = 0;
            int  tokenLen;

            while (i < format.Length)
            {
                char ch = format[i];
                int  nextChar;
                switch (ch)
                {
                case 'h':
                    tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                    if (tokenLen > 2)
                    {
                        goto default;     // to release the builder and throw
                    }
                    DateTimeFormat.FormatDigits(result, hours, tokenLen);
                    break;

                case 'm':
                    tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                    if (tokenLen > 2)
                    {
                        goto default;     // to release the builder and throw
                    }
                    DateTimeFormat.FormatDigits(result, minutes, tokenLen);
                    break;

                case 's':
                    tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                    if (tokenLen > 2)
                    {
                        goto default;     // to release the builder and throw
                    }
                    DateTimeFormat.FormatDigits(result, seconds, tokenLen);
                    break;

                case 'f':
                    //
                    // The fraction of a second in single-digit precision. The remaining digits are truncated.
                    //
                    tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                    if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
                    {
                        goto default;     // to release the builder and throw
                    }

                    tmp  = fraction;
                    tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
                    result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
                    break;

                case 'F':
                    //
                    // Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
                    //
                    tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                    if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
                    {
                        goto default;     // to release the builder and throw
                    }

                    tmp  = fraction;
                    tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
                    int effectiveDigits = tokenLen;
                    while (effectiveDigits > 0)
                    {
                        if (tmp % 10 == 0)
                        {
                            tmp = tmp / 10;
                            effectiveDigits--;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (effectiveDigits > 0)
                    {
                        result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
                    }
                    break;

                case 'd':
                    //
                    // tokenLen == 1 : Day as digits with no leading zero.
                    // tokenLen == 2+: Day as digits with leading zero for single-digit days.
                    //
                    tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                    if (tokenLen > 8)
                    {
                        goto default;     // to release the builder and throw
                    }

                    DateTimeFormat.FormatDigits(result, day, tokenLen, true);
                    break;

                case '\'':
                case '\"':
                    tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
                    break;

                case '%':
                    // Optional format character.
                    // For example, format string "%d" will print day
                    // Most of the cases, "%" can be ignored.
                    nextChar = DateTimeFormat.ParseNextChar(format, i);
                    // nextChar will be -1 if we already reach the end of the format string.
                    // Besides, we will not allow "%%" appear in the pattern.
                    if (nextChar >= 0 && nextChar != (int)'%')
                    {
                        char nextCharChar = (char)nextChar;
                        ReadOnlySpan <char> nextCharSpan;
#if MONO
                        // Remove once Mono switches to Fast Spans
                        unsafe
                        {
                            nextCharSpan = new ReadOnlySpan <char>(&nextCharChar, 1);
                        }
#else
                        nextCharSpan = MemoryMarshal.CreateReadOnlySpan <char>(ref nextCharChar, 1);
#endif
                        StringBuilder origStringBuilder = FormatCustomized(value, nextCharSpan, dtfi, result);
                        Debug.Assert(ReferenceEquals(origStringBuilder, result));
                        tokenLen = 2;
                    }
                    else
                    {
                        //
                        // This means that '%' is at the end of the format string or
                        // "%%" appears in the format string.
                        //
                        goto default;     // to release the builder and throw
                    }
                    break;

                case '\\':
                    // Escaped character.  Can be used to insert character into the format string.
                    // For example, "\d" will insert the character 'd' into the string.
                    //
                    nextChar = DateTimeFormat.ParseNextChar(format, i);
                    if (nextChar >= 0)
                    {
                        result.Append(((char)nextChar));
                        tokenLen = 2;
                    }
                    else
                    {
                        //
                        // This means that '\' is at the end of the formatting string.
                        //
                        goto default;     // to release the builder and throw
                    }
                    break;

                default:
                    // Invalid format string
                    if (resultBuilderIsPooled)
                    {
                        StringBuilderCache.Release(result);
                    }
                    throw new FormatException(SR.Format_InvalidString);
                }
                i += tokenLen;
            }
            return(result);
        }
        internal static string CreateManifestNameImpl
        (
            string fileName,
            string linkFileName,
            bool prependCultureAsDirectory, // true by default
            string rootNamespace,           // May be null
            string dependentUponFileName,   // May be null
            string culture,                 // may be null
            Stream binaryStream,            // File contents binary stream, may be null
            TaskLoggingHelper log,
            bool treatAsCultureNeutral = false
        )
        {
            // Use the link file name if there is one, otherwise, fall back to file name.
            string embeddedFileName = FileUtilities.FixFilePath(linkFileName);

            if (string.IsNullOrEmpty(embeddedFileName))
            {
                embeddedFileName = FileUtilities.FixFilePath(fileName);
            }

            dependentUponFileName = FileUtilities.FixFilePath(dependentUponFileName);
            Culture.ItemCultureInfo info = Culture.GetItemCultureInfo(embeddedFileName, dependentUponFileName, treatAsCultureNeutral);

            // If the item has a culture override, respect that.
            if (!string.IsNullOrEmpty(culture))
            {
                info.culture = culture;
            }

            var manifestName = StringBuilderCache.Acquire();

            if (binaryStream != null)
            {
                // Resource depends on a form. Now, get the form's class name fully
                // qualified with a namespace.
                ExtractedClassName result = CSharpParserUtilities.GetFirstClassNameFullyQualified(binaryStream);

                if (result.IsInsideConditionalBlock)
                {
                    log?.LogWarningWithCodeFromResources("CreateManifestResourceName.DefinitionFoundWithinConditionalDirective", dependentUponFileName, embeddedFileName);
                }

                if (!string.IsNullOrEmpty(result.Name))
                {
                    manifestName.Append(result.Name);

                    // Append the culture if there is one.
                    if (!string.IsNullOrEmpty(info.culture))
                    {
                        manifestName.Append('.').Append(info.culture);
                    }
                }
            }

            // If there's no manifest name at this point, then fall back to using the
            // RootNamespace+Filename_with_slashes_converted_to_dots
            if (manifestName.Length == 0)
            {
                // If Rootnamespace was null, then it wasn't set from the project resourceFile.
                // Empty namespaces are allowed.
                if (!string.IsNullOrEmpty(rootNamespace))
                {
                    manifestName.Append(rootNamespace).Append('.');
                }

                // only strip extension for .resx and .restext files
                string sourceExtension = Path.GetExtension(info.cultureNeutralFilename);
                string directoryName   = Path.GetDirectoryName(info.cultureNeutralFilename);

                // append the directory name
                manifestName.Append(MakeValidEverettIdentifier(directoryName));
                if (
                    string.Equals(sourceExtension, resxFileExtension, StringComparison.OrdinalIgnoreCase)
                    ||
                    string.Equals(sourceExtension, restextFileExtension, StringComparison.OrdinalIgnoreCase)
                    ||
                    string.Equals(sourceExtension, resourcesFileExtension, StringComparison.OrdinalIgnoreCase)
                    )
                {
                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        manifestName.Append('.');
                    }

                    // append the file name without extension
                    manifestName.Append(Path.GetFileNameWithoutExtension(info.cultureNeutralFilename));

                    // Replace all '\' with '.'
                    manifestName.Replace(Path.DirectorySeparatorChar, '.');
                    manifestName.Replace(Path.AltDirectorySeparatorChar, '.');

                    // Append the culture if there is one.
                    if (!string.IsNullOrEmpty(info.culture))
                    {
                        manifestName.Append('.').Append(info.culture);
                    }

                    // If the original extension was .resources, add it back
                    if (string.Equals(sourceExtension, resourcesFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        manifestName.Append(sourceExtension);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        manifestName.Append('.');
                    }

                    manifestName.Append(Path.GetFileName(info.cultureNeutralFilename));

                    // Replace all '\' with '.'
                    manifestName.Replace(Path.DirectorySeparatorChar, '.');
                    manifestName.Replace(Path.AltDirectorySeparatorChar, '.');

                    if (prependCultureAsDirectory)
                    {
                        // Prepend the culture as a subdirectory if there is one.
                        if (!string.IsNullOrEmpty(info.culture))
                        {
                            manifestName.Insert(0, Path.DirectorySeparatorChar);
                            manifestName.Insert(0, info.culture);
                        }
                    }
                }
            }

            return(StringBuilderCache.GetStringAndRelease(manifestName));
        }
            // For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
            // the constants guaranteed to include DHMSF ordered greatest to least significant.
            // Once the data becomes more complex than this we will need to write a proper tokenizer for
            // parsing and formatting
            internal void Init(ReadOnlySpan <char> format, bool useInvariantFieldLengths)
            {
                dd        = hh = mm = ss = ff = 0;
                _literals = new string[6];
                for (int i = 0; i < _literals.Length; i++)
                {
                    _literals[i] = string.Empty;
                }

                StringBuilder sb      = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
                bool          inQuote = false;
                char          quote   = '\'';
                int           field   = 0;

                for (int i = 0; i < format.Length; i++)
                {
                    switch (format[i])
                    {
                    case '\'':
                    case '\"':
                        if (inQuote && (quote == format[i]))
                        {
                            /* we were in a quote and found a matching exit quote, so we are outside a quote now */
                            if (field >= 0 && field <= 5)
                            {
                                _literals[field] = sb.ToString();
                                sb.Length        = 0;
                                inQuote          = false;
                            }
                            else
                            {
                                Debug.Fail($"Unexpected field value: {field}");
                                return;     // how did we get here?
                            }
                        }
                        else if (!inQuote)
                        {
                            /* we are at the start of a new quote block */
                            quote   = format[i];
                            inQuote = true;
                        }
                        else
                        {
                            /* we were in a quote and saw the other type of quote character, so we are still in a quote */
                        }
                        break;

                    case '%':
                        Debug.Fail("Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                        goto default;

                    case '\\':
                        if (!inQuote)
                        {
                            i++;     /* skip next character that is escaped by this backslash or percent sign */
                            break;
                        }
                        goto default;

                    case 'd':
                        if (!inQuote)
                        {
                            Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                            field = 1;     // DayHourSep
                            dd++;
                        }
                        break;

                    case 'h':
                        if (!inQuote)
                        {
                            Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                            field = 2;     // HourMinuteSep
                            hh++;
                        }
                        break;

                    case 'm':
                        if (!inQuote)
                        {
                            Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                            field = 3;     // MinuteSecondSep
                            mm++;
                        }
                        break;

                    case 's':
                        if (!inQuote)
                        {
                            Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                            field = 4;     // SecondFractionSep
                            ss++;
                        }
                        break;

                    case 'f':
                    case 'F':
                        if (!inQuote)
                        {
                            Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                            field = 5;     // End
                            ff++;
                        }
                        break;

                    default:
                        sb.Append(format[i]);
                        break;
                    }
                }

                Debug.Assert(field == 5);
                AppCompatLiteral = MinuteSecondSep + SecondFractionSep;

                Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");

                if (useInvariantFieldLengths)
                {
                    dd = 2;
                    hh = 2;
                    mm = 2;
                    ss = 2;
                    ff = DateTimeFormat.MaxSecondsFractionDigits;
                }
                else
                {
                    if (dd < 1 || dd > 2)
                    {
                        dd = 2;                     // The DTFI property has a problem. let's try to make the best of the situation.
                    }
                    if (hh < 1 || hh > 2)
                    {
                        hh = 2;
                    }
                    if (mm < 1 || mm > 2)
                    {
                        mm = 2;
                    }
                    if (ss < 1 || ss > 2)
                    {
                        ss = 2;
                    }
                    if (ff < 1 || ff > 7)
                    {
                        ff = 7;
                    }
                }
                StringBuilderCache.Release(sb);
            }
        public override string ToString()
        {
            StringBuilder sb = StringBuilderCache.Acquire();

            AppendValueIfRequired(sb, _noStore, noStoreString);
            AppendValueIfRequired(sb, _noTransform, noTransformString);
            AppendValueIfRequired(sb, _onlyIfCached, onlyIfCachedString);
            AppendValueIfRequired(sb, _publicField, publicString);
            AppendValueIfRequired(sb, _mustRevalidate, mustRevalidateString);
            AppendValueIfRequired(sb, _proxyRevalidate, proxyRevalidateString);

            if (_noCache)
            {
                AppendValueWithSeparatorIfRequired(sb, noCacheString);
                if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0))
                {
                    sb.Append("=\"");
                    AppendValues(sb, _noCacheHeaders);
                    sb.Append('\"');
                }
            }

            if (_maxAge.HasValue)
            {
                AppendValueWithSeparatorIfRequired(sb, maxAgeString);
                sb.Append('=');
                int maxAge = (int)_maxAge.GetValueOrDefault().TotalSeconds;
                if (maxAge >= 0)
                {
                    sb.Append(maxAge);
                }
                else
                {
                    // In the corner case where the value is negative, ensure it uses
                    // the invariant's negative sign rather than the current culture's.
                    sb.Append(maxAge.ToString(NumberFormatInfo.InvariantInfo));
                }
            }

            if (_sharedMaxAge.HasValue)
            {
                AppendValueWithSeparatorIfRequired(sb, sharedMaxAgeString);
                sb.Append('=');
                int sharedMaxAge = (int)_sharedMaxAge.GetValueOrDefault().TotalSeconds;
                if (sharedMaxAge >= 0)
                {
                    sb.Append(sharedMaxAge);
                }
                else
                {
                    // In the corner case where the value is negative, ensure it uses
                    // the invariant's negative sign rather than the current culture's.
                    sb.Append(sharedMaxAge.ToString(NumberFormatInfo.InvariantInfo));
                }
            }

            if (_maxStale)
            {
                AppendValueWithSeparatorIfRequired(sb, maxStaleString);
                if (_maxStaleLimit.HasValue)
                {
                    sb.Append('=');
                    int maxStaleLimit = (int)_maxStaleLimit.GetValueOrDefault().TotalSeconds;
                    if (maxStaleLimit >= 0)
                    {
                        sb.Append(maxStaleLimit);
                    }
                    else
                    {
                        // In the corner case where the value is negative, ensure it uses
                        // the invariant's negative sign rather than the current culture's.
                        sb.Append(maxStaleLimit.ToString(NumberFormatInfo.InvariantInfo));
                    }
                }
            }

            if (_minFresh.HasValue)
            {
                AppendValueWithSeparatorIfRequired(sb, minFreshString);
                sb.Append('=');
                int minFresh = (int)_minFresh.GetValueOrDefault().TotalSeconds;
                if (minFresh >= 0)
                {
                    sb.Append(minFresh);
                }
                else
                {
                    // In the corner case where the value is negative, ensure it uses
                    // the invariant's negative sign rather than the current culture's.
                    sb.Append(minFresh.ToString(NumberFormatInfo.InvariantInfo));
                }
            }

            if (_privateField)
            {
                AppendValueWithSeparatorIfRequired(sb, privateString);
                if ((_privateHeaders != null) && (_privateHeaders.Count > 0))
                {
                    sb.Append("=\"");
                    AppendValues(sb, _privateHeaders);
                    sb.Append('\"');
                }
            }

            NameValueHeaderValue.ToString(_extensions, ',', false, sb);

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #19
0
        /// <summary>
        /// The ICU date format characters are not exactly the same as the .NET date format characters.
        /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern.
        /// </summary>
        /// <remarks>
        /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime
        /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
        /// </remarks>
        private static string NormalizeDatePattern(string input)
        {
            StringBuilder destination = StringBuilderCache.Acquire(input.Length);

            int index = 0;

            while (index < input.Length)
            {
                switch (input[index])
                {
                case '\'':
                    // single quotes escape characters, like 'de' in es-SP
                    // so read verbatim until the next single quote
                    destination.Append(input[index++]);
                    while (index < input.Length)
                    {
                        char current = input[index++];
                        destination.Append(current);
                        if (current == '\'')
                        {
                            break;
                        }
                    }
                    break;

                case 'E':
                case 'e':
                case 'c':
                    // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET
                    // 'e' in ICU is the local day of the week, which has no representation in .NET, but
                    // maps closest to 3 or 4 'd's in .NET
                    // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but
                    // maps closest to 3 or 4 'd's in .NET
                    NormalizeDayOfWeek(input, destination, ref index);
                    break;

                case 'L':
                case 'M':
                    // 'L' in ICU is the stand-alone name of the month,
                    // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns
                    // 'M' in both ICU and .NET is the month,
                    // but ICU supports 5 'M's, which is the super short month name
                    int occurrences = CountOccurrences(input, input[index], ref index);
                    if (occurrences > 4)
                    {
                        // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET
                        occurrences = 3;
                    }
                    destination.Append('M', occurrences);
                    break;

                case 'G':
                    // 'G' in ICU is the era, which maps to 'g' in .NET
                    occurrences = CountOccurrences(input, 'G', ref index);

                    // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they
                    // have the same meaning
                    destination.Append('g');
                    break;

                case 'y':
                    // a single 'y' in ICU is the year with no padding or trimming.
                    // a single 'y' in .NET is the year with 1 or 2 digits
                    // so convert any single 'y' to 'yyyy'
                    occurrences = CountOccurrences(input, 'y', ref index);
                    if (occurrences == 1)
                    {
                        occurrences = 4;
                    }
                    destination.Append('y', occurrences);
                    break;

                default:
                    const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
                    Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
                                 string.Format(CultureInfo.InvariantCulture,
                                               "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
                                               input[index]));

                    destination.Append(input[index++]);
                    break;
                }
            }

            return(StringBuilderCache.GetStringAndRelease(destination));
        }
Beispiel #20
0
        //
        //  FormatStandard
        //
        //  Actions: Format the TimeSpan instance using the specified format.
        //
        private static String FormatStandard(TimeSpan value, bool isInvariant, String format, Pattern pattern)
        {
            StringBuilder sb   = StringBuilderCache.Acquire();
            int           day  = (int)(value._ticks / TimeSpan.TicksPerDay);
            long          time = value._ticks % TimeSpan.TicksPerDay;

            if (value._ticks < 0)
            {
                day  = -day;
                time = -time;
            }
            int hours    = (int)(time / TimeSpan.TicksPerHour % 24);
            int minutes  = (int)(time / TimeSpan.TicksPerMinute % 60);
            int seconds  = (int)(time / TimeSpan.TicksPerSecond % 60);
            int fraction = (int)(time % TimeSpan.TicksPerSecond);

            FormatLiterals literal;

            if (isInvariant)
            {
                if (value._ticks < 0)
                {
                    literal = NegativeInvariantFormatLiterals;
                }
                else
                {
                    literal = PositiveInvariantFormatLiterals;
                }
            }
            else
            {
                literal = new FormatLiterals();
                literal.Init(format, pattern == Pattern.Full);
            }
            if (fraction != 0)   // truncate the partial second to the specified length
            {
                fraction = (int)((long)fraction / (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
            }

            // Pattern.Full: [-]dd.hh:mm:ss.fffffff
            // Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff]

            sb.Append(literal.Start);                           // [-]
            if (pattern == Pattern.Full || day != 0)            //
            {
                sb.Append(day);                                 // [dd]
                sb.Append(literal.DayHourSep);                  // [.]
            }                                                   //
            sb.Append(IntToString(hours, literal.hh));          // hh
            sb.Append(literal.HourMinuteSep);                   // :
            sb.Append(IntToString(minutes, literal.mm));        // mm
            sb.Append(literal.MinuteSecondSep);                 // :
            sb.Append(IntToString(seconds, literal.ss));        // ss
            if (!isInvariant && pattern == Pattern.Minimum)
            {
                int effectiveDigits = literal.ff;
                while (effectiveDigits > 0)
                {
                    if (fraction % 10 == 0)
                    {
                        fraction = fraction / 10;
                        effectiveDigits--;
                    }
                    else
                    {
                        break;
                    }
                }
                if (effectiveDigits > 0)
                {
                    sb.Append(literal.SecondFractionSep);           // [.FFFFFFF]
                    sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
                }
            }
            else if (pattern == Pattern.Full || fraction != 0)
            {
                sb.Append(literal.SecondFractionSep);           // [.]
                sb.Append(IntToString(fraction, literal.ff));   // [fffffff]
            }                                                   //
            sb.Append(literal.End);                             //

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #21
0
    static void GenMessageParse(google.protobuf.DescriptorProto message)
    {
        StringBuilder builder = StringBuilderCache.Acquire(4096);

        builder.Append(
            @"
    public void Parse(ProtoBuf.ProtoReader source){
        int fieldNumber = 0;
        while ((fieldNumber = source.ReadFieldHeader()) > 0)
        {
            switch (fieldNumber)
            {
                default:
                    source.SkipField();
                    break;
            
    ");
        foreach (var field in message.field)
        {
            /*builder.AppendFormat(
             *  @"
             *          case {0}:",field.number);
             */
            builder.AppendFormat(@"
            case {0}:   //{1} {2} {3} {4} {5}
                ", field.number, field.name, field.label, field.type, field.type_name, GetDataFromat(field.type));
            if (field.label == google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED)
            {
                /*if (field.type == google.protobuf.FieldDescriptorProto.Type.TYPE_STRING)
                 * {
                 *  builder.AppendFormat(@"
                 *  SubItemToken {0}token = ProtoReader.StartSubItem(source);
                 *  while (ProtoReader.HasSubValue(WireType.String, source))
                 *  {{
                 *      {0}.Add({1});
                 *  }}
                 *  ProtoReader.EndSubItem({0}token, source);
                 *  break;
                 *  ",field.name,
                 *  GetFieldParseByType(field.type, field.type_name));
                 * }
                 * else */
                {
                    if (field.type == google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE)
                    {
                        builder.AppendFormat(
                            @"    int {1}field = source.FieldNumber;
                    do
                    {{
                        {0} {1}temp = new {0}();
                        ProtoBuf.SubItemToken {1}token = ProtoBuf.ProtoReader.StartSubItem(source); 
                        {1}temp.Parse(source);
                        ProtoBuf.ProtoReader.EndSubItem({1}token, source);
                        {1}.Add({1}temp);
                    }} while (source.TryReadFieldHeader({1}field));
                    break;
                    ", field.type_name.Substring(1), field.name);
                    }
                    else
                    {
                        string temp       = GetFieldParseByType(field.type, field.type_name);
                        var    wiretype   = TryGetWireType(field.type);
                        bool   bNeedsHint = NeedsHint(wiretype);
                        if (bNeedsHint)
                        {
                            builder.AppendFormat(
                                @"    int {0}field = source.FieldNumber;
                    do{{
                        source.Hint(ProtoBuf.WireType.{2}); 
                        {0}.Add({1});
                    }} while(source.TryReadFieldHeader({0}field));
                    break;
                    ", field.name,
                                temp, wiretype);
                        }
                        else
                        {
                            builder.AppendFormat(
                                @"    int {0}field = source.FieldNumber;
                    do{{
                        {0}.Add({1});
                    }} while(source.TryReadFieldHeader({0}field));
                    break;
                    ", field.name, temp);
                        }
                    }
                }
            }
            else
            {
                if (field.type == google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE)
                {
                    builder.AppendFormat(@"    {0} = new {1}();", field.name, field.type_name.Substring(1));
                    builder.AppendFormat(@"
                    ProtoBuf.SubItemToken {0}token = ProtoBuf.ProtoReader.StartSubItem(source); 
                    {0}.Parse(source);
                    ProtoBuf.ProtoReader.EndSubItem({0}token, source);
                    break;
                    ", field.name);
                }
                else
                {
                    var  wiretype   = TryGetWireType(field.type);
                    bool bNeedsHint = NeedsHint(wiretype);
                    if (bNeedsHint)
                    {
                        builder.AppendFormat(
                            @"    source.Hint(ProtoBuf.WireType.{2}); 
                    {0} = {1};
                    break;
                    ", field.name,
                            GetFieldParseByType(field.type, field.type_name), wiretype);
                    }
                    else
                    {
                        builder.AppendFormat(
                            @"    {0} = {1};
                    break;
                    ", field.name,
                            GetFieldParseByType(field.type, field.type_name));
                    }
                }
            }
        }

        builder.Append(@"
            }
        }
    }");
        message.ParseCode = builder.ToString();
        foreach (var nestMsg in message.nested_type)
        {
            GenMessageParse(nestMsg);
        }

        StringBuilderCache.Release(builder);
    }
            //
            //  FormatCustomized
            //
            //  Actions: Format the TimeSpan instance using the specified format.
            //
            internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi)
            {
                int  day  = (int)(value.Ticks / TimeSpan.TicksPerDay);
                long time = value.Ticks % TimeSpan.TicksPerDay;

                if (value.Ticks < 0)
                {
                    day  = -day;
                    time = -time;
                }
                int hours    = (int)(time / TimeSpan.TicksPerHour % 24);
                int minutes  = (int)(time / TimeSpan.TicksPerMinute % 60);
                int seconds  = (int)(time / TimeSpan.TicksPerSecond % 60);
                int fraction = (int)(time % TimeSpan.TicksPerSecond);

                long          tmp = 0;
                int           i   = 0;
                int           tokenLen;
                StringBuilder result = StringBuilderCache.Acquire(InternalGloablizationHelper.StringBuilderDefaultCapacity);

                while (i < format.Length)
                {
                    char ch = format[i];
                    int  nextChar;
                    switch (ch)
                    {
                    case 'h':
                        tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                        if (tokenLen > 2)
                        {
                            throw new FormatException(SR.Format_InvalidString);
                        }
                        DateTimeFormat.FormatDigits(result, hours, tokenLen);
                        break;

                    case 'm':
                        tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                        if (tokenLen > 2)
                        {
                            throw new FormatException(SR.Format_InvalidString);
                        }
                        DateTimeFormat.FormatDigits(result, minutes, tokenLen);
                        break;

                    case 's':
                        tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                        if (tokenLen > 2)
                        {
                            throw new FormatException(SR.Format_InvalidString);
                        }
                        DateTimeFormat.FormatDigits(result, seconds, tokenLen);
                        break;

                    case 'f':
                        //
                        // The fraction of a second in single-digit precision. The remaining digits are truncated.
                        //
                        tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                        if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
                        {
                            throw new FormatException(SR.Format_InvalidString);
                        }

                        tmp  = (long)fraction;
                        tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
                        result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
                        break;

                    case 'F':
                        //
                        // Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
                        //
                        tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                        if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
                        {
                            throw new FormatException(SR.Format_InvalidString);
                        }

                        tmp  = (long)fraction;
                        tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
                        int effectiveDigits = tokenLen;
                        while (effectiveDigits > 0)
                        {
                            if (tmp % 10 == 0)
                            {
                                tmp = tmp / 10;
                                effectiveDigits--;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (effectiveDigits > 0)
                        {
                            result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
                        }
                        break;

                    case 'd':
                        //
                        // tokenLen == 1 : Day as digits with no leading zero.
                        // tokenLen == 2+: Day as digits with leading zero for single-digit days.
                        //
                        tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
                        if (tokenLen > 8)
                        {
                            throw new FormatException(SR.Format_InvalidString);
                        }
                        DateTimeFormat.FormatDigits(result, day, tokenLen, true);
                        break;

                    case '\'':
                    case '\"':
                        tokenLen = DateTimeFormat.ParseQuoteString(format, i);
                        result.Append(format, i + 1, tokenLen - 2);
                        break;

                    case '%':
                        // Optional format character.
                        // For example, format string "%d" will print day
                        // Most of the cases, "%" can be ignored.
                        nextChar = DateTimeFormat.ParseNextChar(format, i);
                        // nextChar will be -1 if we already reach the end of the format string.
                        // Besides, we will not allow "%%" appear in the pattern.
                        if (nextChar >= 0 && nextChar != (int)'%')
                        {
                            result.Append(TimeSpanFormat.FormatCustomized(value, ((char)nextChar).ToString(), dtfi));
                            tokenLen = 2;
                        }
                        else
                        {
                            //
                            // This means that '%' is at the end of the format string or
                            // "%%" appears in the format string.
                            //
                            throw new FormatException(SR.Format_InvalidString);
                        }
                        break;

                    case '\\':
                        // Escaped character.  Can be used to insert character into the format string.
                        // For example, "\d" will insert the character 'd' into the string.
                        //
                        nextChar = DateTimeFormat.ParseNextChar(format, i);
                        if (nextChar >= 0)
                        {
                            result.Append(((char)nextChar));
                            tokenLen = 2;
                        }
                        else
                        {
                            //
                            // This means that '\' is at the end of the formatting string.
                            //
                            throw new FormatException(SR.Format_InvalidString);
                        }
                        break;

                    default:
                        throw new FormatException(SR.Format_InvalidString);
                    }
                    i += tokenLen;
                }
                return(StringBuilderCache.GetStringAndRelease(result));
            }
Beispiel #23
0
        private static string GetNextArgument(string arguments, ref int i)
        {
            var  currentArgument = StringBuilderCache.Acquire();
            bool inQuotes        = false;

            while (i < arguments.Length)
            {
                // From the current position, iterate through contiguous backslashes.
                int backslashCount = 0;
                while (i < arguments.Length && arguments[i] == '\\')
                {
                    i++;
                    backslashCount++;
                }

                if (backslashCount > 0)
                {
                    if (i >= arguments.Length || arguments[i] != '"')
                    {
                        // Backslashes not followed by a double quote:
                        // they should all be treated as literal backslashes.
                        currentArgument.Append('\\', backslashCount);
                    }
                    else
                    {
                        // Backslashes followed by a double quote:
                        // - Output a literal slash for each complete pair of slashes
                        // - If one remains, use it to make the subsequent quote a literal.
                        currentArgument.Append('\\', backslashCount / 2);
                        if (backslashCount % 2 != 0)
                        {
                            currentArgument.Append('"');
                            i++;
                        }
                    }

                    continue;
                }

                char c = arguments[i];

                // If this is a double quote, track whether we're inside of quotes or not.
                // Anything within quotes will be treated as a single argument, even if
                // it contains spaces.
                if (c == '"')
                {
                    if (inQuotes && i < arguments.Length - 1 && arguments[i + 1] == '"')
                    {
                        // Two consecutive double quotes inside an inQuotes region should result in a literal double quote
                        // (the parser is left in the inQuotes region).
                        // This behavior is not part of the spec of code:ParseArgumentsIntoList, but is compatible with CRT
                        // and .NET Framework.
                        currentArgument.Append('"');
                        i++;
                    }
                    else
                    {
                        inQuotes = !inQuotes;
                    }

                    i++;
                    continue;
                }

                // If this is a space/tab and we're not in quotes, we're done with the current
                // argument, it should be added to the results and then reset for the next one.
                if ((c == ' ' || c == '\t') && !inQuotes)
                {
                    break;
                }

                // Nothing special; add the character to the current argument.
                currentArgument.Append(c);
                i++;
            }

            return(StringBuilderCache.GetStringAndRelease(currentArgument));
        }
                // For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
                // the constants guaranteed to include DHMSF ordered greatest to least significant.
                // Once the data becomes more complex than this we will need to write a proper tokenizer for
                // parsing and formatting
                internal void Init(String format, bool useInvariantFieldLengths)
                {
                    _literals = new String[6];
                    for (int i = 0; i < _literals.Length; i++)
                    {
                        _literals[i] = String.Empty;
                    }
                    dd = 0;
                    hh = 0;
                    mm = 0;
                    ss = 0;
                    ff = 0;

                    StringBuilder sb      = StringBuilderCache.Acquire(InternalGloablizationHelper.StringBuilderDefaultCapacity);
                    bool          inQuote = false;
                    char          quote   = '\'';
                    int           field   = 0;

                    for (int i = 0; i < format.Length; i++)
                    {
                        switch (format[i])
                        {
                        case '\'':
                        case '\"':
                            if (inQuote && (quote == format[i]))
                            {
                                if (field >= 0 && field <= 5)
                                {
                                    _literals[field] = sb.ToString();
                                    sb.Length        = 0;
                                    inQuote          = false;
                                }
                                else
                                {
                                    return;     // how did we get here?
                                }
                            }
                            else if (!inQuote)
                            {
                                /* we are at the start of a new quote block */
                                quote   = format[i];
                                inQuote = true;
                            }
                            else
                            {
                                /* we were in a quote and saw the other type of quote character, so we are still in a quote */
                            }
                            break;

                        case '%':
                            goto default;

                        case '\\':
                            if (!inQuote)
                            {
                                i++;     /* skip next character that is escaped by this backslash or percent sign */
                                break;
                            }
                            goto default;

                        case 'd':
                            if (!inQuote)
                            {
                                field = 1;     // DayHourSep
                                dd++;
                            }
                            break;

                        case 'h':
                            if (!inQuote)
                            {
                                field = 2;     // HourMinuteSep
                                hh++;
                            }
                            break;

                        case 'm':
                            if (!inQuote)
                            {
                                field = 3;     // MinuteSecondSep
                                mm++;
                            }
                            break;

                        case 's':
                            if (!inQuote)
                            {
                                field = 4;     // SecondFractionSep
                                ss++;
                            }
                            break;

                        case 'f':
                        case 'F':
                            if (!inQuote)
                            {
                                field = 5;     // End
                                ff++;
                            }
                            break;

                        default:
                            sb.Append(format[i]);
                            break;
                        }
                    }
                    AppCompatLiteral = MinuteSecondSep + SecondFractionSep;

                    if (useInvariantFieldLengths)
                    {
                        dd = 2;
                        hh = 2;
                        mm = 2;
                        ss = 2;
                        ff = DateTimeFormat.MaxSecondsFractionDigits;
                    }
                    else
                    {
                        if (dd < 1 || dd > 2)
                        {
                            dd = 2;                     // The DTFI property has a problem. let's try to make the best of the situation.
                        }
                        if (hh < 1 || hh > 2)
                        {
                            hh = 2;
                        }
                        if (mm < 1 || mm > 2)
                        {
                            mm = 2;
                        }
                        if (ss < 1 || ss > 2)
                        {
                            ss = 2;
                        }
                        if (ff < 1 || ff > 7)
                        {
                            ff = 7;
                        }
                    }
                    StringBuilderCache.Release(sb);
                }
Beispiel #25
0
            private string GetNextValue(string data, int currentIndex, bool expectQuotes, out int parsedIndex)
            {
                Debug.Assert(currentIndex < data.Length && !CharIsSpaceOrTab(data[currentIndex]));

                // If quoted value, skip first quote.
                bool quotedValue = false;

                if (data[currentIndex] == '"')
                {
                    quotedValue = true;
                    currentIndex++;
                }

                if (expectQuotes && !quotedValue)
                {
                    parsedIndex = currentIndex;
                    return(null);
                }

                StringBuilder sb = StringBuilderCache.Acquire();

                while (currentIndex < data.Length && ((quotedValue && data[currentIndex] != '"') || (!quotedValue && data[currentIndex] != ',')))
                {
                    sb.Append(data[currentIndex]);
                    currentIndex++;

                    if (currentIndex == data.Length)
                    {
                        break;
                    }

                    if (!quotedValue && CharIsSpaceOrTab(data[currentIndex]))
                    {
                        break;
                    }

                    if (quotedValue && data[currentIndex] == '"' && data[currentIndex - 1] == '\\')
                    {
                        // Include the escaped quote.
                        sb.Append(data[currentIndex]);
                        currentIndex++;
                    }
                }

                // Skip the quote.
                if (quotedValue)
                {
                    currentIndex++;
                }

                // Skip any whitespace.
                while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
                {
                    currentIndex++;
                }

                // Return if this is last value.
                if (currentIndex == data.Length)
                {
                    parsedIndex = currentIndex;
                    return(StringBuilderCache.GetStringAndRelease(sb));
                }

                // A key-value pair should end with ','
                if (data[currentIndex++] != ',')
                {
                    parsedIndex = currentIndex;
                    return(null);
                }

                // Skip space and tab
                while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
                {
                    currentIndex++;
                }

                // Set parsedIndex to current valid char.
                parsedIndex = currentIndex;
                return(StringBuilderCache.GetStringAndRelease(sb));
            }
        public override string ToString()
        {
            StringBuilder sb = StringBuilderCache.Acquire();

            AppendValueIfRequired(sb, _noStore, noStoreString);
            AppendValueIfRequired(sb, _noTransform, noTransformString);
            AppendValueIfRequired(sb, _onlyIfCached, onlyIfCachedString);
            AppendValueIfRequired(sb, _publicField, publicString);
            AppendValueIfRequired(sb, _mustRevalidate, mustRevalidateString);
            AppendValueIfRequired(sb, _proxyRevalidate, proxyRevalidateString);

            if (_noCache)
            {
                AppendValueWithSeparatorIfRequired(sb, noCacheString);
                if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0))
                {
                    sb.Append("=\"");
                    AppendValues(sb, _noCacheHeaders);
                    sb.Append('\"');
                }
            }

            if (_maxAge.HasValue)
            {
                AppendValueWithSeparatorIfRequired(sb, maxAgeString);
                sb.Append('=');
                sb.Append((int)_maxAge.Value.TotalSeconds);
            }

            if (_sharedMaxAge.HasValue)
            {
                AppendValueWithSeparatorIfRequired(sb, sharedMaxAgeString);
                sb.Append('=');
                sb.Append((int)_sharedMaxAge.Value.TotalSeconds);
            }

            if (_maxStale)
            {
                AppendValueWithSeparatorIfRequired(sb, maxStaleString);
                if (_maxStaleLimit.HasValue)
                {
                    sb.Append('=');
                    sb.Append((int)_maxStaleLimit.Value.TotalSeconds);
                }
            }

            if (_minFresh.HasValue)
            {
                AppendValueWithSeparatorIfRequired(sb, minFreshString);
                sb.Append('=');
                sb.Append((int)_minFresh.Value.TotalSeconds);
            }

            if (_privateField)
            {
                AppendValueWithSeparatorIfRequired(sb, privateString);
                if ((_privateHeaders != null) && (_privateHeaders.Count > 0))
                {
                    sb.Append("=\"");
                    AppendValues(sb, _privateHeaders);
                    sb.Append('\"');
                }
            }

            NameValueHeaderValue.ToString(_extensions, ',', false, sb);

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #27
0
        public string GetJsonString()
        {
            var sb         = StringBuilderCache.Acquire();
            var jsonObject = new JsonObject(sb);

            jsonObject.AddIntValue("coverage", Coverage);
            jsonObject.AddStringValue("allAf", ComputingUtilities.ComputeFrequency(AllAlleleNumber, AllAlleleCount), false);
            jsonObject.AddStringValue("afrAf", ComputingUtilities.ComputeFrequency(AfrAlleleNumber, AfrAlleleCount), false);
            jsonObject.AddStringValue("amrAf", ComputingUtilities.ComputeFrequency(AmrAlleleNumber, AmrAlleleCount), false);
            jsonObject.AddStringValue("easAf", ComputingUtilities.ComputeFrequency(EasAlleleNumber, EasAlleleCount), false);
            jsonObject.AddStringValue("finAf", ComputingUtilities.ComputeFrequency(FinAlleleNumber, FinAlleleCount), false);
            jsonObject.AddStringValue("nfeAf", ComputingUtilities.ComputeFrequency(NfeAlleleNumber, NfeAlleleCount), false);
            jsonObject.AddStringValue("sasAf", ComputingUtilities.ComputeFrequency(SasAlleleNumber, SasAlleleCount), false);
            jsonObject.AddStringValue("othAf", ComputingUtilities.ComputeFrequency(OthAlleleNumber, OthAlleleCount), false);

            if (AllAlleleNumber != null)
            {
                jsonObject.AddIntValue("allAn", AllAlleleNumber.Value);
            }
            if (AfrAlleleNumber != null)
            {
                jsonObject.AddIntValue("afrAn", AfrAlleleNumber.Value);
            }
            if (AmrAlleleNumber != null)
            {
                jsonObject.AddIntValue("amrAn", AmrAlleleNumber.Value);
            }
            if (EasAlleleNumber != null)
            {
                jsonObject.AddIntValue("easAn", EasAlleleNumber.Value);
            }
            if (FinAlleleNumber != null)
            {
                jsonObject.AddIntValue("finAn", FinAlleleNumber.Value);
            }
            if (NfeAlleleNumber != null)
            {
                jsonObject.AddIntValue("nfeAn", NfeAlleleNumber.Value);
            }
            if (SasAlleleNumber != null)
            {
                jsonObject.AddIntValue("sasAn", SasAlleleNumber.Value);
            }
            if (OthAlleleNumber != null)
            {
                jsonObject.AddIntValue("othAn", OthAlleleNumber.Value);
            }

            if (AllAlleleCount != null)
            {
                jsonObject.AddIntValue("allAc", AllAlleleCount.Value);
            }
            if (AfrAlleleCount != null)
            {
                jsonObject.AddIntValue("afrAc", AfrAlleleCount.Value);
            }
            if (AmrAlleleCount != null)
            {
                jsonObject.AddIntValue("amrAc", AmrAlleleCount.Value);
            }
            if (EasAlleleCount != null)
            {
                jsonObject.AddIntValue("easAc", EasAlleleCount.Value);
            }
            if (FinAlleleCount != null)
            {
                jsonObject.AddIntValue("finAc", FinAlleleCount.Value);
            }
            if (NfeAlleleCount != null)
            {
                jsonObject.AddIntValue("nfeAc", NfeAlleleCount.Value);
            }
            if (SasAlleleCount != null)
            {
                jsonObject.AddIntValue("sasAc", SasAlleleCount.Value);
            }
            if (OthAlleleCount != null)
            {
                jsonObject.AddIntValue("othAc", OthAlleleCount.Value);
            }

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
        /// <summary>Format the TimeSpan instance using the specified format.</summary>
        private static StringBuilder FormatStandard(TimeSpan value, bool isInvariant, ReadOnlySpan <char> format, Pattern pattern)
        {
            StringBuilder sb   = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
            int           day  = (int)(value.Ticks / TimeSpan.TicksPerDay);
            long          time = value.Ticks % TimeSpan.TicksPerDay;

            if (value.Ticks < 0)
            {
                day  = -day;
                time = -time;
            }
            int hours    = (int)(time / TimeSpan.TicksPerHour % 24);
            int minutes  = (int)(time / TimeSpan.TicksPerMinute % 60);
            int seconds  = (int)(time / TimeSpan.TicksPerSecond % 60);
            int fraction = (int)(time % TimeSpan.TicksPerSecond);

            FormatLiterals literal;

            if (isInvariant)
            {
                literal = value.Ticks < 0 ?
                          NegativeInvariantFormatLiterals :
                          PositiveInvariantFormatLiterals;
            }
            else
            {
                literal = new FormatLiterals();
                literal.Init(format, pattern == Pattern.Full);
            }

            if (fraction != 0)
            {
                // truncate the partial second to the specified length
                fraction = (int)(fraction / TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
            }

            // Pattern.Full: [-]dd.hh:mm:ss.fffffff
            // Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff]

            sb.Append(literal.Start);                           // [-]
            if (pattern == Pattern.Full || day != 0)
            {
                sb.Append(day);                                 // [dd]
                sb.Append(literal.DayHourSep);                  // [.]
            }                                                   //
            AppendNonNegativeInt32(sb, hours, literal.hh);      // hh
            sb.Append(literal.HourMinuteSep);                   // :
            AppendNonNegativeInt32(sb, minutes, literal.mm);    // mm
            sb.Append(literal.MinuteSecondSep);                 // :
            AppendNonNegativeInt32(sb, seconds, literal.ss);    // ss
            if (!isInvariant && pattern == Pattern.Minimum)
            {
                int effectiveDigits = literal.ff;
                while (effectiveDigits > 0)
                {
                    if (fraction % 10 == 0)
                    {
                        fraction = fraction / 10;
                        effectiveDigits--;
                    }
                    else
                    {
                        break;
                    }
                }
                if (effectiveDigits > 0)
                {
                    sb.Append(literal.SecondFractionSep);           // [.FFFFFFF]
                    sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
                }
            }
            else if (pattern == Pattern.Full || fraction != 0)
            {
                sb.Append(literal.SecondFractionSep);             // [.]
                AppendNonNegativeInt32(sb, fraction, literal.ff); // [fffffff]
            }
            sb.Append(literal.End);

            return(sb);
        }
Beispiel #29
0
 /// <summary>Creates an instance of the handler..</summary>
 /// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
 /// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
 /// <param name="condition">The condition Boolean passed to the <see cref="Debug"/> method.</param>
 /// <param name="shouldAppend">A value indicating whether formatting should proceed.</param>
 /// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
 public WriteIfInterpolatedStringHandler(int literalLength, int formattedCount, bool condition, out bool shouldAppend)
 {
     if (condition)
     {
         // Only used in debug, but could be used on non-failure code paths, so use a cached builder.
         _stringBuilderHandler = new StringBuilder.AppendInterpolatedStringHandler(literalLength, formattedCount,
                                                                                   StringBuilderCache.Acquire(DefaultInterpolatedStringHandler.GetDefaultLength(literalLength, formattedCount)));
         shouldAppend = true;
     }
     else
     {
         _stringBuilderHandler = default;
         shouldAppend          = false;
     }
 }
Beispiel #30
0
        protected override IList <DbCommand> MakeAlterTable(EntityModel model, Design.IDesignContext ctx)
        {
            //TODO:***处理主键变更

            var tableName = model.GetSqlTableName(false, ctx);

            StringBuilder    sb;
            bool             needCommand = false;               //用于判断是否需要处理NpgsqlCommand
            List <string>    fks         = new List <string>(); //引用外键列表
            List <DbCommand> commands    = new List <DbCommand>();

            //List<DbCommand> funcCmds = new List<DbCommand>();
            //先处理表名称有没有变更,后续全部使用新名称
            if (model.IsNameChanged)
            {
                var oldTableName   = model.GetSqlTableName(true, ctx);
                var renameTableCmd = new NpgsqlCommand($"ALTER TABLE \"{oldTableName}\" RENAME TO \"{tableName}\"");
                commands.Add(renameTableCmd);
            }

            //处理删除的成员
            var deletedMembers = model.Members.Where(t => t.PersistentState == PersistentState.Deleted).ToArray();

            if (deletedMembers != null && deletedMembers.Length > 0)
            {
                #region ----删除的成员----
                sb = StringBuilderCache.Acquire();
                foreach (var m in deletedMembers)
                {
                    if (m.Type == EntityMemberType.DataField)
                    {
                        needCommand = true;
                        sb.AppendFormat("ALTER TABLE \"{0}\" DROP COLUMN \"{1}\";", tableName, ((DataFieldModel)m).SqlColOriginalName);
                    }
                    else if (m.Type == EntityMemberType.EntityRef)
                    {
                        EntityRefModel rm = (EntityRefModel)m;
                        if (!rm.IsAggregationRef)
                        {
                            var fkName = $"FK_{rm.Owner.Id}_{rm.MemberId}"; //TODO:特殊处理DbFirst导入表的外键约束名称
                            fks.Add($"ALTER TABLE \"{tableName}\" DROP CONSTRAINT \"{fkName}\";");
                        }
                    }
                }

                var cmdText = StringBuilderCache.GetStringAndRelease(sb);
                if (needCommand)
                {
                    //加入删除的外键SQL
                    for (int i = 0; i < fks.Count; i++)
                    {
                        sb.Insert(0, fks[i]);
                        sb.AppendLine();
                    }

                    commands.Add(new NpgsqlCommand(cmdText));
                }
                #endregion
            }

            //reset
            needCommand = false;
            fks.Clear();

            //处理新增的成员
            var addedMembers = model.Members.Where(t => t.PersistentState == PersistentState.Detached).ToArray();
            if (addedMembers != null && addedMembers.Length > 0)
            {
                #region ----新增的成员----
                sb = StringBuilderCache.Acquire();
                foreach (var m in addedMembers)
                {
                    if (m.Type == EntityMemberType.DataField)
                    {
                        needCommand = true;
                        sb.AppendFormat("ALTER TABLE \"{0}\" ADD COLUMN ", tableName);
                        BuildFieldDefine((DataFieldModel)m, sb, false);
                        sb.Append(";");
                    }
                    else if (m.Type == EntityMemberType.EntityRef)
                    {
                        var rm = (EntityRefModel)m;
                        if (!rm.IsAggregationRef) //只有非聚合引合创建外键
                        {
                            fks.Add(BuildForeignKey(rm, ctx, tableName));
                            //考虑CreateGetTreeNodeChildsDbFuncCommand
                        }
                    }
                }

                var cmdText = StringBuilderCache.GetStringAndRelease(sb);
                if (needCommand)
                {
                    //加入关系
                    sb.AppendLine();
                    for (int i = 0; i < fks.Count; i++)
                    {
                        sb.AppendLine(fks[i]);
                    }

                    commands.Add(new NpgsqlCommand(cmdText));
                }
                #endregion
            }

            //reset
            needCommand = false;
            fks.Clear();

            //处理修改的成员
            var changedMembers = model.Members.Where(t => t.PersistentState == PersistentState.Modified).ToArray();
            if (changedMembers != null && changedMembers.Length > 0)
            {
                #region ----修改的成员----
                foreach (var m in changedMembers)
                {
                    if (m.Type == EntityMemberType.DataField)
                    {
                        DataFieldModel dfm = (DataFieldModel)m;
                        //先处理数据类型变更,变更类型或者变更AllowNull或者变更默认值
                        if (dfm.IsDataTypeChanged)
                        {
                            sb = StringBuilderCache.Acquire();
                            sb.AppendFormat("ALTER TABLE \"{0}\" ALTER COLUMN ", tableName);
                            string defaultValue = BuildFieldDefine(dfm, sb, true);

                            if (dfm.AllowNull)
                            {
                                sb.AppendFormat(",ALTER COLUMN \"{0}\" DROP NOT NULL", dfm.SqlColOriginalName);
                            }
                            else
                            {
                                if (dfm.DataType == EntityFieldType.Binary)
                                {
                                    throw new Exception("Binary field must be allow null");
                                }
                                sb.AppendFormat(",ALTER COLUMN \"{0}\" SET NOT NULL,ALTER COLUMN \"{0}\" SET DEFAULT {1}",
                                                dfm.SqlColOriginalName, defaultValue);
                            }

                            commands.Add(new NpgsqlCommand(StringBuilderCache.GetStringAndRelease(sb)));
                        }

                        //再处理重命名列
                        if (m.IsNameChanged)
                        {
                            var renameColCmd = new NpgsqlCommand($"ALTER TABLE \"{tableName}\" RENAME COLUMN \"{dfm.SqlColOriginalName}\" TO \"{dfm.SqlColName}\"");
                            commands.Add(renameColCmd);
                        }
                    }

                    //TODO:处理EntityRef更新与删除规则
                    //注意不再需要同旧实现一样变更EntityRef的外键约束名称 "ALTER TABLE \"XXX\" RENAME CONSTRAINT \"XXX\" TO \"XXX\""
                    //因为ModelFirst的外键名称为FK_{MemberId};CodeFirst为导入的名称
                }
                #endregion
            }

            //处理索引变更
            BuildIndexes(model, commands, tableName);

            return(commands);
        }