Code example for Parcel

Methods: dataPositionsetDataPositionwriteInt

0
    } 
 
    // Check parsing of the parcel fails. Make sure the parser rewind 
    // the parcel properly. 
    private void assertParseFail() throws Exception { 
        mParcel.setDataPosition(0);
        assertFalse(mMetadata.parse(mParcel));
        assertEquals(0, mParcel.dataPosition());
    } 
 
    // Check parsing of the parcel is successful. 
    private void assertParse() throws Exception { 
        mParcel.setDataPosition(0);
        assertTrue(mMetadata.parse(mParcel));
    } 
 
    // Write the number of bytes from the start of the parcel to the 
    // current position at the beginning of the parcel (offset 0). 
    private void adjustSize() { 
        adjustSize(0); 
    } 
 
    // Write the number of bytes from the offset to the current 
    // position at position pointed by offset. 
    private void adjustSize(int offset) {
        final int pos = mParcel.dataPosition();
 
        mParcel.setDataPosition(offset);
        mParcel.writeInt(pos - offset);
        mParcel.setDataPosition(pos);
    } 
 
    // Rewind the parcel and insert the header. 
    private void resetParcel() { 
        mParcel.setDataPosition(0);
        // Most tests will use a properly formed parcel with a size 
        // and the meta marker so we add them by default. 
        mParcel.writeInt(-1);  // Placeholder for the size
        mParcel.writeInt(kMarker);
    } 
 
    // ---------------------------------------------------------------------- 
    // START OF THE TESTS 
 
 
    // There should be at least 8 bytes in the parcel, 4 for the size 
    // and 4 for the 'M' 'E' 'T' 'A' marker. 
    @SmallTest 
    public void testMissingSizeAndMarker() throws Exception { 
        for (int i = 0; i < kHeaderSize; ++i) {
            mParcel.setDataPosition(0);
            mParcel.setDataSize(i);
 
            assertEquals(i, mParcel.dataAvail());
            assertParseFail(); 
        } 
    } 
 
    // There should be at least 'size' bytes in the parcel. 
    @SmallTest 
    public void testMissingData() throws Exception { 
        final int size = 20;
 
        mParcel.writeInt(size);
        mParcel.setDataSize(size - 1);
        assertParseFail(); 
    } 
 
    // Empty parcel is fine 
    @SmallTest 
    public void testEmptyIsOk() throws Exception { 
        adjustSize(); 
        assertParse(); 
    } 
 
    // ---------------------------------------------------------------------- 
    // RECORDS 
    // ---------------------------------------------------------------------- 
 
    // A record header should be at least 12 bytes long 
    @SmallTest 
    public void testRecordMissingId() throws Exception { 
        mParcel.writeInt(13); // record length
        // misses metadata id and metadata type. 
        adjustSize(); 
        assertParseFail(); 
    }