From ad0c31080fc5cef21bbda94927a5887e29b92935 Mon Sep 17 00:00:00 2001 From: Kris Maglione Date: Sun, 14 May 2017 15:54:12 -0700 Subject: [PATCH] Bug 1364768: Part 1 - Add NetUtil.readInputStream helper. r=aswan MozReview-Commit-ID: IZRvdcIiV4z --HG-- extra : rebase_source : e209f70d27f32ed0a073b7dc6c07bdcd1cfffdb7 --- netwerk/base/NetUtil.jsm | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/netwerk/base/NetUtil.jsm b/netwerk/base/NetUtil.jsm index e970c8ad8111..d7bfca2cad71 100644 --- a/netwerk/base/NetUtil.jsm +++ b/netwerk/base/NetUtil.jsm @@ -25,6 +25,9 @@ const PR_UINT32_MAX = 0xffffffff; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); Components.utils.import("resource://gre/modules/Services.jsm"); +const BinaryInputStream = Components.Constructor("@mozilla.org/binaryinputstream;1", + "nsIBinaryInputStream", "setInputStream"); + //////////////////////////////////////////////////////////////////////////////// //// NetUtil Object @@ -447,6 +450,43 @@ this.NetUtil = { } }, + /** + * Reads aCount bytes from aInputStream into a string. + * + * @param {nsIInputStream} aInputStream + * The input stream to read from. + * @param {integer} [aCount = aInputStream.available()] + * The number of bytes to read from the stream. + * + * @return the bytes from the input stream in string form. + * + * @throws NS_ERROR_INVALID_ARG if aInputStream is not an nsIInputStream. + * @throws NS_BASE_STREAM_WOULD_BLOCK if reading from aInputStream would + * block the calling thread (non-blocking mode only). + * @throws NS_ERROR_FAILURE if there are not enough bytes available to read + * aCount amount of data. + */ + readInputStream(aInputStream, aCount) + { + if (!(aInputStream instanceof Ci.nsIInputStream)) { + let exception = new Components.Exception( + "First argument should be an nsIInputStream", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + throw exception; + } + + if (!aCount) { + aCount = aInputStream.available(); + } + + let stream = new BinaryInputStream(aInputStream); + let result = new ArrayBuffer(aCount); + stream.readArrayBuffer(result.byteLength, result); + return result; + }, + /** * Returns a reference to nsIIOService. *