Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/Ulid.Tests/Ulid.New.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,43 @@ public void New_MonotonicRandom_ShouldOverflowToTimestamp(
Assert.Equal(new byte[10], ulid2.Random.ToArray());
}

[Fact]
public void New_WithLongerBytes_ShouldUseFirst16Bytes()
{
// Arrange
var bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

// Act
var ulid = Ulid.New(bytes);

// Assert
Assert.Equal(bytes[..16], ulid.ToByteArray());
}

[Theory]
[InlineData(0)]
[InlineData(5)]
[InlineData(15)]
public void New_WithTooShortBytes_ShouldThrowArgumentException(int length)
{
// Arrange
var bytes = new byte[length];

// Act & Assert
Assert.Throws<ArgumentException>("bytes", () => Ulid.New(bytes));
}

[Fact]
public void DefaultGenerationOptions_SetNull_ShouldThrowArgumentNullException()
{
// Arrange
var original = Ulid.DefaultGenerationOptions;

// Act & Assert
Assert.Throws<ArgumentNullException>("value", () => Ulid.DefaultGenerationOptions = null!);
Assert.Same(original, Ulid.DefaultGenerationOptions);
}

[Fact]
public void New_Monotonic_ShouldRemainUniqueWhenGeneratedConcurrently()
{
Expand Down
14 changes: 14 additions & 0 deletions src/Ulid.Tests/Ulid.String.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@ public void ToString_ShouldReturnExpectedString()
Assert.Equal(_goodUlidString, result);
}

[Fact]
public void Parse_NullString_ShouldThrowArgumentNullException()
{
Assert.Throws<ArgumentNullException>("s", () => Ulid.Parse((string)null!));
Assert.Throws<ArgumentNullException>(() => (Ulid)(string)null!);
}

[Fact]
public void TryParse_NullString_ShouldReturnFalse()
{
Assert.False(Ulid.TryParse((string?)null, null, out var ulid));
Assert.Equal(default, ulid);
}

[Fact]
public void Parse_ValidString_ShouldReturnUlid()
{
Expand Down
27 changes: 24 additions & 3 deletions src/Ulid/Ulid.New.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,35 @@ public readonly partial struct Ulid
/// incremented scenarios during the generation of the ULID. Modifying this property
/// affects the global default behavior for ULID generation across the application.
/// </remarks>
public static GenerationOptions DefaultGenerationOptions { get; set; } = new();
/// <exception cref="ArgumentNullException">Thrown when setting the value to <c>null</c>.</exception>
public static GenerationOptions DefaultGenerationOptions
{
get;
set => field = value ?? throw new ArgumentNullException(nameof(value), "The default generation options cannot be null.");
} = new();

// Constant for Unix Epoch (1970-01-01 UTC) in Ticks
private const long _unixEpochTicks = 621355968000000000;

/// <summary>
/// Initializes a new instance of the <see cref="Ulid"/> struct using the specified byte array.
/// </summary>
/// <param name="bytes">The byte array to initialize the <see cref="Ulid"/> with.</param>
/// <param name="bytes">
/// The bytes to initialize the <see cref="Ulid"/> with, in the same order as <see cref="AsByteSpan"/> returns them.<br/>
/// Must be at least 16 bytes long. If it is longer, only the first 16 bytes are used.
/// </param>
/// <returns>Given bytes as an <see cref="Ulid"/> instance.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="bytes"/> is shorter than 16 bytes.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Ulid New(ReadOnlySpan<byte> bytes)
=> MemoryMarshal.Read<Ulid>(bytes);
{
if (bytes.Length < _ulidSize)
{
ThrowBytesTooShort();
}

return MemoryMarshal.Read<Ulid>(bytes);
}

/// <summary>
/// Creates a new <see cref="Ulid"/> with the current timestamp.
Expand Down Expand Up @@ -133,6 +149,11 @@ ref MemoryMarshal.GetReference(random),
return ulid;
}

[DoesNotReturn]
[SuppressMessage("ReSharper", "NotResolvedInText")]
private static void ThrowBytesTooShort()
=> throw new ArgumentException($"The bytes must be at least {_ulidSize} bytes long.", "bytes");

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
[SuppressMessage("ReSharper", "NotResolvedInText")]
Expand Down
17 changes: 16 additions & 1 deletion src/Ulid/Ulid.String.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,10 +260,24 @@ private static void ThrowInvalidFormat()
/// <param name="provider">Ignored. The ULID is always formatted in its canonical Crockford's Base32 format.</param>
/// <returns>A new <see cref="Ulid"/> instance parsed from the specified string.</returns>
/// <inheritdoc cref="IsValid(string)" path="/remarks"/>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="s"/> is <c>null</c>.</exception>
/// <exception cref="FormatException">Thrown if the input string is not a valid ULID string representation.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Ulid Parse(string s, IFormatProvider? provider = null)
=> Parse(s.AsSpan(), provider);
{
if (s is null)
{
ThrowNullString();
}

return Parse(s.AsSpan(), provider);
}

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
[SuppressMessage("ReSharper", "NotResolvedInText")]
private static void ThrowNullString()
=> throw new ArgumentNullException("s");

/// <summary>
/// Attempts to parse a string representation of a ULID into a <see cref="Ulid"/> instance.
Expand Down Expand Up @@ -414,6 +428,7 @@ private void Fill<T>(Span<T> span, T[] map) where T : unmanaged
/// </summary>
/// <param name="str">The ULID string representation. See <see cref="Parse(string, IFormatProvider)"/>.</param>
/// <returns>The parsed <see cref="Ulid"/>.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is <c>null</c>.</exception>
/// <exception cref="FormatException">Thrown if <paramref name="str"/> is not a valid ULID string representation.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Ulid(string str) => Parse(str);
Expand Down
Loading