Skip to content

Commit

Permalink
Merge pull request #5 from bolorundurowb/develop
Browse files Browse the repository at this point in the history
release: v2.0.0
  • Loading branch information
Bolorunduro Winner-Timothy B committed Mar 9, 2018
2 parents ae510bf + fe8fd4d commit 2a6542a
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 26 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

## About ShortId

A csharp library to generate completely random short id's. they can be used as primary keys or unique identifiers. This library is different in that you can specify the length of the id's generated. I have tested the application generating 200000 ids without duplicates.
A csharp library to generate completely random short id's. they can be used as primary keys or unique identifiers. This library is different in that you can specify the length of the id's generated. I have tested the application generating 180000 id's without duplicates.

## How to use

Expand Down Expand Up @@ -57,7 +57,7 @@ string id = ShortId.Generate(true, false, 12);
// id = VvoCDPazES_w
```

**NOTE: when specifying the desired length, shorter lengths increase the possibility thata duplicate id would be generated**
**NOTE: v2.0.0 introduced a change that prevents lengths of less than 7**


## Customize ShortId
Expand All @@ -71,7 +71,7 @@ string characters = //whatever you want;
ShortId.SetCharacters(characters);
```

**NOTE: the new character set must number `null`, an empty string or whitespace. Also, all whitespace characters would be removed, finally the character set cannot be less than 20 characters.**
**NOTE: the new character set must not be `null`, an empty string or whitespace. Also, all whitespace characters would be removed, finally the character set cannot be less than 20 characters.**

`ShortId` also allows the seed for the random number generator to be set.

Expand Down
11 changes: 6 additions & 5 deletions shortid.Test/ShortId.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace shortid.Test
public class ShortIdTests
{
[Fact]
public void GenerateIsStable()
public void generatedWithoutExceptions()
{
string id = string.Empty;
Action action = () =>
Expand Down Expand Up @@ -65,7 +65,7 @@ public void SetSeedThrowsWhenCharacterSetIsLessThan20Characters()
ShortId.SetCharacters(seed);
};
action.ShouldThrow<InvalidOperationException>()
.WithMessage("The replacement characters must be at least 20 letters in length and without spaces.");
.WithMessage("The replacement characters must be at least 20 letters in length and without whitespace.");
}

[Fact]
Expand All @@ -79,13 +79,14 @@ public void ResetIsStable()
}

[Fact]
public void SetSeedIsStable()
public void DoesNotAllowLengthsLessThan7()
{
Action action = () =>
{
ShortId.Generate(0);
ShortId.Generate(6);
};
action.ShouldNotThrow();
action.ShouldThrowExactly<ArgumentException>()
.WithMessage("The specified length of 6 is less than the lower limit of 7.");
}
}
}
59 changes: 43 additions & 16 deletions shortid/ShortId.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,21 @@

namespace shortid
{
public class ShortId
public static class ShortId
{
// app variables
private static Random _random = new Random();
private const string Bigs = "ABCDEFGHIJKLMNOPQRSTUVWXY";
private const string Smalls = "abcdefghjlkmnopqrstuvwxyz";
private const string Numbers = "0123456789";
private const string Specials = "-_";
private static string _pool = $"{Smalls}{Bigs}";

// thread management variables
private static readonly object threadLock = new object();

/// <summary>
/// Generates a random string of varying length
/// Generates a random string of varying length with special characters and without numbers
/// </summary>
/// <param name="useNumbers">Whether or not to include numbers</param>
/// <param name="useSpecial">Whether or not special characters are included</param>
Expand All @@ -33,7 +37,21 @@ public static string Generate(bool useNumbers = false, bool useSpecial = true)
/// <returns>A random string</returns>
public static string Generate(bool useNumbers, bool useSpecial, int length)
{
StringBuilder poolBuilder = new StringBuilder(_pool);
if (length < 7)
{
throw new ArgumentException($"The specified length of {length} is less than the lower limit of 7.");
}

string __pool;
Random rand;

lock (threadLock)
{
__pool = _pool;
rand = _random;
}

StringBuilder poolBuilder = new StringBuilder(__pool);
if (useNumbers)
{
poolBuilder.Append(Numbers);
Expand All @@ -48,14 +66,14 @@ public static string Generate(bool useNumbers, bool useSpecial, int length)
char[] output = new char[length];
for (int i = 0; i < length; i++)
{
int charIndex = _random.Next(0, pool.Length);
int charIndex = rand.Next(0, pool.Length);
output[i] = pool[charIndex];
}
return new string(output);
}

/// <summary>
/// Generates a random string of a specified length
/// Generates a random string of a specified length with special characetrs and without numbers
/// </summary>
/// <param name="length">The length of the generated string</param>
/// <returns>A random string</returns>
Expand All @@ -76,18 +94,21 @@ public static void SetCharacters(string characters)
throw new ArgumentException("The replacement characters must not be null or empty.");
}

characters = characters
.Replace(" ", "")
.Replace("\t", "")
.Replace("\n", "")
.Replace("\r", "");
var stringBuilder = new StringBuilder();
foreach (var character in characters)
{
if (!char.IsWhiteSpace(character)) {
stringBuilder.Append(character);
}
}

if (characters.Length < 20)
if (stringBuilder.Length < 20)
{
throw new InvalidOperationException(
"The replacement characters must be at least 20 letters in length and without spaces.");
"The replacement characters must be at least 20 letters in length and without whitespace.");
}
_pool = characters;

_pool = stringBuilder.ToString();
}

/// <summary>
Expand All @@ -96,16 +117,22 @@ public static void SetCharacters(string characters)
/// <param name="seed">The seed for the random number generator</param>
public static void SetSeed(int seed)
{
_random = new Random(seed);
lock (threadLock)
{
_random = new Random(seed);
}
}

/// <summary>
/// Resets the random number generator and character set
/// </summary>
public static void Reset()
{
_random = new Random();
_pool = $"{Smalls}{Bigs}";
lock (threadLock)
{
_random = new Random();
_pool = $"{Smalls}{Bigs}";
}
}
}
}
4 changes: 2 additions & 2 deletions shortid/shortid.csproj
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard1.3;net45;net40</TargetFrameworks>
<Version>1.0.4</Version>
<Version>2.0.0</Version>
<Copyright>Copyright 2017</Copyright>
<PackageLicenseUrl>https://github.com/bolorundurowb/shortid/blob/master/LICENSE</PackageLicenseUrl>
<PackageProjectUrl>https://github.com/bolorundurowb/shortid/</PackageProjectUrl>
<PackageIconUrl>https://members.orcid.org/sites/default/files/vector_iD_icon.svg</PackageIconUrl>
<RepositoryUrl>https://github.com/bolorundurowb/shortid/</RepositoryUrl>
<PackageTags>shortid short id databse key primarykey mongodb sql</PackageTags>
<PackageReleaseNotes>Add memory optimizing changes</PackageReleaseNotes>
<PackageReleaseNotes>add thread safety and minimum length</PackageReleaseNotes>
<Authors>Bolorunduro Winner-Timothy</Authors>
<Description>A library that generates random Id's from 7 to 14 characters. Id's generated can be used as primary keys for databases or unique identifiers</Description>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
Expand Down

0 comments on commit 2a6542a

Please sign in to comment.