Skip to content

Commit

Permalink
Encode/Decode Extension Addition (QuantConnect#5708)
Browse files Browse the repository at this point in the history
* Implement Encode/Decode Base 64

* Add unit test
  • Loading branch information
C-SELLERS authored Jun 25, 2021
1 parent 5c10b2c commit c7e6c96
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
32 changes: 32 additions & 0 deletions Common/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,38 @@ public static ulong DecodeBase36(this string symbol)
return result;
}

/// <summary>
/// Convert a string to Base64 Encoding
/// </summary>
/// <param name="text">Text to encode</param>
/// <returns>Encoded result</returns>
public static string EncodeBase64(this string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}

byte[] textBytes = Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(textBytes);
}

/// <summary>
/// Decode a Base64 Encoded string
/// </summary>
/// <param name="base64EncodedText">Text to decode</param>
/// <returns>Decoded result</returns>
public static string DecodeBase64(this string base64EncodedText)
{
if (string.IsNullOrEmpty(base64EncodedText))
{
return base64EncodedText;
}

byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedText);
return Encoding.UTF8.GetString(base64EncodedBytes);
}

/// <summary>
/// Lazy string to upper implementation.
/// Will first verify the string is not already upper and avoid
Expand Down
14 changes: 12 additions & 2 deletions Tests/Common/StringExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
Expand Down Expand Up @@ -227,5 +227,15 @@ public void SafeSubstring_ReturnsSubstring_WhenSubstringThrowException(string so
}
Assert.AreEqual(expected, sourceString.SafeSubstring(startIndex, length));
}

[TestCase("test input")]
[TestCase("[ asdd[ \" 12344 :::}")]
public void EncodeDecode64String(string input)
{
var encoded = input.EncodeBase64();
var decoded = encoded.DecodeBase64();

Assert.AreEqual(input, decoded);
}
}
}
}

0 comments on commit c7e6c96

Please sign in to comment.