/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "gtest/gtest.h"
#include <algorithm>
#include <stdint.h>
#include <vector>

#include "../ClearKeyBase64.cpp"

using namespace std;

struct B64Test {
  string b64;
  vector<uint8_t> raw;
  bool shouldPass;
};

const B64Test tests[] = {
    {"AAAAADk4AU4AAAAAAAAAAA",
     {0x0, 0x0, 0x0, 0x0, 0x39, 0x38, 0x1, 0x4e, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0},
     true},
    {"h2mqp1zAJjDIC34YXEXBxA==",
     {0x87, 0x69, 0xaa, 0xa7, 0x5c, 0xc0, 0x26, 0x30, 0xc8, 0xb, 0x7e, 0x18,
      0x5c, 0x45, 0xc1, 0xc4},
     true},
    {"flcdA35XHQN-Vx0DflcdAw",
     {0x7e, 0x57, 0x1d, 0x3, 0x7e, 0x57, 0x1d, 0x3, 0x7e, 0x57, 0x1d, 0x3, 0x7e,
      0x57, 0x1d, 0x3},
     true},
    {
        "flczM35XMzN-VzMzflczMw",
        {0x7e, 0x57, 0x33, 0x33, 0x7e, 0x57, 0x33, 0x33, 0x7e, 0x57, 0x33, 0x33,
         0x7e, 0x57, 0x33, 0x33},
        true,
    },
    {"flcdBH5XHQR-Vx0EflcdBA",
     {0x7e, 0x57, 0x1d, 0x4, 0x7e, 0x57, 0x1d, 0x4, 0x7e, 0x57, 0x1d, 0x4, 0x7e,
      0x57, 0x1d, 0x4},
     true},
    {"fldERH5XRER-V0REfldERA",
     {0x7e, 0x57, 0x44, 0x44, 0x7e, 0x57, 0x44, 0x44, 0x7e, 0x57, 0x44, 0x44,
      0x7e, 0x57, 0x44, 0x44},
     true},
    {"fuzzbiz=", {0x7e, 0xec, 0xf3, 0x6e, 0x2c}, true},
    {"fuzzbizfuzzbizfuzzbizfuzzbizfuzzbizfuzzbizfuzzbizfuzzbiz",
     {0x7e, 0xec, 0xf3, 0x6e, 0x2c, 0xdf, 0xbb, 0x3c, 0xdb, 0x8b, 0x37,
      0xee, 0xcf, 0x36, 0xe2, 0xcd, 0xfb, 0xb3, 0xcd, 0xb8, 0xb3, 0x7e,
      0xec, 0xf3, 0x6e, 0x2c, 0xdf, 0xbb, 0x3c, 0xdb, 0x8b, 0x37, 0xee,
      0xcf, 0x36, 0xe2, 0xcd, 0xfb, 0xb3, 0xcd, 0xb8, 0xb3},
     true},
    {"", {}, true},
    {"00", {0xd3}, true},
    {"000", {0xd3, 0x4d}, true},

    {"invalid", {0x8a, 0x7b, 0xda, 0x96, 0x27}, true},
    {"invalic", {0x8a, 0x7b, 0xda, 0x96, 0x27}, true},

    // Failure tests
    {"A", {}, false},  // 1 character is too few.
    {"_", {}, false},  // 1 character is too few.
};

TEST(ClearKey, DecodeBase64)
{
  for (const B64Test& test : tests) {
    vector<uint8_t> v;
    bool rv = DecodeBase64(string(test.b64), v);
    EXPECT_EQ(test.shouldPass, rv);
    if (test.shouldPass) {
      EXPECT_EQ(test.raw.size(), v.size());
      for (size_t k = 0; k < test.raw.size(); k++) {
        EXPECT_EQ(test.raw[k], v[k]);
      }
    }
  }
}
