Visit Mozilla.org

nsIInputStream:readSegments

From MDC

« XPCOM API Reference

Contents

[edit] Summary

This method provides direct access to the stream's internal buffer.

  [noscript] unsigned long readSegments(
    in nsWriteSegmentFun aWriter,
    in voidPtr aClosure,
    in unsigned long aCount
  );

[edit] Parameters

aWriter
[in] A callback function that may be called once for each buffer segment contained in the stream. See nsWriteSegmentFun for more details on this function.
aClosure
[in] A parameter that is passed to aWriter each time it is called.
aCount
[in] The maximum number of bytes to read from the stream.

[edit] Return Values

This method returns the number of bytes read from the stream. It returns 0 to indicate end-of-file.

[edit] Exceptions Thrown

NS_BASE_STREAM_WOULD_BLOCK
Indicates that reading from the input stream would block the calling thread for indeterminate amount of time. This exception may only be thrown if isNonBlocking returns true.
NS_ERROR_NOT_IMPLEMENTED
Indicates that the stream does not have an internal buffer that can be accessed directly.

[edit] Remarks

A nsIInputStream is not required to implement this method. In some contexts, readSegments may be guaranteed to be implemented, but in general it is not. This method serves as an optimization.

[edit] Example Code

 // Consume all data from an input stream...

 static NS_METHOD AppendSegment(nsIInputStream* aStream,
                                void* aClosure,
                                const char* aFromSegment,
                                PRUint32 aToOffset,
                                PRUint32 aCount,
                                PRUint32* aWriteCount)
 {
   // aFromSegment now contains aCount bytes of data.

   nsACString* pBuf = (nsACString*) aClosure;
   pBuf->Append(aFromSegment, aCount);

   // Indicate that we have consumed all of aFromSegment
   *aWriteCount = aCount;
   return NS_OK;
 }

 // Copy the contents of aStream into aResultBuf as one
 // contiguous buffer.  Use ReadSegments to avoid an intermediate
 // buffer copy.
 nsresult CopyStream(nsIInputStream* aStream, nsACString& aResultBuf)
 {
   PRUint32 numRead;
   return aStream->ReadSegments(AppendSegment, (void*) &aResultBuf,
                                PR_UINT32_MAX, &numRead);
 }

[edit] See Also

isNonBlocking, nsIInputStream, nsWriteSegmentFun