Bug 1769952 - Fix running raptor on a Win10-64 VM r=sparky
[gecko.git] / dom / system / IOUtils.h
blob570d4fc87d5bd96b99e7f6e345b523b27dadf9f4
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 #ifndef mozilla_dom_IOUtils__
8 #define mozilla_dom_IOUtils__
10 #include "js/Utility.h"
11 #include "mozilla/AlreadyAddRefed.h"
12 #include "mozilla/Attributes.h"
13 #include "mozilla/Buffer.h"
14 #include "mozilla/DataMutex.h"
15 #include "mozilla/MozPromise.h"
16 #include "mozilla/Result.h"
17 #include "mozilla/StaticPtr.h"
18 #include "mozilla/dom/BindingDeclarations.h"
19 #include "mozilla/dom/IOUtilsBinding.h"
20 #include "mozilla/dom/TypedArray.h"
21 #include "nsIAsyncShutdown.h"
22 #include "nsISerialEventTarget.h"
23 #include "nsPrintfCString.h"
24 #include "nsProxyRelease.h"
25 #include "nsString.h"
26 #include "nsStringFwd.h"
27 #include "nsTArray.h"
28 #include "prio.h"
30 class nsFileStream;
32 namespace mozilla {
34 /**
35 * Utility class to be used with |UniquePtr| to automatically close NSPR file
36 * descriptors when they go out of scope.
38 * Example:
40 * UniquePtr<PRFileDesc, PR_CloseDelete> fd = PR_Open(path, flags, mode);
42 class PR_CloseDelete {
43 public:
44 constexpr PR_CloseDelete() = default;
45 PR_CloseDelete(const PR_CloseDelete& aOther) = default;
46 PR_CloseDelete(PR_CloseDelete&& aOther) = default;
47 PR_CloseDelete& operator=(const PR_CloseDelete& aOther) = default;
48 PR_CloseDelete& operator=(PR_CloseDelete&& aOther) = default;
50 void operator()(PRFileDesc* aPtr) const { PR_Close(aPtr); }
53 namespace dom {
55 /**
56 * Implementation for the Web IDL interface at dom/chrome-webidl/IOUtils.webidl.
57 * Methods of this class must only be called from the parent process.
59 class IOUtils final {
60 public:
61 class IOError;
63 static already_AddRefed<Promise> Read(GlobalObject& aGlobal,
64 const nsAString& aPath,
65 const ReadOptions& aOptions,
66 ErrorResult& aError);
68 static already_AddRefed<Promise> ReadUTF8(GlobalObject& aGlobal,
69 const nsAString& aPath,
70 const ReadUTF8Options& aOptions,
71 ErrorResult& aError);
73 static already_AddRefed<Promise> ReadJSON(GlobalObject& aGlobal,
74 const nsAString& aPath,
75 const ReadUTF8Options& aOptions,
76 ErrorResult& aError);
78 static already_AddRefed<Promise> Write(GlobalObject& aGlobal,
79 const nsAString& aPath,
80 const Uint8Array& aData,
81 const WriteOptions& aOptions,
82 ErrorResult& aError);
84 static already_AddRefed<Promise> WriteUTF8(GlobalObject& aGlobal,
85 const nsAString& aPath,
86 const nsACString& aString,
87 const WriteOptions& aOptions,
88 ErrorResult& aError);
90 static already_AddRefed<Promise> WriteJSON(GlobalObject& aGlobal,
91 const nsAString& aPath,
92 JS::Handle<JS::Value> aValue,
93 const WriteOptions& aOptions,
94 ErrorResult& aError);
96 static already_AddRefed<Promise> Move(GlobalObject& aGlobal,
97 const nsAString& aSourcePath,
98 const nsAString& aDestPath,
99 const MoveOptions& aOptions,
100 ErrorResult& aError);
102 static already_AddRefed<Promise> Remove(GlobalObject& aGlobal,
103 const nsAString& aPath,
104 const RemoveOptions& aOptions,
105 ErrorResult& aError);
107 static already_AddRefed<Promise> MakeDirectory(
108 GlobalObject& aGlobal, const nsAString& aPath,
109 const MakeDirectoryOptions& aOptions, ErrorResult& aError);
111 static already_AddRefed<Promise> Stat(GlobalObject& aGlobal,
112 const nsAString& aPath,
113 ErrorResult& aError);
115 static already_AddRefed<Promise> Copy(GlobalObject& aGlobal,
116 const nsAString& aSourcePath,
117 const nsAString& aDestPath,
118 const CopyOptions& aOptions,
119 ErrorResult& aError);
121 static already_AddRefed<Promise> SetModificationTime(
122 GlobalObject& aGlobal, const nsAString& aPath,
123 const Optional<int64_t>& aModification, ErrorResult& aError);
125 static already_AddRefed<Promise> GetChildren(
126 GlobalObject& aGlobal, const nsAString& aPath,
127 const GetChildrenOptions& aOptions, ErrorResult& aError);
129 static already_AddRefed<Promise> SetPermissions(GlobalObject& aGlobal,
130 const nsAString& aPath,
131 uint32_t aPermissions,
132 const bool aHonorUmask,
133 ErrorResult& aError);
135 static already_AddRefed<Promise> Exists(GlobalObject& aGlobal,
136 const nsAString& aPath,
137 ErrorResult& aError);
139 static already_AddRefed<Promise> CreateUniqueFile(GlobalObject& aGlobal,
140 const nsAString& aParent,
141 const nsAString& aPrefix,
142 const uint32_t aPermissions,
143 ErrorResult& aError);
144 static already_AddRefed<Promise> CreateUniqueDirectory(
145 GlobalObject& aGlobal, const nsAString& aParent, const nsAString& aPrefix,
146 const uint32_t aPermissions, ErrorResult& aError);
148 private:
150 * A helper method for CreateUniqueFile and CreateUniqueDirectory.
152 static already_AddRefed<Promise> CreateUnique(GlobalObject& aGlobal,
153 const nsAString& aParent,
154 const nsAString& aPrefix,
155 const uint32_t aFileType,
156 const uint32_t aPermissions,
157 ErrorResult& aError);
159 public:
160 #if defined(XP_WIN)
161 static already_AddRefed<Promise> GetWindowsAttributes(GlobalObject& aGlobal,
162 const nsAString& aPath,
163 ErrorResult& aError);
165 static already_AddRefed<Promise> SetWindowsAttributes(
166 GlobalObject& aGlobal, const nsAString& aPath,
167 const mozilla::dom::WindowsFileAttributes& aAttrs, ErrorResult& aError);
168 #elif defined(XP_MACOSX)
169 static already_AddRefed<Promise> HasMacXAttr(GlobalObject& aGlobal,
170 const nsAString& aPath,
171 const nsACString& aAttr,
172 ErrorResult& aError);
173 static already_AddRefed<Promise> GetMacXAttr(GlobalObject& aGlobal,
174 const nsAString& aPath,
175 const nsACString& aAttr,
176 ErrorResult& aError);
177 static already_AddRefed<Promise> SetMacXAttr(GlobalObject& aGlobal,
178 const nsAString& aPath,
179 const nsACString& aAttr,
180 const Uint8Array& aValue,
181 ErrorResult& aError);
182 static already_AddRefed<Promise> DelMacXAttr(GlobalObject& aGlobal,
183 const nsAString& aPath,
184 const nsACString& aAttr,
185 ErrorResult& aError);
186 #endif
188 static void GetProfileBeforeChange(GlobalObject& aGlobal,
189 JS::MutableHandle<JS::Value>,
190 ErrorResult& aRv);
192 static RefPtr<SyncReadFile> OpenFileForSyncReading(GlobalObject& aGlobal,
193 const nsAString& aPath,
194 ErrorResult& aRv);
196 class JsBuffer;
199 * The kind of buffer to allocate.
201 * This controls what kind of JS object (a JSString or a Uint8Array) is
202 * returned by |ToJSValue()|.
204 enum class BufferKind {
205 String,
206 Uint8Array,
209 private:
210 ~IOUtils() = default;
212 template <typename T>
213 using IOPromise = MozPromise<T, IOError, true>;
215 friend class IOUtilsShutdownBlocker;
216 struct InternalFileInfo;
217 struct InternalWriteOpts;
218 class MozLZ4;
219 class EventQueue;
220 class State;
222 template <typename Fn>
223 static already_AddRefed<Promise> WithPromiseAndState(GlobalObject& aGlobal,
224 ErrorResult& aError,
225 Fn aFn);
228 * Dispatch a task on the event queue and resolve or reject the associated
229 * promise based on the result.
231 * NB: If the calling thread is a worker, this function takes care of keepting
232 * it alive until the |IOPromise| can complete.
234 * @param aPromise The promise corresponding to the task running on the event
235 * queue.
236 * @param aFunc The task to run.
238 template <typename OkT, typename Fn>
239 static void DispatchAndResolve(EventQueue* aQueue, Promise* aPromise,
240 Fn aFunc);
243 * Creates a new JS Promise.
245 * @return The new promise, or |nullptr| on failure.
247 static already_AddRefed<Promise> CreateJSPromise(GlobalObject& aGlobal,
248 ErrorResult& aError);
250 // Allow conversion of |InternalFileInfo| with |ToJSValue|.
251 friend bool ToJSValue(JSContext* aCx,
252 const InternalFileInfo& aInternalFileInfo,
253 JS::MutableHandle<JS::Value> aValue);
256 * Attempts to read the entire file at |aPath| into a buffer.
258 * @param aFile The location of the file.
259 * @param aOffset The offset to start reading from.
260 * @param aMaxBytes If |Some|, then only read up this this number of bytes,
261 * otherwise attempt to read the whole file.
262 * @param aDecompress If true, decompress the bytes read from disk before
263 * returning the result to the caller.
264 * @param aBufferKind The kind of buffer to allocate.
266 * @return A buffer containing the entire (decompressed) file contents, or an
267 * error.
269 static Result<JsBuffer, IOError> ReadSync(nsIFile* aFile,
270 const uint64_t aOffset,
271 const Maybe<uint32_t> aMaxBytes,
272 const bool aDecompress,
273 BufferKind aBufferKind);
276 * Attempts to read the entire file at |aPath| as a UTF-8 string.
278 * @param aFile The location of the file.
279 * @param aDecompress If true, decompress the bytes read from disk before
280 * returning the result to the caller.
282 * @return The (decompressed) contents of the file re-encoded as a UTF-16
283 * string.
285 static Result<JsBuffer, IOError> ReadUTF8Sync(nsIFile* aFile,
286 const bool aDecompress);
289 * Attempt to write the entirety of |aByteArray| to the file at |aPath|.
290 * This may occur by writing to an intermediate destination and performing a
291 * move, depending on |aOptions|.
293 * @param aFile The location of the file.
294 * @param aByteArray The data to write to the file.
295 * @param aOptions Options to modify the way the write is completed.
297 * @return The number of bytes written to the file, or an error if the write
298 * failed or was incomplete.
300 static Result<uint32_t, IOError> WriteSync(
301 nsIFile* aFile, const Span<const uint8_t>& aByteArray,
302 const InternalWriteOpts& aOptions);
305 * Attempts to move the file located at |aSourceFile| to |aDestFile|.
307 * @param aSourceFile The location of the file to move.
308 * @param aDestFile The destination for the file.
309 * @param aNoOverWrite If true, abort with an error if a file already exists
310 * at |aDestFile|. Otherwise, the file will be overwritten by the move.
312 * @return Ok if the file was moved successfully, or an error.
314 static Result<Ok, IOError> MoveSync(nsIFile* aSourceFile, nsIFile* aDestFile,
315 bool aNoOverwrite);
318 * Attempts to copy the file at |aSourceFile| to |aDestFile|.
320 * @param aSourceFile The location of the file to copy.
321 * @param aDestFile The destination that the file will be copied to.
323 * @return Ok if the operation was successful, or an error.
325 static Result<Ok, IOError> CopySync(nsIFile* aSourceFile, nsIFile* aDestFile,
326 bool aNoOverWrite, bool aRecursive);
329 * Provides the implementation for |CopySync| and |MoveSync|.
331 * @param aMethod A pointer to one of |nsIFile::MoveTo| or |CopyTo|
332 * instance methods.
333 * @param aMethodName The name of the method to the performed. Either "move"
334 * or "copy".
335 * @param aSource The source file to be copied or moved.
336 * @param aDest The destination file.
337 * @param aNoOverwrite If true, allow overwriting |aDest| during the copy or
338 * move. Otherwise, abort with an error if the file would
339 * be overwritten.
341 * @return Ok if the operation was successful, or an error.
343 template <typename CopyOrMoveFn>
344 static Result<Ok, IOError> CopyOrMoveSync(CopyOrMoveFn aMethod,
345 const char* aMethodName,
346 nsIFile* aSource, nsIFile* aDest,
347 bool aNoOverwrite);
350 * Attempts to remove the file located at |aFile|.
352 * @param aFile The location of the file.
353 * @param aIgnoreAbsent If true, suppress errors due to an absent target file.
354 * @param aRecursive If true, attempt to recursively remove descendant
355 * files. This option is safe to use even if the target
356 * is not a directory.
358 * @return Ok if the file was removed successfully, or an error.
360 static Result<Ok, IOError> RemoveSync(nsIFile* aFile, bool aIgnoreAbsent,
361 bool aRecursive);
364 * Attempts to create a new directory at |aFile|.
366 * @param aFile The location of the directory to create.
367 * @param aCreateAncestors If true, create missing ancestor directories as
368 * needed. Otherwise, report an error if the target
369 * has non-existing ancestor directories.
370 * @param aIgnoreExisting If true, suppress errors that occur if the target
371 * directory already exists. Otherwise, propagate the
372 * error if it occurs.
373 * @param aMode Optional file mode. Defaults to 0777 to allow the
374 * system umask to compute the best mode for the new
375 * directory.
377 * @return Ok if the directory was created successfully, or an error.
379 static Result<Ok, IOError> MakeDirectorySync(nsIFile* aFile,
380 bool aCreateAncestors,
381 bool aIgnoreExisting,
382 int32_t aMode = 0777);
385 * Attempts to stat a file at |aFile|.
387 * @param aFile The location of the file.
389 * @return An |InternalFileInfo| struct if successful, or an error.
391 static Result<IOUtils::InternalFileInfo, IOError> StatSync(nsIFile* aFile);
394 * Attempts to update the last modification time of the file at |aFile|.
396 * @param aFile The location of the file.
397 * @param aNewModTime Some value in milliseconds since Epoch. For the current
398 * system time, use |Nothing|.
400 * @return Timestamp of the file if the operation was successful, or an error.
402 static Result<int64_t, IOError> SetModificationTimeSync(
403 nsIFile* aFile, const Maybe<int64_t>& aNewModTime);
406 * Returns the immediate children of the directory at |aFile|, if any.
408 * @param aFile The location of the directory.
410 * @return An array of absolute paths identifying the children of |aFile|.
411 * If there are no children, an empty array. Otherwise, an error.
413 static Result<nsTArray<nsString>, IOError> GetChildrenSync(
414 nsIFile* aFile, bool aIgnoreAbsent);
417 * Set the permissions of the given file.
419 * Windows does not make a distinction between user, group, and other
420 * permissions like UNICES do. If a permission flag is set for any of user,
421 * group, or other has a permission, then all users will have that
422 * permission.
424 * @param aFile The location of the file.
425 * @param aPermissions The permissions to set, as a UNIX file mode.
427 * @return |Ok| if the permissions were successfully set, or an error.
429 static Result<Ok, IOError> SetPermissionsSync(nsIFile* aFile,
430 const uint32_t aPermissions);
433 * Return whether or not the file exists.
435 * @param aFile The location of the file.
437 * @return Whether or not the file exists.
439 static Result<bool, IOError> ExistsSync(nsIFile* aFile);
442 * Create a file or directory with a unique path.
444 * @param aFile The location of the file or directory (including prefix)
445 * @param aFileType One of |nsIFile::NORMAL_FILE_TYPE| or
446 * |nsIFile::DIRECTORY_TYPE|.
447 * @param aperms The permissions to create the file or directory with.
449 * @return A unique path.
451 static Result<nsString, IOError> CreateUniqueSync(
452 nsIFile* aFile, const uint32_t aFileType, const uint32_t aPermissions);
454 #if defined(XP_WIN)
456 * Return the Windows-specific attributes of the file.
458 * @param aFile The location of the file.
460 * @return The Windows-specific attributes of the file.
462 static Result<uint32_t, IOError> GetWindowsAttributesSync(nsIFile* aFile);
465 * Set the Windows-specific attributes of the file.
467 * @param aFile The location of the file.
468 * @param aAttrs The attributes to set on the file.
470 * @return |Ok| if the attributes were successfully set, or an error.
472 static Result<Ok, IOError> SetWindowsAttributesSync(
473 nsIFile* aFile, const uint32_t aSetAttrs, const uint32_t aClearAttrs);
474 #elif defined(XP_MACOSX)
475 static Result<bool, IOError> HasMacXAttrSync(nsIFile* aFile,
476 const nsCString& aAttr);
477 static Result<nsTArray<uint8_t>, IOError> GetMacXAttrSync(
478 nsIFile* aFile, const nsCString& aAttr);
479 static Result<Ok, IOError> SetMacXAttrSync(nsIFile* aFile,
480 const nsCString& aAttr,
481 const nsTArray<uint8_t>& aValue);
482 static Result<Ok, IOError> DelMacXAttrSync(nsIFile* aFile,
483 const nsCString& aAttr);
484 #endif
486 enum class EventQueueStatus {
487 Uninitialized,
488 Initialized,
489 Shutdown,
492 enum class ShutdownBlockerStatus {
493 Uninitialized,
494 Initialized,
495 Failed,
499 * Internal IOUtils state.
501 class State {
502 public:
503 StaticAutoPtr<EventQueue> mEventQueue;
504 EventQueueStatus mQueueStatus = EventQueueStatus::Uninitialized;
505 ShutdownBlockerStatus mBlockerStatus = ShutdownBlockerStatus::Uninitialized;
508 * Set up shutdown hooks to free our internals at shutdown.
510 * NB: Must be called on main thread.
512 void SetShutdownHooks();
515 using StateMutex = StaticDataMutex<State>;
518 * Lock the state mutex and return a handle. If shutdown has not yet
519 * finished, the internals will be constructed if necessary.
521 * @returns A handle to the internal state, which can be used to retrieve the
522 * event queue.
523 * If |Some| is returned, |mEventQueue| is guaranteed to be
524 * initialized. If shutdown has finished, |Nothing| is returned.
526 static Maybe<StateMutex::AutoLock> GetState();
528 static StateMutex sState;
532 * The IOUtils event queue.
534 class IOUtils::EventQueue final {
535 friend void IOUtils::State::SetShutdownHooks();
537 public:
538 EventQueue();
540 EventQueue(const EventQueue&) = delete;
541 EventQueue(EventQueue&&) = delete;
542 EventQueue& operator=(const EventQueue&) = delete;
543 EventQueue& operator=(EventQueue&&) = delete;
546 * Dispatch a task on the event queue.
548 * NB: If using this directly from |IOUtils| instead of
549 * |IOUtils::DispatchAndResolve| *and* the calling thread is a worker, you
550 * *must* take care to keep the worker thread alive until the |IOPromise|
551 * resolves or rejects. See the implementation of
552 * |IOUtils::DispatchAndResolve| or |IOUtils::GetWindowsAttributes| for an
553 * example.
555 * @param aFunc The task to dispatch on the event queue.
557 * @return A promise that resolves to the task's return value or rejects with
558 * an error.
560 template <typename OkT, typename Fn>
561 RefPtr<IOPromise<OkT>> Dispatch(Fn aFunc);
563 Result<already_AddRefed<nsIAsyncShutdownClient>, nsresult>
564 GetProfileBeforeChangeClient();
566 Result<already_AddRefed<nsIAsyncShutdownBarrier>, nsresult>
567 GetProfileBeforeChangeBarrier();
569 private:
570 nsresult SetShutdownHooks();
572 nsCOMPtr<nsISerialEventTarget> mBackgroundEventTarget;
573 nsCOMPtr<nsIAsyncShutdownBarrier> mProfileBeforeChangeBarrier;
577 * An error class used with the |Result| type returned by most private |IOUtils|
578 * methods.
580 class IOUtils::IOError {
581 public:
582 MOZ_IMPLICIT IOError(nsresult aCode) : mCode(aCode), mMessage(Nothing()) {}
585 * Replaces the message associated with this error.
587 template <typename... Args>
588 IOError WithMessage(const char* const aMessage, Args... aArgs) {
589 mMessage.emplace(nsPrintfCString(aMessage, aArgs...));
590 return *this;
592 IOError WithMessage(const char* const aMessage) {
593 mMessage.emplace(nsCString(aMessage));
594 return *this;
596 IOError WithMessage(const nsCString& aMessage) {
597 mMessage.emplace(aMessage);
598 return *this;
602 * Returns the |nsresult| associated with this error.
604 nsresult Code() const { return mCode; }
607 * Maybe returns a message associated with this error.
609 const Maybe<nsCString>& Message() const { return mMessage; }
611 private:
612 nsresult mCode;
613 Maybe<nsCString> mMessage;
617 * This is an easier to work with representation of a |mozilla::dom::FileInfo|
618 * for private use in the IOUtils implementation.
620 * Because web IDL dictionaries are not easily copy/moveable, this class is
621 * used instead, until converted to the proper |mozilla::dom::FileInfo| before
622 * returning any results to JavaScript.
624 struct IOUtils::InternalFileInfo {
625 nsString mPath;
626 FileType mType = FileType::Other;
627 uint64_t mSize = 0;
628 uint64_t mLastModified = 0;
629 Maybe<uint64_t> mCreationTime;
630 uint32_t mPermissions = 0;
634 * This is an easier to work with representation of a
635 * |mozilla::dom::WriteOptions| for private use in the |IOUtils|
636 * implementation.
638 * Because web IDL dictionaries are not easily copy/moveable, this class is
639 * used instead.
641 struct IOUtils::InternalWriteOpts {
642 RefPtr<nsIFile> mBackupFile;
643 RefPtr<nsIFile> mTmpFile;
644 WriteMode mMode;
645 bool mFlush = false;
646 bool mCompress = false;
648 static Result<InternalWriteOpts, IOUtils::IOError> FromBinding(
649 const WriteOptions& aOptions);
653 * Re-implements the file compression and decompression utilities found
654 * in toolkit/components/lz4/lz4.js
656 * This implementation uses the non-standard data layout:
658 * - MAGIC_NUMBER (8 bytes)
659 * - content size (uint32_t, little endian)
660 * - content, as obtained from mozilla::Compression::LZ4::compress
662 * See bug 1209390 for more info.
664 class IOUtils::MozLZ4 {
665 public:
666 static constexpr std::array<uint8_t, 8> MAGIC_NUMBER{
667 {'m', 'o', 'z', 'L', 'z', '4', '0', '\0'}};
669 static const uint32_t HEADER_SIZE = 8 + sizeof(uint32_t);
672 * Compresses |aUncompressed| byte array, and returns a byte array with the
673 * correct format whose contents may be written to disk.
675 static Result<nsTArray<uint8_t>, IOError> Compress(
676 Span<const uint8_t> aUncompressed);
679 * Checks |aFileContents| for the correct file header, and returns the
680 * decompressed content.
682 static Result<IOUtils::JsBuffer, IOError> Decompress(
683 Span<const uint8_t> aFileContents, IOUtils::BufferKind);
686 class IOUtilsShutdownBlocker : public nsIAsyncShutdownBlocker,
687 public nsIAsyncShutdownCompletionCallback {
688 public:
689 NS_DECL_THREADSAFE_ISUPPORTS
690 NS_DECL_NSIASYNCSHUTDOWNBLOCKER
691 NS_DECL_NSIASYNCSHUTDOWNCOMPLETIONCALLBACK
693 enum Phase {
694 ProfileBeforeChange,
695 XpcomWillShutdown,
698 explicit IOUtilsShutdownBlocker(Phase aPhase) : mPhase(aPhase) {}
700 private:
701 virtual ~IOUtilsShutdownBlocker() = default;
703 Phase mPhase;
704 RefPtr<nsIAsyncShutdownClient> mParentClient;
708 * A buffer that is allocated inside one of JS heaps so that it can be converted
709 * to a JSString or Uint8Array object with at most one copy in the worst case.
711 class IOUtils::JsBuffer final {
712 public:
714 * Create a new buffer of the given kind with the requested capacity.
716 * @param aBufferKind The kind of buffer to create (either a string or an
717 * array).
718 * @param aCapacity The capacity of the buffer.
720 * @return Either a successfully created buffer or an error if it could not be
721 * allocated.
723 static Result<JsBuffer, IOUtils::IOError> Create(
724 IOUtils::BufferKind aBufferKind, size_t aCapacity);
727 * Create a new, empty buffer.
729 * This operation cannot fail.
731 * @param aBufferKind The kind of buffer to create (either a string or an
732 * array).
734 * @return An empty JsBuffer.
736 static JsBuffer CreateEmpty(IOUtils::BufferKind aBufferKind);
738 JsBuffer(const JsBuffer&) = delete;
739 JsBuffer(JsBuffer&& aOther) noexcept;
740 JsBuffer& operator=(const JsBuffer&) = delete;
741 JsBuffer& operator=(JsBuffer&& aOther) noexcept;
743 size_t Length() { return mLength; }
744 char* Elements() { return mBuffer.get(); }
745 void SetLength(size_t aNewLength) {
746 MOZ_RELEASE_ASSERT(aNewLength <= mCapacity);
747 mLength = aNewLength;
751 * Return a span for writing to the buffer.
753 * |SetLength| should be called after the buffer has been written to.
755 * @returns A span for writing to. The size of the span is the entire
756 * allocated capacity.
758 Span<char> BeginWriting() {
759 MOZ_RELEASE_ASSERT(mBuffer.get());
760 return Span(mBuffer.get(), mCapacity);
764 * Return a span for reading from.
766 * @returns A span for reading form. The size of the span is the set length
767 * of the buffer.
769 Span<const char> BeginReading() const {
770 MOZ_RELEASE_ASSERT(mBuffer.get() || mLength == 0);
771 return Span(mBuffer.get(), mLength);
775 * Consume the JsBuffer and convert it into a JSString.
777 * NOTE: This method asserts the buffer was allocated as a string buffer.
779 * @param aBuffer The buffer to convert to a string. After this call, the
780 * buffer will be invaldated and |IntoString| cannot be called
781 * again.
783 * @returns A JSString with the contents of |aBuffer|.
785 static JSString* IntoString(JSContext* aCx, JsBuffer aBuffer);
788 * Consume the JsBuffer and convert it into a Uint8Array.
790 * NOTE: This method asserts the buffer was allocated as an array buffer.
792 * @param aBuffer The buffer to convert to an array. After this call, the
793 * buffer will be invalidated and |IntoUint8Array| cannot be
794 * called again.
796 * @returns A JSBuffer
798 static JSObject* IntoUint8Array(JSContext* aCx, JsBuffer aBuffer);
800 friend bool ToJSValue(JSContext* aCx, JsBuffer&& aBuffer,
801 JS::MutableHandle<JS::Value> aValue);
803 private:
804 IOUtils::BufferKind mBufferKind;
805 size_t mCapacity;
806 size_t mLength;
807 JS::UniqueChars mBuffer;
809 JsBuffer(BufferKind aBufferKind, size_t aCapacity);
812 class SyncReadFile : public nsISupports, public nsWrapperCache {
813 public:
814 SyncReadFile(nsISupports* aParent, RefPtr<nsFileStream>&& aStream,
815 int64_t aSize);
817 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
818 NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(SyncReadFile)
820 nsISupports* GetParentObject() const { return mParent; }
822 virtual JSObject* WrapObject(JSContext* aCx,
823 JS::Handle<JSObject*> aGivenProto) override;
825 int64_t Size() const { return mSize; }
826 void ReadBytesInto(const Uint8Array&, const int64_t, ErrorResult& aRv);
827 void Close();
829 private:
830 virtual ~SyncReadFile();
832 nsCOMPtr<nsISupports> mParent;
833 RefPtr<nsFileStream> mStream;
834 int64_t mSize = 0;
837 } // namespace dom
838 } // namespace mozilla
840 #endif