TestBase64Stream.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "gtest/gtest.h"
  6. #include "mozilla/Base64.h"
  7. #include "nsIInputStream.h"
  8. namespace mozilla {
  9. namespace net {
  10. // An input stream whose ReadSegments method calls aWriter with writes of size
  11. // aStep from the provided aInput in order to test edge-cases related to small
  12. // buffers.
  13. class TestStream final : public nsIInputStream {
  14. public:
  15. NS_DECL_ISUPPORTS;
  16. TestStream(const nsACString& aInput, uint32_t aStep)
  17. : mInput(aInput), mStep(aStep) {}
  18. NS_IMETHOD Close() override { MOZ_CRASH("This should not be called"); }
  19. NS_IMETHOD Available(uint64_t* aLength) override {
  20. *aLength = mInput.Length() - mPos;
  21. return NS_OK;
  22. }
  23. NS_IMETHOD Read(char* aBuffer, uint32_t aCount,
  24. uint32_t* aReadCount) override {
  25. MOZ_CRASH("This should not be called");
  26. }
  27. NS_IMETHOD ReadSegments(nsWriteSegmentFun aWriter, void* aClosure,
  28. uint32_t aCount, uint32_t* aResult) override {
  29. *aResult = 0;
  30. if (mPos == mInput.Length()) {
  31. return NS_OK;
  32. }
  33. while (aCount > 0) {
  34. uint32_t amt = std::min(mStep, (uint32_t)(mInput.Length() - mPos));
  35. uint32_t read = 0;
  36. nsresult rv =
  37. aWriter(this, aClosure, mInput.get() + mPos, *aResult, amt, &read);
  38. if (NS_WARN_IF(NS_FAILED(rv))) {
  39. return rv;
  40. }
  41. *aResult += read;
  42. aCount -= read;
  43. mPos += read;
  44. }
  45. return NS_OK;
  46. }
  47. NS_IMETHOD IsNonBlocking(bool* aNonBlocking) override {
  48. *aNonBlocking = true;
  49. return NS_OK;
  50. }
  51. private:
  52. ~TestStream() = default;
  53. nsCString mInput;
  54. const uint32_t mStep;
  55. uint32_t mPos = 0;
  56. };
  57. NS_IMPL_ISUPPORTS(TestStream, nsIInputStream)
  58. // Test the base64 encoder with writer buffer sizes between 1 byte and the
  59. // entire length of "Hello World!" in order to exercise various edge cases.
  60. TEST(TestBase64Stream, Run)
  61. {
  62. nsCString input;
  63. input.AssignLiteral("Hello World!");
  64. for (uint32_t step = 1; step <= input.Length(); ++step) {
  65. RefPtr<TestStream> ts = new TestStream(input, step);
  66. nsAutoString encodedData;
  67. nsresult rv = Base64EncodeInputStream(ts, encodedData, input.Length());
  68. ASSERT_TRUE(NS_SUCCEEDED(rv));
  69. EXPECT_TRUE(encodedData.EqualsLiteral("SGVsbG8gV29ybGQh"));
  70. }
  71. }
  72. } // namespace net
  73. } // namespace mozilla