Bug 1362449 - part 3 - templatify core nsCString base64 encode routine; r=erahm
authorNathan Froyd <froydnj@mozilla.com>
Wed, 06 Sep 2017 16:58:37 -0400
changeset 428873 53447e7c6c29bd0dd8c0352850a83771b49f2c57
parent 428872 014a075a5a0d08447f521b841533bb6b2fc9195d
child 428874 837aaf616d8543ced7aed4ffc98d742c835d30cf
push id7761
push userjlund@mozilla.com
push dateFri, 15 Sep 2017 00:19:52 +0000
treeherdermozilla-beta@c38455951db4 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerserahm
bugs1362449
milestone57.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1362449 - part 3 - templatify core nsCString base64 encode routine; r=erahm The nsACString -> nsACString encode routine has several checks in it for correct operation, and the nsAString -> nsAString encode routine relies on those checks happening via the nsACString -> nsACString routine. Once we start encoding nsAStrings directly, we'll still need those checks, and the easiest way to ensure they happen is to move the core base64 encode logic for strings into a templated helper.
xpcom/io/Base64.cpp
--- a/xpcom/io/Base64.cpp
+++ b/xpcom/io/Base64.cpp
@@ -321,18 +321,19 @@ Base64Encode(const char* aBinary, uint32
 
   Encode(aBinary, aBinaryLen, base64.get());
   base64[base64Len] = '\0';
 
   *aBase64 = base64.release();
   return NS_OK;
 }
 
-nsresult
-Base64Encode(const nsACString& aBinary, nsACString& aBase64)
+template<typename T>
+static nsresult
+Base64EncodeHelper(const T& aBinary, T& aBase64)
 {
   // Check for overflow.
   if (aBinary.Length() > (UINT32_MAX / 4) * 3) {
     return NS_ERROR_FAILURE;
   }
 
   if (aBinary.IsEmpty()) {
     aBase64.Truncate();
@@ -341,25 +342,31 @@ Base64Encode(const nsACString& aBinary, 
 
   uint32_t base64Len = ((aBinary.Length() + 2) / 3) * 4;
 
   // Add one byte for null termination.
   if (!aBase64.SetCapacity(base64Len + 1, fallible)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
-  char* base64 = aBase64.BeginWriting();
+  typename T::char_type* base64 = aBase64.BeginWriting();
   Encode(aBinary.BeginReading(), aBinary.Length(), base64);
   base64[base64Len] = '\0';
 
   aBase64.SetLength(base64Len);
   return NS_OK;
 }
 
 nsresult
+Base64Encode(const nsACString& aBinary, nsACString& aBase64)
+{
+  return Base64EncodeHelper(aBinary, aBase64);
+}
+
+nsresult
 Base64Encode(const nsAString& aBinary, nsAString& aBase64)
 {
   auto truncater = mozilla::MakeScopeExit([&]() { aBase64.Truncate(); });
 
   // XXX We should really consider decoding directly from the string, rather
   // than making a separate copy here.
   nsAutoCString binary;
   if (!binary.SetCapacity(aBinary.Length(), mozilla::fallible)) {