1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is Mozilla Communicator client code, released
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 1998-1999
21 * the Initial Developer. All Rights Reserved.
25 * Alternatively, the contents of this file may be used under the terms of
26 * either of the GNU General Public License Version 2 or later (the "GPL"),
27 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
37 * ***** END LICENSE BLOCK ***** */
40 * This file contains implementations of the nsIBinaryInputStream and
41 * nsIBinaryOutputStream interfaces. Together, these interfaces allows reading
42 * and writing of primitive data types (integers, floating-point values,
43 * booleans, etc.) to a stream in a binary, untagged, fixed-endianness format.
44 * This might be used, for example, to implement network protocols or to
45 * produce architecture-neutral binary disk files, i.e. ones that can be read
46 * and written by both big-endian and little-endian platforms. Output is
47 * written in big-endian order (high-order byte first), as this is traditional
50 * @See nsIBinaryInputStream
51 * @See nsIBinaryOutputStream
54 #include "nsBinaryStream.h"
56 #include "nsIStreamBufferAccess.h"
59 #include "nsGenericFactory.h"
61 #include "nsISerializable.h"
62 #include "nsIClassInfo.h"
63 #include "nsComponentManagerUtils.h"
65 NS_IMPL_ISUPPORTS3(nsBinaryOutputStream
, nsIObjectOutputStream
, nsIBinaryOutputStream
, nsIOutputStream
)
68 nsBinaryOutputStream::Flush()
70 NS_ENSURE_STATE(mOutputStream
);
71 return mOutputStream
->Flush();
75 nsBinaryOutputStream::Close()
77 NS_ENSURE_STATE(mOutputStream
);
78 return mOutputStream
->Close();
82 nsBinaryOutputStream::Write(const char *aBuf
, PRUint32 aCount
, PRUint32
*aActualBytes
)
84 NS_ENSURE_STATE(mOutputStream
);
85 return mOutputStream
->Write(aBuf
, aCount
, aActualBytes
);
89 nsBinaryOutputStream::WriteFrom(nsIInputStream
*inStr
, PRUint32 count
, PRUint32
*_retval
)
91 NS_NOTREACHED("WriteFrom");
92 return NS_ERROR_NOT_IMPLEMENTED
;
96 nsBinaryOutputStream::WriteSegments(nsReadSegmentFun reader
, void * closure
, PRUint32 count
, PRUint32
*_retval
)
98 NS_NOTREACHED("WriteSegments");
99 return NS_ERROR_NOT_IMPLEMENTED
;
103 nsBinaryOutputStream::IsNonBlocking(PRBool
*aNonBlocking
)
105 NS_ENSURE_STATE(mOutputStream
);
106 return mOutputStream
->IsNonBlocking(aNonBlocking
);
110 nsBinaryOutputStream::WriteFully(const char *aBuf
, PRUint32 aCount
)
112 NS_ENSURE_STATE(mOutputStream
);
115 PRUint32 bytesWritten
;
117 rv
= mOutputStream
->Write(aBuf
, aCount
, &bytesWritten
);
118 if (NS_FAILED(rv
)) return rv
;
119 if (bytesWritten
!= aCount
)
120 return NS_ERROR_FAILURE
;
125 nsBinaryOutputStream::SetOutputStream(nsIOutputStream
*aOutputStream
)
127 NS_ENSURE_ARG_POINTER(aOutputStream
);
128 mOutputStream
= aOutputStream
;
129 mBufferAccess
= do_QueryInterface(aOutputStream
);
134 nsBinaryOutputStream::WriteBoolean(PRBool aBoolean
)
136 return Write8(aBoolean
);
140 nsBinaryOutputStream::Write8(PRUint8 aByte
)
142 return WriteFully((const char*)&aByte
, sizeof aByte
);
146 nsBinaryOutputStream::Write16(PRUint16 a16
)
148 a16
= NS_SWAP16(a16
);
149 return WriteFully((const char*)&a16
, sizeof a16
);
153 nsBinaryOutputStream::Write32(PRUint32 a32
)
155 a32
= NS_SWAP32(a32
);
156 return WriteFully((const char*)&a32
, sizeof a32
);
160 nsBinaryOutputStream::Write64(PRUint64 a64
)
163 PRUint32 bytesWritten
;
165 a64
= NS_SWAP64(a64
);
166 rv
= Write(reinterpret_cast<char*>(&a64
), sizeof a64
, &bytesWritten
);
167 if (NS_FAILED(rv
)) return rv
;
168 if (bytesWritten
!= sizeof a64
)
169 return NS_ERROR_FAILURE
;
174 nsBinaryOutputStream::WriteFloat(float aFloat
)
176 NS_ASSERTION(sizeof(float) == sizeof (PRUint32
),
177 "False assumption about sizeof(float)");
178 return Write32(*reinterpret_cast<PRUint32
*>(&aFloat
));
182 nsBinaryOutputStream::WriteDouble(double aDouble
)
184 NS_ASSERTION(sizeof(double) == sizeof(PRUint64
),
185 "False assumption about sizeof(double)");
186 return Write64(*reinterpret_cast<PRUint64
*>(&aDouble
));
190 nsBinaryOutputStream::WriteStringZ(const char *aString
)
195 length
= strlen(aString
);
196 rv
= Write32(length
);
197 if (NS_FAILED(rv
)) return rv
;
198 return WriteFully(aString
, length
);
202 nsBinaryOutputStream::WriteWStringZ(const PRUnichar
* aString
)
204 PRUint32 length
, byteCount
;
207 length
= nsCRT::strlen(aString
);
208 rv
= Write32(length
);
209 if (NS_FAILED(rv
)) return rv
;
213 byteCount
= length
* sizeof(PRUnichar
);
216 rv
= WriteBytes(reinterpret_cast<const char*>(aString
), byteCount
);
218 // XXX use WriteSegments here to avoid copy!
219 PRUnichar
*copy
, temp
[64];
223 copy
= reinterpret_cast<PRUnichar
*>(nsMemory::Alloc(byteCount
));
225 return NS_ERROR_OUT_OF_MEMORY
;
227 NS_ASSERTION((PRUptrdiff(aString
) & 0x1) == 0, "aString not properly aligned");
228 for (PRUint32 i
= 0; i
< length
; i
++)
229 copy
[i
] = NS_SWAP16(aString
[i
]);
230 rv
= WriteBytes(reinterpret_cast<const char*>(copy
), byteCount
);
232 nsMemory::Free(copy
);
239 nsBinaryOutputStream::WriteUtf8Z(const PRUnichar
* aString
)
241 return WriteStringZ(NS_ConvertUTF16toUTF8(aString
).get());
245 nsBinaryOutputStream::WriteBytes(const char *aString
, PRUint32 aLength
)
248 PRUint32 bytesWritten
;
250 rv
= Write(aString
, aLength
, &bytesWritten
);
251 if (NS_FAILED(rv
)) return rv
;
252 if (bytesWritten
!= aLength
)
253 return NS_ERROR_FAILURE
;
258 nsBinaryOutputStream::WriteByteArray(PRUint8
*aBytes
, PRUint32 aLength
)
260 return WriteBytes(reinterpret_cast<char *>(aBytes
), aLength
);
264 nsBinaryOutputStream::WriteObject(nsISupports
* aObject
, PRBool aIsStrongRef
)
266 return WriteCompoundObject(aObject
, NS_GET_IID(nsISupports
),
271 nsBinaryOutputStream::WriteSingleRefObject(nsISupports
* aObject
)
273 return WriteCompoundObject(aObject
, NS_GET_IID(nsISupports
),
278 nsBinaryOutputStream::WriteCompoundObject(nsISupports
* aObject
,
282 // Can't deal with weak refs
283 NS_ENSURE_TRUE(aIsStrongRef
, NS_ERROR_UNEXPECTED
);
285 nsCOMPtr
<nsIClassInfo
> classInfo
= do_QueryInterface(aObject
);
286 NS_ENSURE_TRUE(classInfo
, NS_ERROR_NOT_AVAILABLE
);
288 nsCOMPtr
<nsISerializable
> serializable
= do_QueryInterface(aObject
);
289 NS_ENSURE_TRUE(serializable
, NS_ERROR_NOT_AVAILABLE
);
292 classInfo
->GetClassIDNoAlloc(&cid
);
294 nsresult rv
= WriteID(cid
);
295 NS_ENSURE_SUCCESS(rv
, rv
);
298 NS_ENSURE_SUCCESS(rv
, rv
);
300 return serializable
->Write(this);
304 nsBinaryOutputStream::WriteID(const nsIID
& aIID
)
306 nsresult rv
= Write32(aIID
.m0
);
307 NS_ENSURE_SUCCESS(rv
, rv
);
309 rv
= Write16(aIID
.m1
);
310 NS_ENSURE_SUCCESS(rv
, rv
);
312 rv
= Write16(aIID
.m2
);
313 NS_ENSURE_SUCCESS(rv
, rv
);
315 for (int i
= 0; i
< 8; ++i
) {
316 rv
= Write8(aIID
.m3
[i
]);
317 NS_ENSURE_SUCCESS(rv
, rv
);
323 NS_IMETHODIMP_(char*)
324 nsBinaryOutputStream::GetBuffer(PRUint32 aLength
, PRUint32 aAlignMask
)
327 return mBufferAccess
->GetBuffer(aLength
, aAlignMask
);
332 nsBinaryOutputStream::PutBuffer(char* aBuffer
, PRUint32 aLength
)
335 mBufferAccess
->PutBuffer(aBuffer
, aLength
);
338 NS_IMPL_ISUPPORTS3(nsBinaryInputStream
, nsIObjectInputStream
, nsIBinaryInputStream
, nsIInputStream
)
341 nsBinaryInputStream::Available(PRUint32
* aResult
)
343 NS_ENSURE_STATE(mInputStream
);
344 return mInputStream
->Available(aResult
);
348 nsBinaryInputStream::Read(char* aBuffer
, PRUint32 aCount
, PRUint32
*aNumRead
)
350 NS_ENSURE_STATE(mInputStream
);
352 // mInputStream might give us short reads, so deal with that.
353 PRUint32 totalRead
= 0;
357 nsresult rv
= mInputStream
->Read(aBuffer
, aCount
, &bytesRead
);
358 if (rv
== NS_BASE_STREAM_WOULD_BLOCK
&& totalRead
!= 0) {
359 // We already read some data. Return it.
367 totalRead
+= bytesRead
;
368 aBuffer
+= bytesRead
;
370 } while (aCount
!= 0 && bytesRead
!= 0);
372 *aNumRead
= totalRead
;
378 // when forwarding ReadSegments to mInputStream, we need to make sure
379 // 'this' is being passed to the writer each time. To do this, we need
380 // a thunking function which keeps the real input stream around.
382 // the closure wrapper
383 struct ReadSegmentsClosure
{
384 nsIInputStream
* mRealInputStream
;
386 nsWriteSegmentFun mRealWriter
;
387 nsresult mRealResult
;
388 PRUint32 mBytesRead
; // to properly implement aToOffset
391 // the thunking function
393 ReadSegmentForwardingThunk(nsIInputStream
* aStream
,
395 const char* aFromSegment
,
398 PRUint32
*aWriteCount
)
400 ReadSegmentsClosure
* thunkClosure
=
401 reinterpret_cast<ReadSegmentsClosure
*>(aClosure
);
403 NS_ASSERTION(NS_SUCCEEDED(thunkClosure
->mRealResult
),
404 "How did this get to be a failure status?");
406 thunkClosure
->mRealResult
=
407 thunkClosure
->mRealWriter(thunkClosure
->mRealInputStream
,
408 thunkClosure
->mRealClosure
,
410 thunkClosure
->mBytesRead
+ aToOffset
,
411 aCount
, aWriteCount
);
413 return thunkClosure
->mRealResult
;
418 nsBinaryInputStream::ReadSegments(nsWriteSegmentFun writer
, void * closure
, PRUint32 count
, PRUint32
*_retval
)
420 NS_ENSURE_STATE(mInputStream
);
422 ReadSegmentsClosure thunkClosure
= { this, closure
, writer
, NS_OK
, 0 };
424 // mInputStream might give us short reads, so deal with that.
427 nsresult rv
= mInputStream
->ReadSegments(ReadSegmentForwardingThunk
,
431 if (rv
== NS_BASE_STREAM_WOULD_BLOCK
&& thunkClosure
.mBytesRead
!= 0) {
432 // We already read some data. Return it.
440 thunkClosure
.mBytesRead
+= bytesRead
;
442 } while (count
!= 0 && bytesRead
!= 0 &&
443 NS_SUCCEEDED(thunkClosure
.mRealResult
));
445 *_retval
= thunkClosure
.mBytesRead
;
451 nsBinaryInputStream::IsNonBlocking(PRBool
*aNonBlocking
)
453 NS_ENSURE_STATE(mInputStream
);
454 return mInputStream
->IsNonBlocking(aNonBlocking
);
458 nsBinaryInputStream::Close()
460 NS_ENSURE_STATE(mInputStream
);
461 return mInputStream
->Close();
465 nsBinaryInputStream::SetInputStream(nsIInputStream
*aInputStream
)
467 NS_ENSURE_ARG_POINTER(aInputStream
);
468 mInputStream
= aInputStream
;
469 mBufferAccess
= do_QueryInterface(aInputStream
);
474 nsBinaryInputStream::ReadBoolean(PRBool
* aBoolean
)
477 nsresult rv
= Read8(&byteResult
);
478 *aBoolean
= !!byteResult
;
483 nsBinaryInputStream::Read8(PRUint8
* aByte
)
488 rv
= Read(reinterpret_cast<char*>(aByte
), sizeof(*aByte
), &bytesRead
);
489 if (NS_FAILED(rv
)) return rv
;
491 return NS_ERROR_FAILURE
;
496 nsBinaryInputStream::Read16(PRUint16
* a16
)
501 rv
= Read(reinterpret_cast<char*>(a16
), sizeof *a16
, &bytesRead
);
502 if (NS_FAILED(rv
)) return rv
;
503 if (bytesRead
!= sizeof *a16
)
504 return NS_ERROR_FAILURE
;
505 *a16
= NS_SWAP16(*a16
);
510 nsBinaryInputStream::Read32(PRUint32
* a32
)
515 rv
= Read(reinterpret_cast<char*>(a32
), sizeof *a32
, &bytesRead
);
516 if (NS_FAILED(rv
)) return rv
;
517 if (bytesRead
!= sizeof *a32
)
518 return NS_ERROR_FAILURE
;
519 *a32
= NS_SWAP32(*a32
);
524 nsBinaryInputStream::Read64(PRUint64
* a64
)
529 rv
= Read(reinterpret_cast<char*>(a64
), sizeof *a64
, &bytesRead
);
530 if (NS_FAILED(rv
)) return rv
;
531 if (bytesRead
!= sizeof *a64
)
532 return NS_ERROR_FAILURE
;
533 *a64
= NS_SWAP64(*a64
);
538 nsBinaryInputStream::ReadFloat(float* aFloat
)
540 NS_ASSERTION(sizeof(float) == sizeof (PRUint32
),
541 "False assumption about sizeof(float)");
542 return Read32(reinterpret_cast<PRUint32
*>(aFloat
));
546 nsBinaryInputStream::ReadDouble(double* aDouble
)
548 NS_ASSERTION(sizeof(double) == sizeof(PRUint64
),
549 "False assumption about sizeof(double)");
550 return Read64(reinterpret_cast<PRUint64
*>(aDouble
));
554 WriteSegmentToCString(nsIInputStream
* aStream
,
556 const char* aFromSegment
,
559 PRUint32
*aWriteCount
)
561 nsACString
* outString
= static_cast<nsACString
*>(aClosure
);
563 outString
->Append(aFromSegment
, aCount
);
565 *aWriteCount
= aCount
;
571 nsBinaryInputStream::ReadCString(nsACString
& aString
)
574 PRUint32 length
, bytesRead
;
576 rv
= Read32(&length
);
577 if (NS_FAILED(rv
)) return rv
;
580 rv
= ReadSegments(WriteSegmentToCString
, &aString
, length
, &bytesRead
);
581 if (NS_FAILED(rv
)) return rv
;
583 if (bytesRead
!= length
)
584 return NS_ERROR_FAILURE
;
590 // sometimes, WriteSegmentToString will be handed an odd-number of
591 // bytes, which means we only have half of the last PRUnichar
592 struct WriteStringClosure
{
593 PRUnichar
*mWriteCursor
;
594 PRPackedBool mHasCarryoverByte
;
598 // there are a few cases we have to account for here:
599 // * even length buffer, no carryover - easy, just append
600 // * odd length buffer, no carryover - the last byte needs to be saved
602 // * odd length buffer, with carryover - first byte needs to be used
603 // with the carryover byte, and
604 // the rest of the even length
605 // buffer is appended as normal
606 // * even length buffer, with carryover - the first byte needs to be
607 // used with the previous carryover byte.
608 // this gives you an odd length buffer,
609 // so you have to save the last byte for
610 // the next carryover
613 // same version of the above, but with correct casting and endian swapping
615 WriteSegmentToString(nsIInputStream
* aStream
,
617 const char* aFromSegment
,
620 PRUint32
*aWriteCount
)
622 NS_PRECONDITION(aCount
> 0, "Why are we being told to write 0 bytes?");
623 NS_PRECONDITION(sizeof(PRUnichar
) == 2, "We can't handle other sizes!");
625 WriteStringClosure
* closure
= static_cast<WriteStringClosure
*>(aClosure
);
626 PRUnichar
*cursor
= closure
->mWriteCursor
;
628 // we're always going to consume the whole buffer no matter what
629 // happens, so take care of that right now.. that allows us to
630 // tweak aCount later. Do NOT move this!
631 *aWriteCount
= aCount
;
633 // if the last Write had an odd-number of bytes read, then
634 if (closure
->mHasCarryoverByte
) {
635 // re-create the two-byte sequence we want to work with
636 char bytes
[2] = { closure
->mCarryoverByte
, *aFromSegment
};
637 *cursor
= *(PRUnichar
*)bytes
;
638 // Now the little endianness dance
639 #ifdef IS_LITTLE_ENDIAN
640 *cursor
= (PRUnichar
) NS_SWAP16(*cursor
);
644 // now skip past the first byte of the buffer.. code from here
645 // can assume normal operations, but should not assume aCount
646 // is relative to the ORIGINAL buffer
650 closure
->mHasCarryoverByte
= PR_FALSE
;
653 // this array is possibly unaligned... be careful how we access it!
654 const PRUnichar
*unicodeSegment
=
655 reinterpret_cast<const PRUnichar
*>(aFromSegment
);
657 // calculate number of full characters in segment (aCount could be odd!)
658 PRUint32 segmentLength
= aCount
/ sizeof(PRUnichar
);
660 // copy all data into our aligned buffer. byte swap if necessary.
661 memcpy(cursor
, unicodeSegment
, segmentLength
* sizeof(PRUnichar
));
662 PRUnichar
*end
= cursor
+ segmentLength
;
663 #ifdef IS_LITTLE_ENDIAN
664 for (; cursor
< end
; ++cursor
)
665 *cursor
= (PRUnichar
) NS_SWAP16(*cursor
);
667 closure
->mWriteCursor
= end
;
669 // remember this is the modifed aCount and aFromSegment,
670 // so that will take into account the fact that we might have
671 // skipped the first byte in the buffer
672 if (aCount
% sizeof(PRUnichar
) != 0) {
673 // we must have had a carryover byte, that we'll need the next
675 closure
->mCarryoverByte
= aFromSegment
[aCount
- 1];
676 closure
->mHasCarryoverByte
= PR_TRUE
;
684 nsBinaryInputStream::ReadString(nsAString
& aString
)
687 PRUint32 length
, bytesRead
;
689 rv
= Read32(&length
);
690 if (NS_FAILED(rv
)) return rv
;
697 // pre-allocate output buffer, and get direct access to buffer...
698 if (!EnsureStringLength(aString
, length
))
699 return NS_ERROR_OUT_OF_MEMORY
;
701 nsAString::iterator start
;
702 aString
.BeginWriting(start
);
704 WriteStringClosure closure
;
705 closure
.mWriteCursor
= start
.get();
706 closure
.mHasCarryoverByte
= PR_FALSE
;
708 rv
= ReadSegments(WriteSegmentToString
, &closure
,
709 length
*sizeof(PRUnichar
), &bytesRead
);
710 if (NS_FAILED(rv
)) return rv
;
712 NS_ASSERTION(!closure
.mHasCarryoverByte
, "some strange stream corruption!");
714 if (bytesRead
!= length
*sizeof(PRUnichar
))
715 return NS_ERROR_FAILURE
;
721 nsBinaryInputStream::ReadBytes(PRUint32 aLength
, char* *_rval
)
727 s
= reinterpret_cast<char*>(nsMemory::Alloc(aLength
));
729 return NS_ERROR_OUT_OF_MEMORY
;
731 rv
= Read(s
, aLength
, &bytesRead
);
736 if (bytesRead
!= aLength
) {
738 return NS_ERROR_FAILURE
;
746 nsBinaryInputStream::ReadByteArray(PRUint32 aLength
, PRUint8
* *_rval
)
748 return ReadBytes(aLength
, reinterpret_cast<char **>(_rval
));
752 nsBinaryInputStream::ReadObject(PRBool aIsStrongRef
, nsISupports
* *aObject
)
756 nsresult rv
= ReadID(&cid
);
757 NS_ENSURE_SUCCESS(rv
, rv
);
760 NS_ENSURE_SUCCESS(rv
, rv
);
762 nsCOMPtr
<nsISupports
> object
= do_CreateInstance(cid
, &rv
);
763 NS_ENSURE_SUCCESS(rv
, rv
);
765 nsCOMPtr
<nsISerializable
> serializable
= do_QueryInterface(object
);
766 NS_ENSURE_TRUE(serializable
, NS_ERROR_UNEXPECTED
);
768 rv
= serializable
->Read(this);
769 NS_ENSURE_SUCCESS(rv
, rv
);
771 return object
->QueryInterface(iid
, reinterpret_cast<void**>(aObject
));
775 nsBinaryInputStream::ReadID(nsID
*aResult
)
777 nsresult rv
= Read32(&aResult
->m0
);
778 NS_ENSURE_SUCCESS(rv
, rv
);
780 rv
= Read16(&aResult
->m1
);
781 NS_ENSURE_SUCCESS(rv
, rv
);
783 rv
= Read16(&aResult
->m2
);
784 NS_ENSURE_SUCCESS(rv
, rv
);
786 for (int i
= 0; i
< 8; ++i
) {
787 rv
= Read8(&aResult
->m3
[i
]);
788 NS_ENSURE_SUCCESS(rv
, rv
);
794 NS_IMETHODIMP_(char*)
795 nsBinaryInputStream::GetBuffer(PRUint32 aLength
, PRUint32 aAlignMask
)
798 return mBufferAccess
->GetBuffer(aLength
, aAlignMask
);
803 nsBinaryInputStream::PutBuffer(char* aBuffer
, PRUint32 aLength
)
806 mBufferAccess
->PutBuffer(aBuffer
, aLength
);