BsonUtils.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /* Copyright 2010-2014 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. namespace MongoDB.Bson
  19. {
  20. /// <summary>
  21. /// A static class containing BSON utility methods.
  22. /// </summary>
  23. public static class BsonUtils
  24. {
  25. // public static methods
  26. /// <summary>
  27. /// Gets a friendly class name suitable for use in error messages.
  28. /// </summary>
  29. /// <param name="type">The type.</param>
  30. /// <returns>A friendly class name.</returns>
  31. public static string GetFriendlyTypeName(Type type)
  32. {
  33. if (!type.IsGenericType)
  34. {
  35. return type.Name;
  36. }
  37. var sb = new StringBuilder();
  38. sb.AppendFormat("{0}<", Regex.Replace(type.Name, @"\`\d+$", ""));
  39. foreach (var typeParameter in type.GetGenericArguments())
  40. {
  41. sb.AppendFormat("{0}, ", GetFriendlyTypeName(typeParameter));
  42. }
  43. sb.Remove(sb.Length - 2, 2);
  44. sb.Append(">");
  45. return sb.ToString();
  46. }
  47. /// <summary>
  48. /// Parses a hex string into its equivalent byte array.
  49. /// </summary>
  50. /// <param name="s">The hex string to parse.</param>
  51. /// <returns>The byte equivalent of the hex string.</returns>
  52. public static byte[] ParseHexString(string s)
  53. {
  54. if (s == null)
  55. {
  56. throw new ArgumentNullException("s");
  57. }
  58. byte[] bytes;
  59. if ((s.Length & 1) != 0)
  60. {
  61. s = "0" + s; // make length of s even
  62. }
  63. bytes = new byte[s.Length / 2];
  64. for (int i = 0; i < bytes.Length; i++)
  65. {
  66. string hex = s.Substring(2 * i, 2);
  67. try
  68. {
  69. byte b = Convert.ToByte(hex, 16);
  70. bytes[i] = b;
  71. }
  72. catch (FormatException e)
  73. {
  74. throw new FormatException(
  75. string.Format("Invalid hex string {0}. Problem with substring {1} starting at position {2}",
  76. s,
  77. hex,
  78. 2 * i),
  79. e);
  80. }
  81. }
  82. return bytes;
  83. }
  84. /// <summary>
  85. /// Converts from number of milliseconds since Unix epoch to DateTime.
  86. /// </summary>
  87. /// <param name="millisecondsSinceEpoch">The number of milliseconds since Unix epoch.</param>
  88. /// <returns>A DateTime.</returns>
  89. public static DateTime ToDateTimeFromMillisecondsSinceEpoch(long millisecondsSinceEpoch)
  90. {
  91. if (millisecondsSinceEpoch < BsonConstants.DateTimeMinValueMillisecondsSinceEpoch ||
  92. millisecondsSinceEpoch > BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
  93. {
  94. var message = string.Format(
  95. "The value {0} for the BsonDateTime MillisecondsSinceEpoch is outside the"+
  96. "range that can be converted to a .NET DateTime.",
  97. millisecondsSinceEpoch);
  98. throw new ArgumentOutOfRangeException("millisecondsSinceEpoch", message);
  99. }
  100. // MaxValue has to be handled specially to avoid rounding errors
  101. if (millisecondsSinceEpoch == BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
  102. {
  103. return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
  104. }
  105. else
  106. {
  107. return BsonConstants.UnixEpoch.AddTicks(millisecondsSinceEpoch * 10000);
  108. }
  109. }
  110. /// <summary>
  111. /// Converts a byte array to a hex string.
  112. /// </summary>
  113. /// <param name="bytes">The byte array.</param>
  114. /// <returns>A hex string.</returns>
  115. public static string ToHexString(byte[] bytes)
  116. {
  117. if (bytes == null)
  118. {
  119. throw new ArgumentNullException("bytes");
  120. }
  121. var sb = new StringBuilder(bytes.Length * 2);
  122. foreach (var b in bytes)
  123. {
  124. sb.AppendFormat("{0:x2}", b);
  125. }
  126. return sb.ToString();
  127. }
  128. /// <summary>
  129. /// Converts a DateTime to local time (with special handling for MinValue and MaxValue).
  130. /// </summary>
  131. /// <param name="dateTime">A DateTime.</param>
  132. /// <returns>The DateTime in local time.</returns>
  133. public static DateTime ToLocalTime(DateTime dateTime)
  134. {
  135. if (dateTime == DateTime.MinValue)
  136. {
  137. return DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Local);
  138. }
  139. else if (dateTime == DateTime.MaxValue)
  140. {
  141. return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Local);
  142. }
  143. else
  144. {
  145. return dateTime.ToLocalTime();
  146. }
  147. }
  148. /// <summary>
  149. /// Converts a DateTime to number of milliseconds since Unix epoch.
  150. /// </summary>
  151. /// <param name="dateTime">A DateTime.</param>
  152. /// <returns>Number of seconds since Unix epoch.</returns>
  153. public static long ToMillisecondsSinceEpoch(DateTime dateTime)
  154. {
  155. var utcDateTime = ToUniversalTime(dateTime);
  156. return (utcDateTime - BsonConstants.UnixEpoch).Ticks / 10000;
  157. }
  158. /// <summary>
  159. /// Converts a DateTime to UTC (with special handling for MinValue and MaxValue).
  160. /// </summary>
  161. /// <param name="dateTime">A DateTime.</param>
  162. /// <returns>The DateTime in UTC.</returns>
  163. public static DateTime ToUniversalTime(DateTime dateTime)
  164. {
  165. if (dateTime == DateTime.MinValue)
  166. {
  167. return DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
  168. }
  169. else if (dateTime == DateTime.MaxValue)
  170. {
  171. return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
  172. }
  173. else
  174. {
  175. return dateTime.ToUniversalTime();
  176. }
  177. }
  178. /// <summary>
  179. /// Tries to parse a hex string to a byte array.
  180. /// </summary>
  181. /// <param name="s">The hex string.</param>
  182. /// <param name="bytes">A byte array.</param>
  183. /// <returns>True if the hex string was successfully parsed.</returns>
  184. public static bool TryParseHexString(string s, out byte[] bytes)
  185. {
  186. try
  187. {
  188. bytes = ParseHexString(s);
  189. }
  190. catch
  191. {
  192. bytes = null;
  193. return false;
  194. }
  195. return true;
  196. }
  197. }
  198. }