Refactored WebHeaderCollection.cs

This commit is contained in:
sta 2014-10-29 14:41:30 +09:00
parent af250750b7
commit 6822fdce36
6 changed files with 65 additions and 73 deletions

View File

@ -323,7 +323,7 @@ namespace WebSocketSharp
internal static void CloseWithAuthChallenge ( internal static void CloseWithAuthChallenge (
this HttpListenerResponse response, string challenge) this HttpListenerResponse response, string challenge)
{ {
response.Headers.SetInternally ("WWW-Authenticate", challenge, true); response.Headers.InternalSet ("WWW-Authenticate", challenge, true);
response.Close (HttpStatusCode.Unauthorized); response.Close (HttpStatusCode.Unauthorized);
} }

View File

@ -154,7 +154,7 @@ namespace WebSocketSharp
var headers = new WebHeaderCollection (); var headers = new WebHeaderCollection ();
for (int i = 1; i < headerParts.Length; i++) for (int i = 1; i < headerParts.Length; i++)
headers.SetInternally (headerParts[i], false); headers.InternalSet (headerParts[i], false);
return new HttpRequest ( return new HttpRequest (
requestLine[0], requestLine[1], new Version (requestLine[2].Substring (5)), headers); requestLine[0], requestLine[1], new Version (requestLine[2].Substring (5)), headers);

View File

@ -168,7 +168,7 @@ namespace WebSocketSharp
var headers = new WebHeaderCollection (); var headers = new WebHeaderCollection ();
for (int i = 1; i < headerParts.Length; i++) for (int i = 1; i < headerParts.Length; i++)
headers.SetInternally (headerParts[i], true); headers.InternalSet (headerParts[i], true);
return new HttpResponse ( return new HttpResponse (
statusLine[1], statusLine[2], new Version (statusLine[0].Substring (5)), headers); statusLine[1], statusLine[2], new Version (statusLine[0].Substring (5)), headers);

View File

@ -491,7 +491,7 @@ namespace WebSocketSharp.Net
var name = header.Substring (0, colon).Trim (); var name = header.Substring (0, colon).Trim ();
var val = header.Substring (colon + 1).Trim (); var val = header.Substring (colon + 1).Trim ();
_headers.SetInternally (name, val, false); _headers.InternalSet (name, val, false);
var lower = name.ToLower (CultureInfo.InvariantCulture); var lower = name.ToLower (CultureInfo.InvariantCulture);
if (lower == "accept") { if (lower == "accept") {

View File

@ -518,15 +518,15 @@ namespace WebSocketSharp.Net
"{0}; charset={1}", _contentType, _contentEncoding.WebName) "{0}; charset={1}", _contentType, _contentEncoding.WebName)
: _contentType; : _contentType;
_headers.SetInternally ("Content-Type", contentType, true); _headers.InternalSet ("Content-Type", contentType, true);
} }
if (_headers["Server"] == null) if (_headers["Server"] == null)
_headers.SetInternally ("Server", "websocket-sharp/1.0", true); _headers.InternalSet ("Server", "websocket-sharp/1.0", true);
var provider = CultureInfo.InvariantCulture; var provider = CultureInfo.InvariantCulture;
if (_headers["Date"] == null) if (_headers["Date"] == null)
_headers.SetInternally ("Date", DateTime.UtcNow.ToString ("r", provider), true); _headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", provider), true);
if (!_chunked) { if (!_chunked) {
if (!_contentLengthWasSet && closing) { if (!_contentLengthWasSet && closing) {
@ -535,7 +535,7 @@ namespace WebSocketSharp.Net
} }
if (_contentLengthWasSet) if (_contentLengthWasSet)
_headers.SetInternally ("Content-Length", _contentLength.ToString (provider), true); _headers.InternalSet ("Content-Length", _contentLength.ToString (provider), true);
} }
var reqVer = _context.Request.ProtocolVersion; var reqVer = _context.Request.ProtocolVersion;
@ -565,36 +565,36 @@ namespace WebSocketSharp.Net
// They sent both KeepAlive: true and Connection: close!? // They sent both KeepAlive: true and Connection: close!?
if (!_keepAlive || connClose) { if (!_keepAlive || connClose) {
_headers.SetInternally ("Connection", "close", true); _headers.InternalSet ("Connection", "close", true);
connClose = true; connClose = true;
} }
if (_chunked) if (_chunked)
_headers.SetInternally ("Transfer-Encoding", "chunked", true); _headers.InternalSet ("Transfer-Encoding", "chunked", true);
var reuses = _context.Connection.Reuses; var reuses = _context.Connection.Reuses;
if (reuses >= 100) { if (reuses >= 100) {
_forceCloseChunked = true; _forceCloseChunked = true;
if (!connClose) { if (!connClose) {
_headers.SetInternally ("Connection", "close", true); _headers.InternalSet ("Connection", "close", true);
connClose = true; connClose = true;
} }
} }
if (!connClose) { if (!connClose) {
_headers.SetInternally ( _headers.InternalSet (
"Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true); "Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true);
if (reqVer < HttpVersion.Version11) if (reqVer < HttpVersion.Version11)
_headers.SetInternally ("Connection", "keep-alive", true); _headers.InternalSet ("Connection", "keep-alive", true);
} }
if (_location != null) if (_location != null)
_headers.SetInternally ("Location", _location, true); _headers.InternalSet ("Location", _location, true);
if (_cookies != null) if (_cookies != null)
foreach (Cookie cookie in _cookies) foreach (Cookie cookie in _cookies)
_headers.SetInternally ("Set-Cookie", cookie.ToResponseString (), true); _headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true);
var enc = _contentEncoding ?? Encoding.Default; var enc = _contentEncoding ?? Encoding.Default;
var writer = new StreamWriter (stream, enc, 256); var writer = new StreamWriter (stream, enc, 256);

View File

@ -59,16 +59,11 @@ namespace WebSocketSharp.Net
[ComVisible (true)] [ComVisible (true)]
public class WebHeaderCollection : NameValueCollection, ISerializable public class WebHeaderCollection : NameValueCollection, ISerializable
{ {
#region Private Static Fields
private static readonly Dictionary<string, HttpHeaderInfo> _headers;
#endregion
#region Private Fields #region Private Fields
private bool _internallyCreated; private static readonly Dictionary<string, HttpHeaderInfo> _headers;
private HttpHeaderType _state; private bool _internallyCreated;
private HttpHeaderType _state;
#endregion #endregion
@ -557,11 +552,11 @@ namespace WebSocketSharp.Net
_internallyCreated = serializationInfo.GetBoolean ("InternallyCreated"); _internallyCreated = serializationInfo.GetBoolean ("InternallyCreated");
_state = (HttpHeaderType) serializationInfo.GetInt32 ("State"); _state = (HttpHeaderType) serializationInfo.GetInt32 ("State");
var count = serializationInfo.GetInt32 ("Count"); var cnt = serializationInfo.GetInt32 ("Count");
for (int i = 0; i < count; i++) { for (var i = 0; i < cnt; i++) {
base.Add ( base.Add (
serializationInfo.GetString (i.ToString ()), serializationInfo.GetString (i.ToString ()),
serializationInfo.GetString ((count + i).ToString ())); serializationInfo.GetString ((cnt + i).ToString ()));
} }
} }
catch (SerializationException ex) { catch (SerializationException ex) {
@ -578,7 +573,6 @@ namespace WebSocketSharp.Net
/// </summary> /// </summary>
public WebHeaderCollection () public WebHeaderCollection ()
{ {
_internallyCreated = false;
_state = HttpHeaderType.Unspecified; _state = HttpHeaderType.Unspecified;
} }
@ -592,7 +586,7 @@ namespace WebSocketSharp.Net
/// <value> /// <value>
/// An array of <see cref="string"/> that contains all header names in the collection. /// An array of <see cref="string"/> that contains all header names in the collection.
/// </value> /// </value>
public override string [] AllKeys { public override string[] AllKeys {
get { get {
return base.AllKeys; return base.AllKeys;
} }
@ -638,7 +632,7 @@ namespace WebSocketSharp.Net
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow the request /// The current <see cref="WebHeaderCollection"/> instance doesn't allow the request
/// <paramref name="header"/>. /// <paramref name="header"/>.
/// </exception> /// </exception>
public string this [HttpRequestHeader header] { public string this[HttpRequestHeader header] {
get { get {
return Get (Convert (header)); return Get (Convert (header));
} }
@ -676,7 +670,7 @@ namespace WebSocketSharp.Net
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow the response /// The current <see cref="WebHeaderCollection"/> instance doesn't allow the response
/// <paramref name="header"/>. /// <paramref name="header"/>.
/// </exception> /// </exception>
public string this [HttpResponseHeader header] { public string this[HttpResponseHeader header] {
get { get {
return Get (Convert (header)); return Get (Convert (header));
} }
@ -705,11 +699,9 @@ namespace WebSocketSharp.Net
private void add (string name, string value, bool ignoreRestricted) private void add (string name, string value, bool ignoreRestricted)
{ {
Action <string, string> act; var act = ignoreRestricted
if (ignoreRestricted) ? (Action <string, string>) addWithoutCheckingNameAndRestricted
act = addWithoutCheckingNameAndRestricted; : addWithoutCheckingName;
else
act = addWithoutCheckingName;
doWithCheckingState (act, checkName (name), value, true); doWithCheckingState (act, checkName (name), value, true);
} }
@ -728,7 +720,7 @@ namespace WebSocketSharp.Net
{ {
var i = header.IndexOf (':'); var i = header.IndexOf (':');
if (i == -1) if (i == -1)
throw new ArgumentException ("No colon found.", "header"); throw new ArgumentException ("No colon could be found.", "header");
return i; return i;
} }
@ -867,6 +859,26 @@ namespace WebSocketSharp.Net
return convert (header.ToString ()); return convert (header.ToString ());
} }
internal void InternalRemove (string name)
{
base.Remove (name);
}
internal void InternalSet (string header, bool response)
{
var pos = checkColonSeparated (header);
InternalSet (header.Substring (0, pos), header.Substring (pos + 1), response);
}
internal void InternalSet (string name, string value, bool response)
{
value = checkValue (value);
if (IsMultiValue (name, response))
base.Add (name, value);
else
base.Set (name, value);
}
internal static bool IsHeaderName (string name) internal static bool IsHeaderName (string name)
{ {
return name != null && name.Length > 0 && name.IsToken (); return name != null && name.Length > 0 && name.IsToken ();
@ -886,26 +898,6 @@ namespace WebSocketSharp.Net
return info != null && info.IsMultiValue (response); return info != null && info.IsMultiValue (response);
} }
internal void RemoveInternally (string name)
{
base.Remove (name);
}
internal void SetInternally (string header, bool response)
{
var pos = checkColonSeparated (header);
SetInternally (header.Substring (0, pos), header.Substring (pos + 1), response);
}
internal void SetInternally (string name, string value, bool response)
{
value = checkValue (value);
if (IsMultiValue (name, response))
base.Add (name, value);
else
base.Set (name, value);
}
internal string ToStringMultiValue (bool response) internal string ToStringMultiValue (bool response)
{ {
var buff = new StringBuilder (); var buff = new StringBuilder ();
@ -913,8 +905,8 @@ namespace WebSocketSharp.Net
i => { i => {
var key = GetKey (i); var key = GetKey (i);
if (IsMultiValue (key, response)) if (IsMultiValue (key, response))
foreach (var value in GetValues (i)) foreach (var val in GetValues (i))
buff.AppendFormat ("{0}: {1}\r\n", key, value); buff.AppendFormat ("{0}: {1}\r\n", key, val);
else else
buff.AppendFormat ("{0}: {1}\r\n", key, Get (i)); buff.AppendFormat ("{0}: {1}\r\n", key, Get (i));
}); });
@ -963,7 +955,7 @@ namespace WebSocketSharp.Net
/// </summary> /// </summary>
/// <param name="header"> /// <param name="header">
/// A <see cref="string"/> that represents the header with the name and value separated by /// A <see cref="string"/> that represents the header with the name and value separated by
/// a colon (<c>:</c>). /// a colon (<c>':'</c>).
/// </param> /// </param>
/// <exception cref="ArgumentNullException"> /// <exception cref="ArgumentNullException">
/// <paramref name="header"/> is <see langword="null"/>, empty, or the name part of /// <paramref name="header"/> is <see langword="null"/>, empty, or the name part of
@ -1189,11 +1181,11 @@ namespace WebSocketSharp.Net
/// <exception cref="ArgumentOutOfRangeException"> /// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection. /// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception> /// </exception>
public override string [] GetValues (int index) public override string[] GetValues (int index)
{ {
var values = base.GetValues (index); var vals = base.GetValues (index);
return values != null && values.Length > 0 return vals != null && vals.Length > 0
? values ? vals
: null; : null;
} }
@ -1207,11 +1199,11 @@ namespace WebSocketSharp.Net
/// <param name="header"> /// <param name="header">
/// A <see cref="string"/> that represents the name of the header to find. /// A <see cref="string"/> that represents the name of the header to find.
/// </param> /// </param>
public override string [] GetValues (string header) public override string[] GetValues (string header)
{ {
var values = base.GetValues (header); var vals = base.GetValues (header);
return values != null && values.Length > 0 return vals != null && vals.Length > 0
? values ? vals
: null; : null;
} }
@ -1239,12 +1231,12 @@ namespace WebSocketSharp.Net
serializationInfo.AddValue ("InternallyCreated", _internallyCreated); serializationInfo.AddValue ("InternallyCreated", _internallyCreated);
serializationInfo.AddValue ("State", (int) _state); serializationInfo.AddValue ("State", (int) _state);
var count = Count; var cnt = Count;
serializationInfo.AddValue ("Count", count); serializationInfo.AddValue ("Count", cnt);
count.Times ( cnt.Times (
i => { i => {
serializationInfo.AddValue (i.ToString (), GetKey (i)); serializationInfo.AddValue (i.ToString (), GetKey (i));
serializationInfo.AddValue ((count + i).ToString (), Get (i)); serializationInfo.AddValue ((cnt + i).ToString (), Get (i));
}); });
} }
@ -1477,7 +1469,7 @@ namespace WebSocketSharp.Net
/// An array of <see cref="byte"/> that receives the converted current /// An array of <see cref="byte"/> that receives the converted current
/// <see cref="WebHeaderCollection"/>. /// <see cref="WebHeaderCollection"/>.
/// </returns> /// </returns>
public byte [] ToByteArray () public byte[] ToByteArray ()
{ {
return Encoding.UTF8.GetBytes (ToString ()); return Encoding.UTF8.GetBytes (ToString ());
} }
@ -1499,7 +1491,7 @@ namespace WebSocketSharp.Net
#endregion #endregion
#region Explicit Interface Implementation #region Explicit Interface Implementations
/// <summary> /// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize /// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize