Skip to content

Commit 858abaa

Browse files
authored
Replace string creation with static strings for Regex options conversion to string (#1504)
1 parent 7fd4cf7 commit 858abaa

File tree

1 file changed

+34
-17
lines changed

1 file changed

+34
-17
lines changed

src/MongoDB.Bson/ObjectModel/BsonRegularExpression.cs

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,27 @@ namespace MongoDB.Bson
2424
/// </summary>
2525
public class BsonRegularExpression : BsonValue, IComparable<BsonRegularExpression>, IEquatable<BsonRegularExpression>
2626
{
27+
// private static fields
28+
private static readonly string[] RegexOptionStrings = new[]
29+
{
30+
"", // 0000
31+
"i", // 0001
32+
"m", // 0010
33+
"im", // 0011
34+
"s", // 0100
35+
"is", // 0101
36+
"ms", // 0110
37+
"ims", // 0111
38+
"x", // 1000
39+
"ix", // 1001
40+
"mx", // 1010
41+
"imx", // 1011
42+
"sx", // 1100
43+
"isx", // 1101
44+
"msx", // 1110
45+
"imsx" // 1111
46+
};
47+
2748
// private fields
2849
private readonly string _pattern;
2950
private readonly string _options;
@@ -80,23 +101,19 @@ public BsonRegularExpression(Regex regex)
80101
throw new ArgumentNullException("regex");
81102
}
82103
_pattern = regex.ToString();
83-
_options = "";
84-
if ((regex.Options & RegexOptions.IgnoreCase) != 0)
85-
{
86-
_options += "i";
87-
}
88-
if ((regex.Options & RegexOptions.Multiline) != 0)
89-
{
90-
_options += "m";
91-
}
92-
if ((regex.Options & RegexOptions.Singleline) != 0)
93-
{
94-
_options += "s";
95-
}
96-
if ((regex.Options & RegexOptions.IgnorePatternWhitespace) != 0)
97-
{
98-
_options += "x";
99-
}
104+
_options = ConvertToBsonRegularExpressionOptions(regex);
105+
}
106+
107+
private static string ConvertToBsonRegularExpressionOptions(Regex regex)
108+
{
109+
var regexOptions = regex.Options;
110+
111+
var index = ((regexOptions & RegexOptions.IgnoreCase) != 0 ? 1 : 0) |
112+
((regexOptions & RegexOptions.Multiline) != 0 ? 1 : 0) << 1 |
113+
((regexOptions & RegexOptions.Singleline) != 0 ? 1 : 0) << 2 |
114+
((regexOptions & RegexOptions.IgnorePatternWhitespace) != 0 ? 1 : 0) << 3;
115+
116+
return RegexOptionStrings[index];
100117
}
101118

102119
// public properties

0 commit comments

Comments
 (0)