QueryStringHttpHeaders.cs 1.86 KB
Newer Older
Shani Elharrar's avatar
Shani Elharrar committed
1 2 3
using System;
using System.Collections;
using System.Collections.Generic;
4
using System.Diagnostics;
Shani Elharrar's avatar
Shani Elharrar committed
5 6 7

namespace uhttpsharp.Headers
{
8 9 10
    [DebuggerDisplay("{Count} Query String Headers")]
    [DebuggerTypeProxy(typeof(HttpHeadersDebuggerProxy))]
    internal class QueryStringHttpHeaders : IHttpHeaders
Shani Elharrar's avatar
Shani Elharrar committed
11 12 13 14
    {
        private readonly HttpHeaders _child;
        private static readonly char[] Seperators = {'&', '='};

15 16
        private readonly int _count;

Shani Elharrar's avatar
Shani Elharrar committed
17 18 19 20 21 22 23 24
        public QueryStringHttpHeaders(string query)
        {
            var splittedKeyValues = query.Split(Seperators, StringSplitOptions.RemoveEmptyEntries);
            var values = new Dictionary<string, string>(splittedKeyValues.Length / 2, StringComparer.InvariantCultureIgnoreCase);

            for (int i = 0; i < splittedKeyValues.Length; i += 2)
            {
                var key = Uri.UnescapeDataString(splittedKeyValues[i]);
25 26 27 28 29 30
                string value = null;
                if (splittedKeyValues.Length > i + 1)
                {
                    value = Uri.UnescapeDataString(splittedKeyValues[i + 1]).Replace('+', ' ');    
                }
                
Shani Elharrar's avatar
Shani Elharrar committed
31 32 33
                values[key] = value;
            }

34
            _count = values.Count;
Shani Elharrar's avatar
Shani Elharrar committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
            _child = new HttpHeaders(values);
        }

        public string GetByName(string name)
        {
            return _child.GetByName(name);
        }
        public bool TryGetByName(string name, out string value)
        {
            return _child.TryGetByName(name, out value);
        }
        public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
        {
            return _child.GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
54 55 56 57 58 59 60 61

        internal int Count
        {
            get
            {
                return _count;
            }
        }
Shani Elharrar's avatar
Shani Elharrar committed
62 63
    }
}