Skip to content

Commit

Permalink
modernizing code. We should really be splitting these into individual…
Browse files Browse the repository at this point in the history
… packages
  • Loading branch information
mariodivece committed Aug 23, 2021
1 parent 83ad3fb commit f7ef048
Show file tree
Hide file tree
Showing 26 changed files with 174 additions and 97 deletions.
2 changes: 1 addition & 1 deletion mail.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ server.on('error', err => {
console.log('Error %s', err.message);
});
server.listen(1030);
console.log('We can now sent emails to port 1030!');
console.log('We can now send emails through port 1030!');
2 changes: 1 addition & 1 deletion src/Swan.Lite/CompositeHashCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public static int Using(params object?[] fields)
{
unchecked
{
return fields.Where(f => !(f is null))
return fields.Where(f => f is not null)
.Aggregate(InitialSeed, (current, field) => (Multiplier * current) + field.GetHashCode());
}
}
Expand Down
51 changes: 37 additions & 14 deletions src/Swan.Lite/Cryptography/Hasher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,21 @@
namespace Swan.Cryptography
{
/// <summary>
/// Use this class to compute a hash in MD4, SHA1, SHA256 or SHA512.
/// Use this class to compute a hash in MD5, SHA1, SHA256 or SHA512.
/// </summary>
public static class Hasher
{
private static readonly Lazy<MD5> Md5Hasher = new(MD5.Create, true);
private static readonly Lazy<SHA1> SHA1Hasher = new(SHA1.Create, true);
private static readonly Lazy<SHA256> SHA256Hasher = new(SHA256.Create, true);
private static readonly Lazy<SHA512> SHA512Hasher = new(SHA512.Create, true);

/// <summary>
/// Computes the MD5 hash of the given stream.
/// Do not use for large streams as this reads ALL bytes at once.
/// </summary>
/// <param name="this">The stream.</param>
/// <param name="createHasher">if set to <c>true</c> [create hasher].</param>
/// <returns>
/// The computed hash code.
/// </returns>
/// <exception cref="ArgumentNullException">stream.</exception>
[Obsolete("Use a better hasher.")]
public static byte[] ComputeMD5(Stream @this, bool createHasher = false)
public static byte[] ComputeMD5(this Stream @this)
{
if (@this == null)
throw new ArgumentNullException(nameof(@this));
Expand All @@ -52,7 +46,7 @@ public static byte[] ComputeMD5(Stream @this, bool createHasher = false)
}
while (readAheadBytesRead != 0);

return md5.Hash;
return md5.Hash ?? Array.Empty<byte>();
}

/// <summary>
Expand All @@ -72,8 +66,17 @@ public static byte[] ComputeMD5(string value, bool createHasher = false) =>
/// <param name="createHasher">if set to <c>true</c> [create hasher].</param>
/// <returns>The computed hash code.</returns>
[Obsolete("Use a better hasher.")]
public static byte[] ComputeMD5(byte[] data, bool createHasher = false) =>
(createHasher ? MD5.Create() : Md5Hasher.Value).ComputeHash(data);
public static byte[] ComputeMD5(byte[] data, bool createHasher = false)
{
if (createHasher)
{
using var hasher = MD5.Create();
hasher.ComputeHash(data);
}

return MD5.HashData(data);
}


/// <summary>
/// Computes the SHA-1 hash of the given string using UTF8 byte encoding.
Expand All @@ -88,7 +91,14 @@ public static byte[] ComputeMD5(byte[] data, bool createHasher = false) =>
public static byte[] ComputeSha1(string @this, bool createHasher = false)
{
var inputBytes = Encoding.UTF8.GetBytes(@this);
return (createHasher ? SHA1.Create() : SHA1Hasher.Value).ComputeHash(inputBytes);

if (createHasher)
{
using var hasher = SHA1.Create();
return hasher.ComputeHash(inputBytes);
}

return SHA1.HashData(inputBytes);
}

/// <summary>
Expand All @@ -103,7 +113,13 @@ public static byte[] ComputeSha1(string @this, bool createHasher = false)
public static byte[] ComputeSha256(string value, bool createHasher = false)
{
var inputBytes = Encoding.UTF8.GetBytes(value);
return (createHasher ? SHA256.Create() : SHA256Hasher.Value).ComputeHash(inputBytes);
if (createHasher)
{
using var hasher = SHA256.Create();
return hasher.ComputeHash(inputBytes);
}

return SHA256.HashData(inputBytes);
}

/// <summary>
Expand All @@ -118,7 +134,14 @@ public static byte[] ComputeSha256(string value, bool createHasher = false)
public static byte[] ComputeSha512(string value, bool createHasher = false)
{
var inputBytes = Encoding.UTF8.GetBytes(value);
return (createHasher ? SHA512.Create() : SHA512Hasher.Value).ComputeHash(inputBytes);

if (createHasher)
{
using var hasher = SHA512.Create();
return hasher.ComputeHash(inputBytes);
}

return SHA512.HashData(inputBytes);
}
}
}
6 changes: 3 additions & 3 deletions src/Swan.Lite/Extensions.ByteArrays.cs
Original file line number Diff line number Diff line change
Expand Up @@ -428,17 +428,17 @@ public static async Task<byte[]> ReadBytesAsync(this Stream stream, long length,

try
{
var buff = new byte[bufferLength];
Memory<byte> buff = new byte[bufferLength];
while (length > 0)
{
if (length < bufferLength)
bufferLength = (int)length;

var read = await stream.ReadAsync(buff, 0, bufferLength, cancellationToken).ConfigureAwait(false);
var read = await stream.ReadAsync(buff, cancellationToken).ConfigureAwait(false);
if (read == 0)
break;

dest.Write(buff, 0, read);
await dest.WriteAsync(buff.Slice(0, bufferLength), cancellationToken);
length -= read;
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/Swan.Lite/Extensions.Dates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,16 +195,16 @@ public static string ToRfc1123String(this DateTime @this)
if (string.IsNullOrWhiteSpace(parts) || parts == "*")
return null;

if (parts.Contains(","))
if (parts.Contains(",", StringComparison.Ordinal))
{
return parts.Split(',').Select(int.Parse).Contains(value);
}

var stop = DateRanges[type];

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

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

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

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

return int.Parse(parts) == value;
return int.Parse(parts, CultureInfo.InvariantCulture) == value;
}
}
}
42 changes: 33 additions & 9 deletions src/Swan.Lite/Extensions.Strings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public static class StringExtensions
return x[0] + " " + x.Substring(1, x.Length - 1);
});

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

#endregion

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

if (@this is string stringValue)
return stringValue;

var itemType = @this.GetType();

if (itemType == typeof(string))
return @this as string ?? string.Empty;
if (Definitions.BasicTypesInfo.Value.TryGetValue(itemType, out var info))
return info.ToStringInvariant(@this);

return Definitions.BasicTypesInfo.Value.ContainsKey(itemType)
? Definitions.BasicTypesInfo.Value[itemType].ToStringInvariant(@this)
: @this.ToString();
return @this.ToString() ?? string.Empty;
}

/// <summary>
Expand Down Expand Up @@ -288,9 +289,32 @@ public static string ToSafeFilename(this string? value) =>
value == null
? throw new ArgumentNullException(nameof(value))
: InvalidFilenameChars.Value
.Aggregate(value, (current, c) => current.Replace(c, string.Empty))
.Aggregate(value, (current, c) => current.RemoveChar(c))
.Slice(0, 220);

/// <summary>
/// Removes all instances of the given character from a string.
/// </summary>
/// <param name="value">The string to be searched.</param>
/// <param name="find">The character to be removed.</param>
/// <returns>The newly-formed string without the given char.</returns>
public static string RemoveChar(this string? value, char find)
{
if (value == null)
throw new ArgumentNullException(nameof(value));

var builder = new StringBuilder(value.Length);
foreach (var c in value)
{
if (c == find)
continue;

builder.Append(c);
}

return builder.ToString();
}

/// <summary>
/// Formats a long into the closest bytes string.
/// </summary>
Expand Down Expand Up @@ -378,7 +402,7 @@ public static bool Contains(this string value, params char[] chars) =>
/// <param name="chars">The chars.</param>
/// <returns>The string with the characters replaced.</returns>
public static string ReplaceAll(this string value, string replaceValue, params char[] chars) =>
chars.Aggregate(value, (current, c) => current.Replace(new string(new[] { c }), replaceValue));
chars.Aggregate(value, (current, c) => current.Replace(new string(c, 1), replaceValue, StringComparison.Ordinal));

/// <summary>
/// Convert hex character to an integer. Return -1 if char is something
Expand Down
12 changes: 6 additions & 6 deletions src/Swan.Lite/Formatters/CsvWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,18 +264,18 @@ public void WriteLine(IEnumerable<string> items)

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

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

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

// Get the bytes to write to the stream and write them
output = _encoding.GetBytes(textValue);
Expand Down
7 changes: 4 additions & 3 deletions src/Swan.Lite/Formatters/HumanizeJson.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

private void AppendString(string stringValue)
{
if (stringValue.Length + _indentStr.Length <= 96 && stringValue.IndexOf('\r') < 0 &&
stringValue.IndexOf('\n') < 0)
if (stringValue.Length + _indentStr.Length <= 96 && !stringValue.Contains('\r', StringComparison.Ordinal) &&
!stringValue.Contains('\n', StringComparison.Ordinal))
{
_builder.Append($"{stringValue}");
return;
Expand Down
4 changes: 2 additions & 2 deletions src/Swan.Lite/Formatters/Json.Deserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,10 @@ private void ExtractValue()
private static string Unescape(string str)
{
// check if we need to unescape at all
if (str.IndexOf(StringEscapeChar) < 0)
if (!str.Contains(StringEscapeChar, StringComparison.Ordinal))
return str;

var builder = new StringBuilder(str.Length);
var builder = new StringBuilder(str.Length * 2);
for (var i = 0; i < str.Length; i++)
{
if (str[i] != StringEscapeChar)
Expand Down
11 changes: 9 additions & 2 deletions src/Swan.Lite/Formatters/Json.Serializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -245,13 +245,20 @@ private string ResolveDictionary(IDictionary items, int depth)
var writeCount = 0;
foreach (var key in items.Keys)
{
var keyName = key is not null
? key.ToString()
: string.Empty;

if (key == null || string.IsNullOrWhiteSpace(keyName))
continue;

// Serialize and append the key (first char indented)
Append(StringQuotedChar, depth + 1);
Escape(key.ToString(), _builder);
Escape(keyName, _builder);
_builder
.Append(StringQuotedChar)
.Append(ValueSeparatorChar)
.Append(" ");
.Append(' ');

// Serialize and append the value
var serializedValue = Serialize(items[key], depth + 1, _options, _excludedNames);
Expand Down
9 changes: 4 additions & 5 deletions src/Swan.Lite/Logging/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -653,11 +653,10 @@ private static void LogMessage(

foreach (var logger in Loggers)
{
Task.Run(() =>
{
if (logger.LogLevel <= logLevel)
logger.Log(eventArgs);
});
if (logLevel < logger.LogLevel)
continue;

_ = Task.Run(() => logger.Log(eventArgs));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Swan.Lite/Mappers/CopyableAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Swan.Mappers
/// </summary>
/// <seealso cref="Attribute" />
[AttributeUsage(AttributeTargets.Property)]
public class CopyableAttribute : Attribute
public sealed class CopyableAttribute : Attribute
{
}
}
2 changes: 1 addition & 1 deletion src/Swan.Lite/Parsers/ArgumentParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ private void ReportIssues(Validator validator)
// TODO: If Enum list values
var shortName = string.IsNullOrWhiteSpace(option.ShortName) ? string.Empty : $"-{option.ShortName}";
var longName = string.IsNullOrWhiteSpace(option.LongName) ? string.Empty : $"--{option.LongName}";
var comma = string.IsNullOrWhiteSpace(shortName) || string.IsNullOrWhiteSpace(longName)
var comma = shortName.Length == 0 || longName.Length == 0
? string.Empty
: ", ";
var defaultValue = option.DefaultValue == null ? string.Empty : $"(Default: {option.DefaultValue}) ";
Expand Down
3 changes: 2 additions & 1 deletion src/Swan.Lite/SingletonBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ public abstract class SingletonBase<T> : IDisposable
/// The static, singleton instance reference.
/// </summary>
protected static readonly Lazy<T> LazyInstance = new(
valueFactory: () => Activator.CreateInstance(typeof(T), true) as T,
valueFactory: () => Activator.CreateInstance(typeof(T), true) as T
?? throw new MissingMethodException(typeof(T).Name, ".ctor"),
isThreadSafe: true);

private bool _isDisposing; // To detect redundant calls
Expand Down
2 changes: 1 addition & 1 deletion src/Swan.Lite/StructEndiannessAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Swan
/// </summary>
/// <seealso cref="Attribute" />
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct)]
public class StructEndiannessAttribute : Attribute
public sealed class StructEndiannessAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="StructEndiannessAttribute"/> class.
Expand Down
Loading

0 comments on commit f7ef048

Please sign in to comment.