TextEncoder.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* -*- Mode: C++; tab-width: 8; 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 "mozilla/dom/TextEncoder.h"
  6. #include "mozilla/dom/EncodingUtils.h"
  7. #include "mozilla/UniquePtrExtensions.h"
  8. #include "nsContentUtils.h"
  9. namespace mozilla {
  10. namespace dom {
  11. void
  12. TextEncoder::Init()
  13. {
  14. // Create an encoder object for utf-8.
  15. mEncoder = EncodingUtils::EncoderForEncoding(NS_LITERAL_CSTRING("UTF-8"));
  16. }
  17. void
  18. TextEncoder::Encode(JSContext* aCx,
  19. JS::Handle<JSObject*> aObj,
  20. const nsAString& aString,
  21. JS::MutableHandle<JSObject*> aRetval,
  22. ErrorResult& aRv)
  23. {
  24. // Run the steps of the encoding algorithm.
  25. int32_t srcLen = aString.Length();
  26. int32_t maxLen;
  27. const char16_t* data = aString.BeginReading();
  28. nsresult rv = mEncoder->GetMaxLength(data, srcLen, &maxLen);
  29. if (NS_FAILED(rv)) {
  30. aRv.Throw(rv);
  31. return;
  32. }
  33. // Need a fallible allocator because the caller may be a content
  34. // and the content can specify the length of the string.
  35. auto buf = MakeUniqueFallible<char[]>(maxLen + 1);
  36. if (!buf) {
  37. aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
  38. return;
  39. }
  40. int32_t dstLen = maxLen;
  41. rv = mEncoder->Convert(data, &srcLen, buf.get(), &dstLen);
  42. // Now reset the encoding algorithm state to the default values for encoding.
  43. int32_t finishLen = maxLen - dstLen;
  44. rv = mEncoder->Finish(&buf[dstLen], &finishLen);
  45. if (NS_SUCCEEDED(rv)) {
  46. dstLen += finishLen;
  47. }
  48. JSObject* outView = nullptr;
  49. if (NS_SUCCEEDED(rv)) {
  50. buf[dstLen] = '\0';
  51. JSAutoCompartment ac(aCx, aObj);
  52. outView = Uint8Array::Create(aCx, dstLen,
  53. reinterpret_cast<uint8_t*>(buf.get()));
  54. if (!outView) {
  55. aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
  56. return;
  57. }
  58. }
  59. if (NS_FAILED(rv)) {
  60. aRv.Throw(rv);
  61. }
  62. aRetval.set(outView);
  63. }
  64. void
  65. TextEncoder::GetEncoding(nsAString& aEncoding)
  66. {
  67. aEncoding.AssignLiteral("utf-8");
  68. }
  69. } // namespace dom
  70. } // namespace mozilla