HeaderValue.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace BestHTTP.Extensions
  6. {
  7. /// <summary>
  8. /// Used in string parsers. Its Value is optional.
  9. /// </summary>
  10. public sealed class HeaderValue
  11. {
  12. #region Public Properties
  13. public string Key { get; set; }
  14. public string Value { get; set; }
  15. public List<HeaderValue> Options { get; set; }
  16. public bool HasValue { get { return !string.IsNullOrEmpty(this.Value); } }
  17. #endregion
  18. #region Constructors
  19. public HeaderValue()
  20. { }
  21. public HeaderValue(string key)
  22. {
  23. this.Key = key;
  24. }
  25. #endregion
  26. #region Public Helper Functions
  27. public void Parse(string headerStr, ref int pos)
  28. {
  29. ParseImplementation(headerStr, ref pos, true);
  30. }
  31. public bool TryGetOption(string key, out HeaderValue option)
  32. {
  33. option = null;
  34. if (Options == null || Options.Count == 0)
  35. return false;
  36. for (int i = 0; i < Options.Count; ++i)
  37. if (String.Equals(Options[i].Key, key, StringComparison.OrdinalIgnoreCase))
  38. {
  39. option = Options[i];
  40. return true;
  41. }
  42. return false;
  43. }
  44. #endregion
  45. #region Private Helper Functions
  46. private void ParseImplementation(string headerStr, ref int pos, bool isOptionIsAnOption)
  47. {
  48. string key = headerStr.Read(ref pos, (ch) => ch != ';' && ch != '=' && ch != ',', true);
  49. this.Key = key;
  50. char? skippedChar = headerStr.Peek(pos - 1);
  51. bool isValue = skippedChar == '=';
  52. bool isOption = isOptionIsAnOption && skippedChar == ';';
  53. while (skippedChar != null && isValue || isOption)
  54. {
  55. if (isValue)
  56. {
  57. string value = headerStr.ReadPossibleQuotedText(ref pos);
  58. this.Value = value;
  59. }
  60. else if (isOption)
  61. {
  62. HeaderValue option = new HeaderValue();
  63. option.ParseImplementation(headerStr, ref pos, false);
  64. if (this.Options == null)
  65. this.Options = new List<HeaderValue>();
  66. this.Options.Add(option);
  67. }
  68. if (!isOptionIsAnOption)
  69. return;
  70. skippedChar = headerStr.Peek(pos - 1);
  71. isValue = skippedChar == '=';
  72. isOption = isOptionIsAnOption && skippedChar == ';';
  73. }
  74. }
  75. #endregion
  76. #region Overrides
  77. public override string ToString()
  78. {
  79. if (!string.IsNullOrEmpty(Value))
  80. return String.Concat(Key, '=', Value);
  81. else
  82. return Key;
  83. }
  84. #endregion
  85. }
  86. }