1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "mozilla/dom/BlobSet.h"
8 #include "mozilla/CheckedInt.h"
9 #include "mozilla/dom/File.h"
10 #include "MemoryBlobImpl.h"
11 #include "MultipartBlobImpl.h"
12 #include "StringBlobImpl.h"
13 
14 namespace mozilla::dom {
15 
AppendVoidPtr(const void * aData,uint32_t aLength)16 nsresult BlobSet::AppendVoidPtr(const void* aData, uint32_t aLength) {
17   NS_ENSURE_ARG_POINTER(aData);
18   if (!aLength) {
19     return NS_OK;
20   }
21 
22   void* data = malloc(aLength);
23   if (!data) {
24     return NS_ERROR_OUT_OF_MEMORY;
25   }
26 
27   memcpy((char*)data, aData, aLength);
28 
29   RefPtr<BlobImpl> blobImpl = new MemoryBlobImpl(data, aLength, u""_ns);
30   return AppendBlobImpl(blobImpl);
31 }
32 
AppendString(const nsAString & aString,bool nativeEOL)33 nsresult BlobSet::AppendString(const nsAString& aString, bool nativeEOL) {
34   nsCString utf8Str;
35   if (NS_WARN_IF(!AppendUTF16toUTF8(aString, utf8Str, mozilla::fallible))) {
36     return NS_ERROR_OUT_OF_MEMORY;
37   }
38 
39   if (nativeEOL) {
40     if (utf8Str.Contains('\r')) {
41       utf8Str.ReplaceSubstring("\r\n", "\n");
42       utf8Str.ReplaceSubstring("\r", "\n");
43     }
44 #ifdef XP_WIN
45     utf8Str.ReplaceSubstring("\n", "\r\n");
46 #endif
47   }
48 
49   RefPtr<StringBlobImpl> blobImpl = StringBlobImpl::Create(utf8Str, u""_ns);
50   return AppendBlobImpl(blobImpl);
51 }
52 
AppendBlobImpl(BlobImpl * aBlobImpl)53 nsresult BlobSet::AppendBlobImpl(BlobImpl* aBlobImpl) {
54   NS_ENSURE_ARG_POINTER(aBlobImpl);
55 
56   // If aBlobImpl is a MultipartBlobImpl, let's append the sub-blobImpls
57   // instead.
58   const nsTArray<RefPtr<BlobImpl>>* subBlobs = aBlobImpl->GetSubBlobImpls();
59   if (subBlobs) {
60     for (BlobImpl* subBlob : *subBlobs) {
61       nsresult rv = AppendBlobImpl(subBlob);
62       if (NS_WARN_IF(NS_FAILED(rv))) {
63         return rv;
64       }
65     }
66 
67     return NS_OK;
68   }
69 
70   if (NS_WARN_IF(!mBlobImpls.AppendElement(aBlobImpl, fallible))) {
71     return NS_ERROR_OUT_OF_MEMORY;
72   }
73   return NS_OK;
74 }
75 
76 }  // namespace mozilla::dom
77