Skip to content

Instantly share code, notes, and snippets.

@chakrit
Created September 30, 2010 05:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chakrit/604080 to your computer and use it in GitHub Desktop.
Save chakrit/604080 to your computer and use it in GitHub Desktop.
using System;
namespace TCastr.Models
{
/// <summary>
/// An implicitly-convertible buffer that automatically converts between
/// a compact string representation and a Guid.
/// </summary>
/// <remarks>
/// Reference implementation:
/// http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx
/// </remarks>
public struct CompactGuid
{
private Guid _guid = Guid.Empty;
private string _str = null;
public Guid Guid { get { return this; } }
private CompactGuid() { _guid = Guid.NewGuid(); }
public CompactGuid(string s) { _str = s; }
public CompactGuid(Guid guid) { _guid = guid; }
public static CompactGuid NewGuid()
{
return Guid.NewGuid();
}
public static implicit operator CompactGuid(string source) { return new CompactGuid(source); }
public static implicit operator CompactGuid(Guid source) { return new CompactGuid(source); }
public static implicit operator string(CompactGuid source)
{
return (source._guid != null) ? Encode(source._guid) : source._str;
}
public static implicit operator Guid(CompactGuid source)
{
return (source._guid != null) ? source._guid : Decode(source._str);
}
public static string Encode(Guid guid)
{
return Convert
.ToBase64String(guid.ToByteArray())
.Replace('/', '_')
.Replace('+', '-')
.Substring(0, 22);
}
public static Guid Decode(string sguid)
{
return new Guid(Convert.FromBase64String(sguid
.Replace('-', '+')
.Replace('_', '/')
+ "=="));
}
public override string ToString() { return this; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment