コード例 #1
0
        private static bool TrySetOptionalTokenList(
            NameValueHeaderValue nameValue,
            ref bool boolField,
            ref ICollection <StringSegment> destination)
        {
            Contract.Requires(nameValue != null);

            if (nameValue.Value == null)
            {
                boolField = true;
                return(true);
            }

            // We need the string to be at least 3 chars long: 2x quotes and at least 1 character. Also make sure we
            // have a quoted string. Note that NameValueHeaderValue will never have leading/trailing whitespaces.
            var valueString = nameValue.Value;

            if ((valueString.Length < 3) || (valueString[0] != '\"') || (valueString[valueString.Length - 1] != '\"'))
            {
                return(false);
            }

            // We have a quoted string. Now verify that the string contains a list of valid tokens separated by ','.
            var current            = 1;                      // skip the initial '"' character.
            var maxLength          = valueString.Length - 1; // -1 because we don't want to parse the final '"'.
            var separatorFound     = false;
            var originalValueCount = destination == null ? 0 : destination.Count;

            while (current < maxLength)
            {
                current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true,
                                                                           out separatorFound);

                if (current == maxLength)
                {
                    break;
                }

                var tokenLength = HttpRuleParser.GetTokenLength(valueString, current);

                if (tokenLength == 0)
                {
                    // We already skipped whitespaces and separators. If we don't have a token it must be an invalid
                    // character.
                    return(false);
                }

                if (destination == null)
                {
                    destination = new ObjectCollection <StringSegment>(CheckIsValidTokenAction);
                }

                destination.Add(valueString.Subsegment(current, tokenLength));

                current = current + tokenLength;
            }

            // After parsing a valid token list, we expect to have at least one value
            if ((destination != null) && (destination.Count > originalValueCount))
            {
                boolField = true;
                return(true);
            }

            return(false);
        }