Skip to content

Commit f7ef048

Browse files
committed
modernizing code. We should really be splitting these into individual packages
1 parent 83ad3fb commit f7ef048

26 files changed

+174
-97
lines changed

mail.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,4 @@ server.on('error', err => {
2323
console.log('Error %s', err.message);
2424
});
2525
server.listen(1030);
26-
console.log('We can now sent emails to port 1030!');
26+
console.log('We can now send emails through port 1030!');

src/Swan.Lite/CompositeHashCode.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ public static int Using(params object?[] fields)
9090
{
9191
unchecked
9292
{
93-
return fields.Where(f => !(f is null))
93+
return fields.Where(f => f is not null)
9494
.Aggregate(InitialSeed, (current, field) => (Multiplier * current) + field.GetHashCode());
9595
}
9696
}

src/Swan.Lite/Cryptography/Hasher.cs

+37-14
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,21 @@
66
namespace Swan.Cryptography
77
{
88
/// <summary>
9-
/// Use this class to compute a hash in MD4, SHA1, SHA256 or SHA512.
9+
/// Use this class to compute a hash in MD5, SHA1, SHA256 or SHA512.
1010
/// </summary>
1111
public static class Hasher
1212
{
13-
private static readonly Lazy<MD5> Md5Hasher = new(MD5.Create, true);
14-
private static readonly Lazy<SHA1> SHA1Hasher = new(SHA1.Create, true);
15-
private static readonly Lazy<SHA256> SHA256Hasher = new(SHA256.Create, true);
16-
private static readonly Lazy<SHA512> SHA512Hasher = new(SHA512.Create, true);
17-
1813
/// <summary>
1914
/// Computes the MD5 hash of the given stream.
2015
/// Do not use for large streams as this reads ALL bytes at once.
2116
/// </summary>
2217
/// <param name="this">The stream.</param>
23-
/// <param name="createHasher">if set to <c>true</c> [create hasher].</param>
2418
/// <returns>
2519
/// The computed hash code.
2620
/// </returns>
2721
/// <exception cref="ArgumentNullException">stream.</exception>
2822
[Obsolete("Use a better hasher.")]
29-
public static byte[] ComputeMD5(Stream @this, bool createHasher = false)
23+
public static byte[] ComputeMD5(this Stream @this)
3024
{
3125
if (@this == null)
3226
throw new ArgumentNullException(nameof(@this));
@@ -52,7 +46,7 @@ public static byte[] ComputeMD5(Stream @this, bool createHasher = false)
5246
}
5347
while (readAheadBytesRead != 0);
5448

55-
return md5.Hash;
49+
return md5.Hash ?? Array.Empty<byte>();
5650
}
5751

5852
/// <summary>
@@ -72,8 +66,17 @@ public static byte[] ComputeMD5(string value, bool createHasher = false) =>
7266
/// <param name="createHasher">if set to <c>true</c> [create hasher].</param>
7367
/// <returns>The computed hash code.</returns>
7468
[Obsolete("Use a better hasher.")]
75-
public static byte[] ComputeMD5(byte[] data, bool createHasher = false) =>
76-
(createHasher ? MD5.Create() : Md5Hasher.Value).ComputeHash(data);
69+
public static byte[] ComputeMD5(byte[] data, bool createHasher = false)
70+
{
71+
if (createHasher)
72+
{
73+
using var hasher = MD5.Create();
74+
hasher.ComputeHash(data);
75+
}
76+
77+
return MD5.HashData(data);
78+
}
79+
7780

7881
/// <summary>
7982
/// Computes the SHA-1 hash of the given string using UTF8 byte encoding.
@@ -88,7 +91,14 @@ public static byte[] ComputeMD5(byte[] data, bool createHasher = false) =>
8891
public static byte[] ComputeSha1(string @this, bool createHasher = false)
8992
{
9093
var inputBytes = Encoding.UTF8.GetBytes(@this);
91-
return (createHasher ? SHA1.Create() : SHA1Hasher.Value).ComputeHash(inputBytes);
94+
95+
if (createHasher)
96+
{
97+
using var hasher = SHA1.Create();
98+
return hasher.ComputeHash(inputBytes);
99+
}
100+
101+
return SHA1.HashData(inputBytes);
92102
}
93103

94104
/// <summary>
@@ -103,7 +113,13 @@ public static byte[] ComputeSha1(string @this, bool createHasher = false)
103113
public static byte[] ComputeSha256(string value, bool createHasher = false)
104114
{
105115
var inputBytes = Encoding.UTF8.GetBytes(value);
106-
return (createHasher ? SHA256.Create() : SHA256Hasher.Value).ComputeHash(inputBytes);
116+
if (createHasher)
117+
{
118+
using var hasher = SHA256.Create();
119+
return hasher.ComputeHash(inputBytes);
120+
}
121+
122+
return SHA256.HashData(inputBytes);
107123
}
108124

109125
/// <summary>
@@ -118,7 +134,14 @@ public static byte[] ComputeSha256(string value, bool createHasher = false)
118134
public static byte[] ComputeSha512(string value, bool createHasher = false)
119135
{
120136
var inputBytes = Encoding.UTF8.GetBytes(value);
121-
return (createHasher ? SHA512.Create() : SHA512Hasher.Value).ComputeHash(inputBytes);
137+
138+
if (createHasher)
139+
{
140+
using var hasher = SHA512.Create();
141+
return hasher.ComputeHash(inputBytes);
142+
}
143+
144+
return SHA512.HashData(inputBytes);
122145
}
123146
}
124147
}

src/Swan.Lite/Extensions.ByteArrays.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -428,17 +428,17 @@ public static async Task<byte[]> ReadBytesAsync(this Stream stream, long length,
428428

429429
try
430430
{
431-
var buff = new byte[bufferLength];
431+
Memory<byte> buff = new byte[bufferLength];
432432
while (length > 0)
433433
{
434434
if (length < bufferLength)
435435
bufferLength = (int)length;
436436

437-
var read = await stream.ReadAsync(buff, 0, bufferLength, cancellationToken).ConfigureAwait(false);
437+
var read = await stream.ReadAsync(buff, cancellationToken).ConfigureAwait(false);
438438
if (read == 0)
439439
break;
440440

441-
dest.Write(buff, 0, read);
441+
await dest.WriteAsync(buff.Slice(0, bufferLength), cancellationToken);
442442
length -= read;
443443
}
444444
}

src/Swan.Lite/Extensions.Dates.cs

+7-7
Original file line numberDiff line numberDiff line change
@@ -195,16 +195,16 @@ public static string ToRfc1123String(this DateTime @this)
195195
if (string.IsNullOrWhiteSpace(parts) || parts == "*")
196196
return null;
197197

198-
if (parts.Contains(","))
198+
if (parts.Contains(",", StringComparison.Ordinal))
199199
{
200200
return parts.Split(',').Select(int.Parse).Contains(value);
201201
}
202202

203203
var stop = DateRanges[type];
204204

205-
if (parts.Contains("/"))
205+
if (parts.Contains("/", StringComparison.Ordinal))
206206
{
207-
var multiple = int.Parse(parts.Split('/').Last());
207+
var multiple = int.Parse(parts.Split('/').Last(), CultureInfo.InvariantCulture);
208208
var start = type is "dayOfMonth" or "month" ? 1 : 0;
209209

210210
for (var i = start; i <= stop; i += multiple)
@@ -213,11 +213,11 @@ public static string ToRfc1123String(this DateTime @this)
213213
return false;
214214
}
215215

216-
if (parts.Contains("-"))
216+
if (parts.Contains("-", StringComparison.Ordinal))
217217
{
218218
var range = parts.Split('-');
219-
var start = int.Parse(range.First());
220-
stop = Math.Max(stop, int.Parse(range.Last()));
219+
var start = int.Parse(range.First(), CultureInfo.InvariantCulture);
220+
stop = Math.Max(stop, int.Parse(range.Last(), CultureInfo.InvariantCulture));
221221

222222
if ((type is "dayOfMonth" or "month") && start == 0)
223223
start = 1;
@@ -228,7 +228,7 @@ public static string ToRfc1123String(this DateTime @this)
228228
return false;
229229
}
230230

231-
return int.Parse(parts) == value;
231+
return int.Parse(parts, CultureInfo.InvariantCulture) == value;
232232
}
233233
}
234234
}

src/Swan.Lite/Extensions.Strings.cs

+33-9
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ public static class StringExtensions
3434
return x[0] + " " + x.Substring(1, x.Length - 1);
3535
});
3636

37-
private static readonly Lazy<string[]> InvalidFilenameChars =
38-
new(() => Path.GetInvalidFileNameChars().Select(c => c.ToStringInvariant()).ToArray());
37+
private static readonly Lazy<char[]> InvalidFilenameChars =
38+
new(() => Path.GetInvalidFileNameChars().ToArray());
3939

4040
#endregion
4141

@@ -51,14 +51,15 @@ public static string ToStringInvariant(this object? @this)
5151
if (@this == null)
5252
return string.Empty;
5353

54+
if (@this is string stringValue)
55+
return stringValue;
56+
5457
var itemType = @this.GetType();
5558

56-
if (itemType == typeof(string))
57-
return @this as string ?? string.Empty;
59+
if (Definitions.BasicTypesInfo.Value.TryGetValue(itemType, out var info))
60+
return info.ToStringInvariant(@this);
5861

59-
return Definitions.BasicTypesInfo.Value.ContainsKey(itemType)
60-
? Definitions.BasicTypesInfo.Value[itemType].ToStringInvariant(@this)
61-
: @this.ToString();
62+
return @this.ToString() ?? string.Empty;
6263
}
6364

6465
/// <summary>
@@ -288,9 +289,32 @@ public static string ToSafeFilename(this string? value) =>
288289
value == null
289290
? throw new ArgumentNullException(nameof(value))
290291
: InvalidFilenameChars.Value
291-
.Aggregate(value, (current, c) => current.Replace(c, string.Empty))
292+
.Aggregate(value, (current, c) => current.RemoveChar(c))
292293
.Slice(0, 220);
293294

295+
/// <summary>
296+
/// Removes all instances of the given character from a string.
297+
/// </summary>
298+
/// <param name="value">The string to be searched.</param>
299+
/// <param name="find">The character to be removed.</param>
300+
/// <returns>The newly-formed string without the given char.</returns>
301+
public static string RemoveChar(this string? value, char find)
302+
{
303+
if (value == null)
304+
throw new ArgumentNullException(nameof(value));
305+
306+
var builder = new StringBuilder(value.Length);
307+
foreach (var c in value)
308+
{
309+
if (c == find)
310+
continue;
311+
312+
builder.Append(c);
313+
}
314+
315+
return builder.ToString();
316+
}
317+
294318
/// <summary>
295319
/// Formats a long into the closest bytes string.
296320
/// </summary>
@@ -378,7 +402,7 @@ public static bool Contains(this string value, params char[] chars) =>
378402
/// <param name="chars">The chars.</param>
379403
/// <returns>The string with the characters replaced.</returns>
380404
public static string ReplaceAll(this string value, string replaceValue, params char[] chars) =>
381-
chars.Aggregate(value, (current, c) => current.Replace(new string(new[] { c }), replaceValue));
405+
chars.Aggregate(value, (current, c) => current.Replace(new string(c, 1), replaceValue, StringComparison.Ordinal));
382406

383407
/// <summary>
384408
/// Convert hex character to an integer. Return -1 if char is something

src/Swan.Lite/Formatters/CsvWriter.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -264,18 +264,18 @@ public void WriteLine(IEnumerable<string> items)
264264

265265
// Determine if we need the string to be enclosed
266266
// (it either contains an escape, new line, or separator char)
267-
needsEnclosing = textValue.IndexOf(SeparatorCharacter) >= 0
268-
|| textValue.IndexOf(EscapeCharacter) >= 0
269-
|| textValue.IndexOf('\r') >= 0
270-
|| textValue.IndexOf('\n') >= 0;
267+
needsEnclosing = textValue.Contains(SeparatorCharacter, StringComparison.Ordinal)
268+
|| textValue.Contains(EscapeCharacter, StringComparison.Ordinal)
269+
|| textValue.Contains('\r', StringComparison.Ordinal)
270+
|| textValue.Contains('\n', StringComparison.Ordinal);
271271

272272
// Escape the escape characters by repeating them twice for every instance
273273
textValue = textValue.Replace($"{EscapeCharacter}",
274-
$"{EscapeCharacter}{EscapeCharacter}");
274+
$"{EscapeCharacter}{EscapeCharacter}", StringComparison.Ordinal);
275275

276276
// Enclose the text value if we need to
277277
if (needsEnclosing)
278-
textValue = string.Format($"{EscapeCharacter}{textValue}{EscapeCharacter}", textValue);
278+
textValue = $"{EscapeCharacter}{textValue}{EscapeCharacter}";
279279

280280
// Get the bytes to write to the stream and write them
281281
output = _encoding.GetBytes(textValue);

src/Swan.Lite/Formatters/HumanizeJson.cs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System.Collections.Generic;
1+
using System;
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Text;
45

@@ -126,8 +127,8 @@ private void AppendList(IEnumerable<object> objects)
126127

127128
private void AppendString(string stringValue)
128129
{
129-
if (stringValue.Length + _indentStr.Length <= 96 && stringValue.IndexOf('\r') < 0 &&
130-
stringValue.IndexOf('\n') < 0)
130+
if (stringValue.Length + _indentStr.Length <= 96 && !stringValue.Contains('\r', StringComparison.Ordinal) &&
131+
!stringValue.Contains('\n', StringComparison.Ordinal))
131132
{
132133
_builder.Append($"{stringValue}");
133134
return;

src/Swan.Lite/Formatters/Json.Deserializer.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,10 @@ private void ExtractValue()
166166
private static string Unescape(string str)
167167
{
168168
// check if we need to unescape at all
169-
if (str.IndexOf(StringEscapeChar) < 0)
169+
if (!str.Contains(StringEscapeChar, StringComparison.Ordinal))
170170
return str;
171171

172-
var builder = new StringBuilder(str.Length);
172+
var builder = new StringBuilder(str.Length * 2);
173173
for (var i = 0; i < str.Length; i++)
174174
{
175175
if (str[i] != StringEscapeChar)

src/Swan.Lite/Formatters/Json.Serializer.cs

+9-2
Original file line numberDiff line numberDiff line change
@@ -245,13 +245,20 @@ private string ResolveDictionary(IDictionary items, int depth)
245245
var writeCount = 0;
246246
foreach (var key in items.Keys)
247247
{
248+
var keyName = key is not null
249+
? key.ToString()
250+
: string.Empty;
251+
252+
if (key == null || string.IsNullOrWhiteSpace(keyName))
253+
continue;
254+
248255
// Serialize and append the key (first char indented)
249256
Append(StringQuotedChar, depth + 1);
250-
Escape(key.ToString(), _builder);
257+
Escape(keyName, _builder);
251258
_builder
252259
.Append(StringQuotedChar)
253260
.Append(ValueSeparatorChar)
254-
.Append(" ");
261+
.Append(' ');
255262

256263
// Serialize and append the value
257264
var serializedValue = Serialize(items[key], depth + 1, _options, _excludedNames);

src/Swan.Lite/Logging/Logger.cs

+4-5
Original file line numberDiff line numberDiff line change
@@ -653,11 +653,10 @@ private static void LogMessage(
653653

654654
foreach (var logger in Loggers)
655655
{
656-
Task.Run(() =>
657-
{
658-
if (logger.LogLevel <= logLevel)
659-
logger.Log(eventArgs);
660-
});
656+
if (logLevel < logger.LogLevel)
657+
continue;
658+
659+
_ = Task.Run(() => logger.Log(eventArgs));
661660
}
662661
}
663662
}

src/Swan.Lite/Mappers/CopyableAttribute.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace Swan.Mappers
77
/// </summary>
88
/// <seealso cref="Attribute" />
99
[AttributeUsage(AttributeTargets.Property)]
10-
public class CopyableAttribute : Attribute
10+
public sealed class CopyableAttribute : Attribute
1111
{
1212
}
1313
}

src/Swan.Lite/Parsers/ArgumentParser.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ private void ReportIssues(Validator validator)
232232
// TODO: If Enum list values
233233
var shortName = string.IsNullOrWhiteSpace(option.ShortName) ? string.Empty : $"-{option.ShortName}";
234234
var longName = string.IsNullOrWhiteSpace(option.LongName) ? string.Empty : $"--{option.LongName}";
235-
var comma = string.IsNullOrWhiteSpace(shortName) || string.IsNullOrWhiteSpace(longName)
235+
var comma = shortName.Length == 0 || longName.Length == 0
236236
? string.Empty
237237
: ", ";
238238
var defaultValue = option.DefaultValue == null ? string.Empty : $"(Default: {option.DefaultValue}) ";

src/Swan.Lite/SingletonBase.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ public abstract class SingletonBase<T> : IDisposable
1313
/// The static, singleton instance reference.
1414
/// </summary>
1515
protected static readonly Lazy<T> LazyInstance = new(
16-
valueFactory: () => Activator.CreateInstance(typeof(T), true) as T,
16+
valueFactory: () => Activator.CreateInstance(typeof(T), true) as T
17+
?? throw new MissingMethodException(typeof(T).Name, ".ctor"),
1718
isThreadSafe: true);
1819

1920
private bool _isDisposing; // To detect redundant calls

src/Swan.Lite/StructEndiannessAttribute.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace Swan
88
/// </summary>
99
/// <seealso cref="Attribute" />
1010
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct)]
11-
public class StructEndiannessAttribute : Attribute
11+
public sealed class StructEndiannessAttribute : Attribute
1212
{
1313
/// <summary>
1414
/// Initializes a new instance of the <see cref="StructEndiannessAttribute"/> class.

0 commit comments

Comments
 (0)