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/. */
7 #include "nsScriptableInputStream.h"
11 NS_IMPL_ISUPPORTS(nsScriptableInputStream
, nsIScriptableInputStream
)
13 // nsIScriptableInputStream methods
15 nsScriptableInputStream::Close()
18 return NS_ERROR_NOT_INITIALIZED
;
20 return mInputStream
->Close();
24 nsScriptableInputStream::Init(nsIInputStream
* aInputStream
)
27 return NS_ERROR_NULL_POINTER
;
29 mInputStream
= aInputStream
;
34 nsScriptableInputStream::Available(uint64_t* aResult
)
37 return NS_ERROR_NOT_INITIALIZED
;
39 return mInputStream
->Available(aResult
);
43 nsScriptableInputStream::Read(uint32_t aCount
, char** aResult
)
47 char* buffer
= nullptr;
50 return NS_ERROR_NOT_INITIALIZED
;
53 rv
= mInputStream
->Available(&count64
);
58 // bug716556 - Ensure count+1 doesn't overflow
60 XPCOM_MIN((uint32_t)XPCOM_MIN
<uint64_t>(count64
, aCount
), UINT32_MAX
- 1);
61 buffer
= (char*)moz_malloc(count
+ 1); // make room for '\0'
63 return NS_ERROR_OUT_OF_MEMORY
;
66 rv
= ReadHelper(buffer
, count
);
68 nsMemory::Free(buffer
);
78 nsScriptableInputStream::ReadBytes(uint32_t aCount
, nsACString
& aResult
)
81 return NS_ERROR_NOT_INITIALIZED
;
84 aResult
.SetLength(aCount
);
85 if (aResult
.Length() != aCount
) {
86 return NS_ERROR_OUT_OF_MEMORY
;
89 char* ptr
= aResult
.BeginWriting();
90 nsresult rv
= ReadHelper(ptr
, aCount
);
98 nsScriptableInputStream::ReadHelper(char* aBuffer
, uint32_t aCount
)
100 uint32_t totalBytesRead
= 0;
103 nsresult rv
= mInputStream
->Read(aBuffer
+ totalBytesRead
,
104 aCount
- totalBytesRead
,
110 totalBytesRead
+= bytesRead
;
111 if (totalBytesRead
== aCount
) {
115 // If we have read zero bytes, we have hit EOF.
116 if (bytesRead
== 0) {
117 return NS_ERROR_FAILURE
;
125 nsScriptableInputStream::Create(nsISupports
* aOuter
, REFNSIID aIID
,
129 return NS_ERROR_NO_AGGREGATION
;
132 nsScriptableInputStream
* sis
= new nsScriptableInputStream();
134 return NS_ERROR_OUT_OF_MEMORY
;
138 nsresult rv
= sis
->QueryInterface(aIID
, aResult
);