Metadata.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #region Copyright notice and license
  2. // Copyright 2015, Google Inc.
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #endregion
  31. using System;
  32. using System.Collections;
  33. using System.Collections.Generic;
  34. using System.Collections.Specialized;
  35. using System.Runtime.InteropServices;
  36. using System.Text;
  37. using Grpc.Core.Utils;
  38. namespace Grpc.Core
  39. {
  40. /// <summary>
  41. /// Provides access to read and write metadata values to be exchanged during a call.
  42. /// </summary>
  43. public sealed class Metadata : IList<Metadata.Entry>
  44. {
  45. /// <summary>
  46. /// All binary headers should have this suffix.
  47. /// </summary>
  48. public const string BinaryHeaderSuffix = "-bin";
  49. /// <summary>
  50. /// An read-only instance of metadata containing no entries.
  51. /// </summary>
  52. public static readonly Metadata Empty = new Metadata().Freeze();
  53. readonly List<Entry> entries;
  54. bool readOnly;
  55. public Metadata()
  56. {
  57. this.entries = new List<Entry>();
  58. }
  59. public Metadata(ICollection<Entry> entries)
  60. {
  61. this.entries = new List<Entry>(entries);
  62. }
  63. /// <summary>
  64. /// Makes this object read-only.
  65. /// </summary>
  66. /// <returns>this object</returns>
  67. public Metadata Freeze()
  68. {
  69. this.readOnly = true;
  70. return this;
  71. }
  72. // TODO: add support for access by key
  73. #region IList members
  74. public int IndexOf(Metadata.Entry item)
  75. {
  76. return entries.IndexOf(item);
  77. }
  78. public void Insert(int index, Metadata.Entry item)
  79. {
  80. CheckWriteable();
  81. entries.Insert(index, item);
  82. }
  83. public void RemoveAt(int index)
  84. {
  85. CheckWriteable();
  86. entries.RemoveAt(index);
  87. }
  88. public Metadata.Entry this[int index]
  89. {
  90. get
  91. {
  92. return entries[index];
  93. }
  94. set
  95. {
  96. CheckWriteable();
  97. entries[index] = value;
  98. }
  99. }
  100. public void Add(Metadata.Entry item)
  101. {
  102. CheckWriteable();
  103. entries.Add(item);
  104. }
  105. public void Add(string key, string value)
  106. {
  107. Add(new Entry(key, value));
  108. }
  109. public void Add(string key, byte[] valueBytes)
  110. {
  111. Add(new Entry(key, valueBytes));
  112. }
  113. public void Clear()
  114. {
  115. CheckWriteable();
  116. entries.Clear();
  117. }
  118. public bool Contains(Metadata.Entry item)
  119. {
  120. return entries.Contains(item);
  121. }
  122. public void CopyTo(Metadata.Entry[] array, int arrayIndex)
  123. {
  124. entries.CopyTo(array, arrayIndex);
  125. }
  126. public int Count
  127. {
  128. get { return entries.Count; }
  129. }
  130. public bool IsReadOnly
  131. {
  132. get { return readOnly; }
  133. }
  134. public bool Remove(Metadata.Entry item)
  135. {
  136. CheckWriteable();
  137. return entries.Remove(item);
  138. }
  139. public IEnumerator<Metadata.Entry> GetEnumerator()
  140. {
  141. return entries.GetEnumerator();
  142. }
  143. IEnumerator System.Collections.IEnumerable.GetEnumerator()
  144. {
  145. return entries.GetEnumerator();
  146. }
  147. private void CheckWriteable()
  148. {
  149. Preconditions.CheckState(!readOnly, "Object is read only");
  150. }
  151. #endregion
  152. /// <summary>
  153. /// Metadata entry
  154. /// </summary>
  155. public struct Entry
  156. {
  157. private static readonly Encoding Encoding = Encoding.ASCII;
  158. readonly string key;
  159. readonly string value;
  160. readonly byte[] valueBytes;
  161. private Entry(string key, string value, byte[] valueBytes)
  162. {
  163. this.key = key;
  164. this.value = value;
  165. this.valueBytes = valueBytes;
  166. }
  167. /// <summary>
  168. /// Initializes a new instance of the <see cref="Grpc.Core.Metadata+Entry"/> struct with a binary value.
  169. /// </summary>
  170. /// <param name="key">Metadata key, needs to have suffix indicating a binary valued metadata entry.</param>
  171. /// <param name="valueBytes">Value bytes.</param>
  172. public Entry(string key, byte[] valueBytes)
  173. {
  174. this.key = NormalizeKey(key);
  175. Preconditions.CheckArgument(this.key.EndsWith(BinaryHeaderSuffix),
  176. "Key for binary valued metadata entry needs to have suffix indicating binary value.");
  177. this.value = null;
  178. Preconditions.CheckNotNull(valueBytes, "valueBytes");
  179. this.valueBytes = new byte[valueBytes.Length];
  180. Buffer.BlockCopy(valueBytes, 0, this.valueBytes, 0, valueBytes.Length); // defensive copy to guarantee immutability
  181. }
  182. /// <summary>
  183. /// Initializes a new instance of the <see cref="Grpc.Core.Metadata+Entry"/> struct holding an ASCII value.
  184. /// </summary>
  185. /// <param name="key">Metadata key, must not use suffix indicating a binary valued metadata entry.</param>
  186. /// <param name="value">Value string. Only ASCII characters are allowed.</param>
  187. public Entry(string key, string value)
  188. {
  189. this.key = NormalizeKey(key);
  190. Preconditions.CheckArgument(!this.key.EndsWith(BinaryHeaderSuffix),
  191. "Key for ASCII valued metadata entry cannot have suffix indicating binary value.");
  192. this.value = Preconditions.CheckNotNull(value, "value");
  193. this.valueBytes = null;
  194. }
  195. /// <summary>
  196. /// Gets the metadata entry key.
  197. /// </summary>
  198. public string Key
  199. {
  200. get
  201. {
  202. return this.key;
  203. }
  204. }
  205. /// <summary>
  206. /// Gets the binary value of this metadata entry.
  207. /// </summary>
  208. public byte[] ValueBytes
  209. {
  210. get
  211. {
  212. if (valueBytes == null)
  213. {
  214. return Encoding.GetBytes(value);
  215. }
  216. // defensive copy to guarantee immutability
  217. var bytes = new byte[valueBytes.Length];
  218. Buffer.BlockCopy(valueBytes, 0, bytes, 0, valueBytes.Length);
  219. return bytes;
  220. }
  221. }
  222. /// <summary>
  223. /// Gets the string value of this metadata entry.
  224. /// </summary>
  225. public string Value
  226. {
  227. get
  228. {
  229. Preconditions.CheckState(!IsBinary, "Cannot access string value of a binary metadata entry");
  230. return value ?? Encoding.GetString(valueBytes);
  231. }
  232. }
  233. /// <summary>
  234. /// Returns <c>true</c> if this entry is a binary-value entry.
  235. /// </summary>
  236. public bool IsBinary
  237. {
  238. get
  239. {
  240. return value == null;
  241. }
  242. }
  243. /// <summary>
  244. /// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Metadata+Entry"/>.
  245. /// </summary>
  246. public override string ToString()
  247. {
  248. if (IsBinary)
  249. {
  250. return string.Format("[Entry: key={0}, valueBytes={1}]", key, valueBytes);
  251. }
  252. return string.Format("[Entry: key={0}, value={1}]", key, value);
  253. }
  254. /// <summary>
  255. /// Gets the serialized value for this entry. For binary metadata entries, this leaks
  256. /// the internal <c>valueBytes</c> byte array and caller must not change contents of it.
  257. /// </summary>
  258. internal byte[] GetSerializedValueUnsafe()
  259. {
  260. return valueBytes ?? Encoding.GetBytes(value);
  261. }
  262. /// <summary>
  263. /// Creates a binary value or ascii value metadata entry from data received from the native layer.
  264. /// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying.
  265. /// </summary>
  266. internal static Entry CreateUnsafe(string key, byte[] valueBytes)
  267. {
  268. if (key.EndsWith(BinaryHeaderSuffix))
  269. {
  270. return new Entry(key, null, valueBytes);
  271. }
  272. return new Entry(key, Encoding.GetString(valueBytes), null);
  273. }
  274. private static string NormalizeKey(string key)
  275. {
  276. return Preconditions.CheckNotNull(key, "key").ToLower();
  277. }
  278. }
  279. }
  280. }