You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

234 lines
8.8 KiB

  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.Text.RegularExpressions;
  27. using Newtonsoft.Json.Bson;
  28. using System.Globalization;
  29. using System.Runtime.CompilerServices;
  30. using Newtonsoft.Json.Serialization;
  31. using Newtonsoft.Json.Utilities;
  32. namespace Newtonsoft.Json.Converters
  33. {
  34. /// <summary>
  35. /// Converts a <see cref="Regex"/> to and from JSON and BSON.
  36. /// </summary>
  37. internal class RegexConverter : JsonConverter
  38. {
  39. private const string PatternName = "Pattern";
  40. private const string OptionsName = "Options";
  41. /// <summary>
  42. /// Writes the JSON representation of the object.
  43. /// </summary>
  44. /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
  45. /// <param name="value">The value.</param>
  46. /// <param name="serializer">The calling serializer.</param>
  47. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  48. {
  49. if (value == null)
  50. {
  51. writer.WriteNull();
  52. return;
  53. }
  54. Regex regex = (Regex)value;
  55. #pragma warning disable 618
  56. if (writer is BsonWriter bsonWriter)
  57. {
  58. WriteBson(bsonWriter, regex);
  59. }
  60. #pragma warning restore 618
  61. else
  62. {
  63. WriteJson(writer, regex, serializer);
  64. }
  65. }
  66. private bool HasFlag(RegexOptions options, RegexOptions flag)
  67. {
  68. return ((options & flag) == flag);
  69. }
  70. #pragma warning disable 618
  71. private void WriteBson(BsonWriter writer, Regex regex)
  72. {
  73. // Regular expression - The first cstring is the regex pattern, the second
  74. // is the regex options string. Options are identified by characters, which
  75. // must be stored in alphabetical order. Valid options are 'i' for case
  76. // insensitive matching, 'm' for multiline matching, 'x' for verbose mode,
  77. // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode
  78. // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.
  79. string options = null;
  80. if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
  81. {
  82. options += "i";
  83. }
  84. if (HasFlag(regex.Options, RegexOptions.Multiline))
  85. {
  86. options += "m";
  87. }
  88. if (HasFlag(regex.Options, RegexOptions.Singleline))
  89. {
  90. options += "s";
  91. }
  92. options += "u";
  93. if (HasFlag(regex.Options, RegexOptions.ExplicitCapture))
  94. {
  95. options += "x";
  96. }
  97. writer.WriteRegex(regex.ToString(), options);
  98. }
  99. #pragma warning restore 618
  100. private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer)
  101. {
  102. DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
  103. writer.WriteStartObject();
  104. writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName);
  105. writer.WriteValue(regex.ToString());
  106. writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(OptionsName) : OptionsName);
  107. serializer.Serialize(writer, regex.Options);
  108. writer.WriteEndObject();
  109. }
  110. /// <summary>
  111. /// Reads the JSON representation of the object.
  112. /// </summary>
  113. /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
  114. /// <param name="objectType">Type of the object.</param>
  115. /// <param name="existingValue">The existing value of object being read.</param>
  116. /// <param name="serializer">The calling serializer.</param>
  117. /// <returns>The object value.</returns>
  118. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  119. {
  120. switch (reader.TokenType)
  121. {
  122. case JsonToken.StartObject:
  123. return ReadRegexObject(reader, serializer);
  124. case JsonToken.String:
  125. return ReadRegexString(reader);
  126. case JsonToken.Null:
  127. return null;
  128. }
  129. throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex.");
  130. }
  131. private object ReadRegexString(JsonReader reader)
  132. {
  133. string regexText = (string)reader.Value;
  134. if (regexText.Length > 0 && regexText[0] == '/')
  135. {
  136. int patternOptionDelimiterIndex = regexText.LastIndexOf('/');
  137. if (patternOptionDelimiterIndex > 0)
  138. {
  139. string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
  140. string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);
  141. RegexOptions options = MiscellaneousUtils.GetRegexOptions(optionsText);
  142. return new Regex(patternText, options);
  143. }
  144. }
  145. throw JsonSerializationException.Create(reader, "Regex pattern must be enclosed by slashes.");
  146. }
  147. private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer)
  148. {
  149. string pattern = null;
  150. RegexOptions? options = null;
  151. while (reader.Read())
  152. {
  153. switch (reader.TokenType)
  154. {
  155. case JsonToken.PropertyName:
  156. string propertyName = reader.Value.ToString();
  157. if (!reader.Read())
  158. {
  159. throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
  160. }
  161. if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase))
  162. {
  163. pattern = (string)reader.Value;
  164. }
  165. else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase))
  166. {
  167. options = serializer.Deserialize<RegexOptions>(reader);
  168. }
  169. else
  170. {
  171. reader.Skip();
  172. }
  173. break;
  174. case JsonToken.Comment:
  175. break;
  176. case JsonToken.EndObject:
  177. if (pattern == null)
  178. {
  179. throw JsonSerializationException.Create(reader, "Error deserializing Regex. No pattern found.");
  180. }
  181. return new Regex(pattern, options ?? RegexOptions.None);
  182. }
  183. }
  184. throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
  185. }
  186. /// <summary>
  187. /// Determines whether this instance can convert the specified object type.
  188. /// </summary>
  189. /// <param name="objectType">Type of the object.</param>
  190. /// <returns>
  191. /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
  192. /// </returns>
  193. public override bool CanConvert(Type objectType)
  194. {
  195. return objectType.Name == nameof(Regex) && IsRegex(objectType);
  196. }
  197. [MethodImpl(MethodImplOptions.NoInlining)]
  198. private bool IsRegex(Type objectType)
  199. {
  200. return (objectType == typeof(Regex));
  201. }
  202. }
  203. }