rt/emul/compact/src/main/java/java/io/ObjectOutputStream.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 604 emul/compact/src/main/java/java/io/ObjectOutputStream.java@3fcc279c921b
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
jaroslav@601
     1
/*
jaroslav@601
     2
 * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
jaroslav@601
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@601
     4
 *
jaroslav@601
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@601
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@601
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@601
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@601
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@601
    10
 *
jaroslav@601
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@601
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@601
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@601
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@601
    15
 * accompanied this code).
jaroslav@601
    16
 *
jaroslav@601
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@601
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@601
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@601
    20
 *
jaroslav@601
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@601
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@601
    23
 * questions.
jaroslav@601
    24
 */
jaroslav@601
    25
jaroslav@601
    26
package java.io;
jaroslav@601
    27
jaroslav@601
    28
import java.util.ArrayList;
jaroslav@601
    29
import java.util.Arrays;
jaroslav@601
    30
import java.util.List;
jaroslav@604
    31
import org.apidesign.bck2brwsr.emul.lang.System;
jaroslav@601
    32
jaroslav@601
    33
/**
jaroslav@601
    34
 * An ObjectOutputStream writes primitive data types and graphs of Java objects
jaroslav@601
    35
 * to an OutputStream.  The objects can be read (reconstituted) using an
jaroslav@601
    36
 * ObjectInputStream.  Persistent storage of objects can be accomplished by
jaroslav@601
    37
 * using a file for the stream.  If the stream is a network socket stream, the
jaroslav@601
    38
 * objects can be reconstituted on another host or in another process.
jaroslav@601
    39
 *
jaroslav@601
    40
 * <p>Only objects that support the java.io.Serializable interface can be
jaroslav@601
    41
 * written to streams.  The class of each serializable object is encoded
jaroslav@601
    42
 * including the class name and signature of the class, the values of the
jaroslav@601
    43
 * object's fields and arrays, and the closure of any other objects referenced
jaroslav@601
    44
 * from the initial objects.
jaroslav@601
    45
 *
jaroslav@601
    46
 * <p>The method writeObject is used to write an object to the stream.  Any
jaroslav@601
    47
 * object, including Strings and arrays, is written with writeObject. Multiple
jaroslav@601
    48
 * objects or primitives can be written to the stream.  The objects must be
jaroslav@601
    49
 * read back from the corresponding ObjectInputstream with the same types and
jaroslav@601
    50
 * in the same order as they were written.
jaroslav@601
    51
 *
jaroslav@601
    52
 * <p>Primitive data types can also be written to the stream using the
jaroslav@601
    53
 * appropriate methods from DataOutput. Strings can also be written using the
jaroslav@601
    54
 * writeUTF method.
jaroslav@601
    55
 *
jaroslav@601
    56
 * <p>The default serialization mechanism for an object writes the class of the
jaroslav@601
    57
 * object, the class signature, and the values of all non-transient and
jaroslav@601
    58
 * non-static fields.  References to other objects (except in transient or
jaroslav@601
    59
 * static fields) cause those objects to be written also. Multiple references
jaroslav@601
    60
 * to a single object are encoded using a reference sharing mechanism so that
jaroslav@601
    61
 * graphs of objects can be restored to the same shape as when the original was
jaroslav@601
    62
 * written.
jaroslav@601
    63
 *
jaroslav@601
    64
 * <p>For example to write an object that can be read by the example in
jaroslav@601
    65
 * ObjectInputStream:
jaroslav@601
    66
 * <br>
jaroslav@601
    67
 * <pre>
jaroslav@601
    68
 *      FileOutputStream fos = new FileOutputStream("t.tmp");
jaroslav@601
    69
 *      ObjectOutputStream oos = new ObjectOutputStream(fos);
jaroslav@601
    70
 *
jaroslav@601
    71
 *      oos.writeInt(12345);
jaroslav@601
    72
 *      oos.writeObject("Today");
jaroslav@601
    73
 *      oos.writeObject(new Date());
jaroslav@601
    74
 *
jaroslav@601
    75
 *      oos.close();
jaroslav@601
    76
 * </pre>
jaroslav@601
    77
 *
jaroslav@601
    78
 * <p>Classes that require special handling during the serialization and
jaroslav@601
    79
 * deserialization process must implement special methods with these exact
jaroslav@601
    80
 * signatures:
jaroslav@601
    81
 * <br>
jaroslav@601
    82
 * <pre>
jaroslav@601
    83
 * private void readObject(java.io.ObjectInputStream stream)
jaroslav@601
    84
 *     throws IOException, ClassNotFoundException;
jaroslav@601
    85
 * private void writeObject(java.io.ObjectOutputStream stream)
jaroslav@601
    86
 *     throws IOException
jaroslav@601
    87
 * private void readObjectNoData()
jaroslav@601
    88
 *     throws ObjectStreamException;
jaroslav@601
    89
 * </pre>
jaroslav@601
    90
 *
jaroslav@601
    91
 * <p>The writeObject method is responsible for writing the state of the object
jaroslav@601
    92
 * for its particular class so that the corresponding readObject method can
jaroslav@601
    93
 * restore it.  The method does not need to concern itself with the state
jaroslav@601
    94
 * belonging to the object's superclasses or subclasses.  State is saved by
jaroslav@601
    95
 * writing the individual fields to the ObjectOutputStream using the
jaroslav@601
    96
 * writeObject method or by using the methods for primitive data types
jaroslav@601
    97
 * supported by DataOutput.
jaroslav@601
    98
 *
jaroslav@601
    99
 * <p>Serialization does not write out the fields of any object that does not
jaroslav@601
   100
 * implement the java.io.Serializable interface.  Subclasses of Objects that
jaroslav@601
   101
 * are not serializable can be serializable. In this case the non-serializable
jaroslav@601
   102
 * class must have a no-arg constructor to allow its fields to be initialized.
jaroslav@601
   103
 * In this case it is the responsibility of the subclass to save and restore
jaroslav@601
   104
 * the state of the non-serializable class. It is frequently the case that the
jaroslav@601
   105
 * fields of that class are accessible (public, package, or protected) or that
jaroslav@601
   106
 * there are get and set methods that can be used to restore the state.
jaroslav@601
   107
 *
jaroslav@601
   108
 * <p>Serialization of an object can be prevented by implementing writeObject
jaroslav@601
   109
 * and readObject methods that throw the NotSerializableException.  The
jaroslav@601
   110
 * exception will be caught by the ObjectOutputStream and abort the
jaroslav@601
   111
 * serialization process.
jaroslav@601
   112
 *
jaroslav@601
   113
 * <p>Implementing the Externalizable interface allows the object to assume
jaroslav@601
   114
 * complete control over the contents and format of the object's serialized
jaroslav@601
   115
 * form.  The methods of the Externalizable interface, writeExternal and
jaroslav@601
   116
 * readExternal, are called to save and restore the objects state.  When
jaroslav@601
   117
 * implemented by a class they can write and read their own state using all of
jaroslav@601
   118
 * the methods of ObjectOutput and ObjectInput.  It is the responsibility of
jaroslav@601
   119
 * the objects to handle any versioning that occurs.
jaroslav@601
   120
 *
jaroslav@601
   121
 * <p>Enum constants are serialized differently than ordinary serializable or
jaroslav@601
   122
 * externalizable objects.  The serialized form of an enum constant consists
jaroslav@601
   123
 * solely of its name; field values of the constant are not transmitted.  To
jaroslav@601
   124
 * serialize an enum constant, ObjectOutputStream writes the string returned by
jaroslav@601
   125
 * the constant's name method.  Like other serializable or externalizable
jaroslav@601
   126
 * objects, enum constants can function as the targets of back references
jaroslav@601
   127
 * appearing subsequently in the serialization stream.  The process by which
jaroslav@601
   128
 * enum constants are serialized cannot be customized; any class-specific
jaroslav@601
   129
 * writeObject and writeReplace methods defined by enum types are ignored
jaroslav@601
   130
 * during serialization.  Similarly, any serialPersistentFields or
jaroslav@601
   131
 * serialVersionUID field declarations are also ignored--all enum types have a
jaroslav@601
   132
 * fixed serialVersionUID of 0L.
jaroslav@601
   133
 *
jaroslav@601
   134
 * <p>Primitive data, excluding serializable fields and externalizable data, is
jaroslav@601
   135
 * written to the ObjectOutputStream in block-data records. A block data record
jaroslav@601
   136
 * is composed of a header and data. The block data header consists of a marker
jaroslav@601
   137
 * and the number of bytes to follow the header.  Consecutive primitive data
jaroslav@601
   138
 * writes are merged into one block-data record.  The blocking factor used for
jaroslav@601
   139
 * a block-data record will be 1024 bytes.  Each block-data record will be
jaroslav@601
   140
 * filled up to 1024 bytes, or be written whenever there is a termination of
jaroslav@601
   141
 * block-data mode.  Calls to the ObjectOutputStream methods writeObject,
jaroslav@601
   142
 * defaultWriteObject and writeFields initially terminate any existing
jaroslav@601
   143
 * block-data record.
jaroslav@601
   144
 *
jaroslav@601
   145
 * @author      Mike Warres
jaroslav@601
   146
 * @author      Roger Riggs
jaroslav@601
   147
 * @see java.io.DataOutput
jaroslav@601
   148
 * @see java.io.ObjectInputStream
jaroslav@601
   149
 * @see java.io.Serializable
jaroslav@601
   150
 * @see java.io.Externalizable
jaroslav@601
   151
 * @see <a href="../../../platform/serialization/spec/output.html">Object Serialization Specification, Section 2, Object Output Classes</a>
jaroslav@601
   152
 * @since       JDK1.1
jaroslav@601
   153
 */
jaroslav@601
   154
public class ObjectOutputStream
jaroslav@601
   155
    extends OutputStream implements ObjectOutput, ObjectStreamConstants
jaroslav@601
   156
{
jaroslav@601
   157
    /** filter stream for handling block data conversion */
jaroslav@601
   158
    private final BlockDataOutputStream bout;
jaroslav@601
   159
    /** obj -> wire handle map */
jaroslav@601
   160
    private final HandleTable handles;
jaroslav@601
   161
    /** obj -> replacement obj map */
jaroslav@601
   162
    private final ReplaceTable subs;
jaroslav@601
   163
    /** stream protocol version */
jaroslav@601
   164
    private int protocol = PROTOCOL_VERSION_2;
jaroslav@601
   165
    /** recursion depth */
jaroslav@601
   166
    private int depth;
jaroslav@601
   167
jaroslav@601
   168
    /** buffer for writing primitive field values */
jaroslav@601
   169
    private byte[] primVals;
jaroslav@601
   170
jaroslav@601
   171
    /** if true, invoke writeObjectOverride() instead of writeObject() */
jaroslav@601
   172
    private final boolean enableOverride;
jaroslav@601
   173
    /** if true, invoke replaceObject() */
jaroslav@601
   174
    private boolean enableReplace;
jaroslav@601
   175
jaroslav@601
   176
    // values below valid only during upcalls to writeObject()/writeExternal()
jaroslav@601
   177
    /**
jaroslav@601
   178
     * Context during upcalls to class-defined writeObject methods; holds
jaroslav@601
   179
     * object currently being serialized and descriptor for current class.
jaroslav@601
   180
     * Null when not during writeObject upcall.
jaroslav@601
   181
     */
jaroslav@604
   182
    private Object curContext;
jaroslav@601
   183
    /** current PutField object */
jaroslav@601
   184
    private PutFieldImpl curPut;
jaroslav@601
   185
jaroslav@601
   186
    /** custom storage for debug trace info */
jaroslav@601
   187
    private final DebugTraceInfoStack debugInfoStack;
jaroslav@601
   188
jaroslav@601
   189
    /**
jaroslav@601
   190
     * value of "sun.io.serialization.extendedDebugInfo" property,
jaroslav@601
   191
     * as true or false for extended information about exception's place
jaroslav@601
   192
     */
jaroslav@604
   193
    private static final boolean extendedDebugInfo = false;
jaroslav@601
   194
jaroslav@601
   195
    /**
jaroslav@601
   196
     * Creates an ObjectOutputStream that writes to the specified OutputStream.
jaroslav@601
   197
     * This constructor writes the serialization stream header to the
jaroslav@601
   198
     * underlying stream; callers may wish to flush the stream immediately to
jaroslav@601
   199
     * ensure that constructors for receiving ObjectInputStreams will not block
jaroslav@601
   200
     * when reading the header.
jaroslav@601
   201
     *
jaroslav@601
   202
     * <p>If a security manager is installed, this constructor will check for
jaroslav@601
   203
     * the "enableSubclassImplementation" SerializablePermission when invoked
jaroslav@601
   204
     * directly or indirectly by the constructor of a subclass which overrides
jaroslav@601
   205
     * the ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared
jaroslav@601
   206
     * methods.
jaroslav@601
   207
     *
jaroslav@601
   208
     * @param   out output stream to write to
jaroslav@601
   209
     * @throws  IOException if an I/O error occurs while writing stream header
jaroslav@601
   210
     * @throws  SecurityException if untrusted subclass illegally overrides
jaroslav@601
   211
     *          security-sensitive methods
jaroslav@601
   212
     * @throws  NullPointerException if <code>out</code> is <code>null</code>
jaroslav@601
   213
     * @since   1.4
jaroslav@601
   214
     * @see     ObjectOutputStream#ObjectOutputStream()
jaroslav@601
   215
     * @see     ObjectOutputStream#putFields()
jaroslav@601
   216
     * @see     ObjectInputStream#ObjectInputStream(InputStream)
jaroslav@601
   217
     */
jaroslav@601
   218
    public ObjectOutputStream(OutputStream out) throws IOException {
jaroslav@601
   219
        verifySubclass();
jaroslav@601
   220
        bout = new BlockDataOutputStream(out);
jaroslav@601
   221
        handles = new HandleTable(10, (float) 3.00);
jaroslav@601
   222
        subs = new ReplaceTable(10, (float) 3.00);
jaroslav@601
   223
        enableOverride = false;
jaroslav@601
   224
        writeStreamHeader();
jaroslav@601
   225
        bout.setBlockDataMode(true);
jaroslav@601
   226
        if (extendedDebugInfo) {
jaroslav@601
   227
            debugInfoStack = new DebugTraceInfoStack();
jaroslav@601
   228
        } else {
jaroslav@601
   229
            debugInfoStack = null;
jaroslav@601
   230
        }
jaroslav@601
   231
    }
jaroslav@601
   232
jaroslav@601
   233
    /**
jaroslav@601
   234
     * Provide a way for subclasses that are completely reimplementing
jaroslav@601
   235
     * ObjectOutputStream to not have to allocate private data just used by
jaroslav@601
   236
     * this implementation of ObjectOutputStream.
jaroslav@601
   237
     *
jaroslav@601
   238
     * <p>If there is a security manager installed, this method first calls the
jaroslav@601
   239
     * security manager's <code>checkPermission</code> method with a
jaroslav@601
   240
     * <code>SerializablePermission("enableSubclassImplementation")</code>
jaroslav@601
   241
     * permission to ensure it's ok to enable subclassing.
jaroslav@601
   242
     *
jaroslav@601
   243
     * @throws  SecurityException if a security manager exists and its
jaroslav@601
   244
     *          <code>checkPermission</code> method denies enabling
jaroslav@601
   245
     *          subclassing.
jaroslav@601
   246
     * @see SecurityManager#checkPermission
jaroslav@601
   247
     * @see java.io.SerializablePermission
jaroslav@601
   248
     */
jaroslav@601
   249
    protected ObjectOutputStream() throws IOException, SecurityException {
jaroslav@604
   250
        throw new SecurityException();
jaroslav@601
   251
    }
jaroslav@601
   252
jaroslav@601
   253
    /**
jaroslav@601
   254
     * Specify stream protocol version to use when writing the stream.
jaroslav@601
   255
     *
jaroslav@601
   256
     * <p>This routine provides a hook to enable the current version of
jaroslav@601
   257
     * Serialization to write in a format that is backwards compatible to a
jaroslav@601
   258
     * previous version of the stream format.
jaroslav@601
   259
     *
jaroslav@601
   260
     * <p>Every effort will be made to avoid introducing additional
jaroslav@601
   261
     * backwards incompatibilities; however, sometimes there is no
jaroslav@601
   262
     * other alternative.
jaroslav@601
   263
     *
jaroslav@601
   264
     * @param   version use ProtocolVersion from java.io.ObjectStreamConstants.
jaroslav@601
   265
     * @throws  IllegalStateException if called after any objects
jaroslav@601
   266
     *          have been serialized.
jaroslav@601
   267
     * @throws  IllegalArgumentException if invalid version is passed in.
jaroslav@601
   268
     * @throws  IOException if I/O errors occur
jaroslav@601
   269
     * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
jaroslav@601
   270
     * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_2
jaroslav@601
   271
     * @since   1.2
jaroslav@601
   272
     */
jaroslav@601
   273
    public void useProtocolVersion(int version) throws IOException {
jaroslav@601
   274
        if (handles.size() != 0) {
jaroslav@601
   275
            // REMIND: implement better check for pristine stream?
jaroslav@601
   276
            throw new IllegalStateException("stream non-empty");
jaroslav@601
   277
        }
jaroslav@601
   278
        switch (version) {
jaroslav@601
   279
            case PROTOCOL_VERSION_1:
jaroslav@601
   280
            case PROTOCOL_VERSION_2:
jaroslav@601
   281
                protocol = version;
jaroslav@601
   282
                break;
jaroslav@601
   283
jaroslav@601
   284
            default:
jaroslav@601
   285
                throw new IllegalArgumentException(
jaroslav@601
   286
                    "unknown version: " + version);
jaroslav@601
   287
        }
jaroslav@601
   288
    }
jaroslav@601
   289
jaroslav@601
   290
    /**
jaroslav@601
   291
     * Write the specified object to the ObjectOutputStream.  The class of the
jaroslav@601
   292
     * object, the signature of the class, and the values of the non-transient
jaroslav@601
   293
     * and non-static fields of the class and all of its supertypes are
jaroslav@601
   294
     * written.  Default serialization for a class can be overridden using the
jaroslav@601
   295
     * writeObject and the readObject methods.  Objects referenced by this
jaroslav@601
   296
     * object are written transitively so that a complete equivalent graph of
jaroslav@601
   297
     * objects can be reconstructed by an ObjectInputStream.
jaroslav@601
   298
     *
jaroslav@601
   299
     * <p>Exceptions are thrown for problems with the OutputStream and for
jaroslav@601
   300
     * classes that should not be serialized.  All exceptions are fatal to the
jaroslav@601
   301
     * OutputStream, which is left in an indeterminate state, and it is up to
jaroslav@601
   302
     * the caller to ignore or recover the stream state.
jaroslav@601
   303
     *
jaroslav@601
   304
     * @throws  InvalidClassException Something is wrong with a class used by
jaroslav@601
   305
     *          serialization.
jaroslav@601
   306
     * @throws  NotSerializableException Some object to be serialized does not
jaroslav@601
   307
     *          implement the java.io.Serializable interface.
jaroslav@601
   308
     * @throws  IOException Any exception thrown by the underlying
jaroslav@601
   309
     *          OutputStream.
jaroslav@601
   310
     */
jaroslav@601
   311
    public final void writeObject(Object obj) throws IOException {
jaroslav@601
   312
        if (enableOverride) {
jaroslav@601
   313
            writeObjectOverride(obj);
jaroslav@601
   314
            return;
jaroslav@601
   315
        }
jaroslav@601
   316
        try {
jaroslav@601
   317
            writeObject0(obj, false);
jaroslav@601
   318
        } catch (IOException ex) {
jaroslav@601
   319
            if (depth == 0) {
jaroslav@601
   320
                writeFatalException(ex);
jaroslav@601
   321
            }
jaroslav@601
   322
            throw ex;
jaroslav@601
   323
        }
jaroslav@601
   324
    }
jaroslav@601
   325
jaroslav@601
   326
    /**
jaroslav@601
   327
     * Method used by subclasses to override the default writeObject method.
jaroslav@601
   328
     * This method is called by trusted subclasses of ObjectInputStream that
jaroslav@601
   329
     * constructed ObjectInputStream using the protected no-arg constructor.
jaroslav@601
   330
     * The subclass is expected to provide an override method with the modifier
jaroslav@601
   331
     * "final".
jaroslav@601
   332
     *
jaroslav@601
   333
     * @param   obj object to be written to the underlying stream
jaroslav@601
   334
     * @throws  IOException if there are I/O errors while writing to the
jaroslav@601
   335
     *          underlying stream
jaroslav@601
   336
     * @see #ObjectOutputStream()
jaroslav@601
   337
     * @see #writeObject(Object)
jaroslav@601
   338
     * @since 1.2
jaroslav@601
   339
     */
jaroslav@601
   340
    protected void writeObjectOverride(Object obj) throws IOException {
jaroslav@601
   341
    }
jaroslav@601
   342
jaroslav@601
   343
    /**
jaroslav@601
   344
     * Writes an "unshared" object to the ObjectOutputStream.  This method is
jaroslav@601
   345
     * identical to writeObject, except that it always writes the given object
jaroslav@601
   346
     * as a new, unique object in the stream (as opposed to a back-reference
jaroslav@601
   347
     * pointing to a previously serialized instance).  Specifically:
jaroslav@601
   348
     * <ul>
jaroslav@601
   349
     *   <li>An object written via writeUnshared is always serialized in the
jaroslav@601
   350
     *       same manner as a newly appearing object (an object that has not
jaroslav@601
   351
     *       been written to the stream yet), regardless of whether or not the
jaroslav@601
   352
     *       object has been written previously.
jaroslav@601
   353
     *
jaroslav@601
   354
     *   <li>If writeObject is used to write an object that has been previously
jaroslav@601
   355
     *       written with writeUnshared, the previous writeUnshared operation
jaroslav@601
   356
     *       is treated as if it were a write of a separate object.  In other
jaroslav@601
   357
     *       words, ObjectOutputStream will never generate back-references to
jaroslav@601
   358
     *       object data written by calls to writeUnshared.
jaroslav@601
   359
     * </ul>
jaroslav@601
   360
     * While writing an object via writeUnshared does not in itself guarantee a
jaroslav@601
   361
     * unique reference to the object when it is deserialized, it allows a
jaroslav@601
   362
     * single object to be defined multiple times in a stream, so that multiple
jaroslav@601
   363
     * calls to readUnshared by the receiver will not conflict.  Note that the
jaroslav@601
   364
     * rules described above only apply to the base-level object written with
jaroslav@601
   365
     * writeUnshared, and not to any transitively referenced sub-objects in the
jaroslav@601
   366
     * object graph to be serialized.
jaroslav@601
   367
     *
jaroslav@601
   368
     * <p>ObjectOutputStream subclasses which override this method can only be
jaroslav@601
   369
     * constructed in security contexts possessing the
jaroslav@601
   370
     * "enableSubclassImplementation" SerializablePermission; any attempt to
jaroslav@601
   371
     * instantiate such a subclass without this permission will cause a
jaroslav@601
   372
     * SecurityException to be thrown.
jaroslav@601
   373
     *
jaroslav@601
   374
     * @param   obj object to write to stream
jaroslav@601
   375
     * @throws  NotSerializableException if an object in the graph to be
jaroslav@601
   376
     *          serialized does not implement the Serializable interface
jaroslav@601
   377
     * @throws  InvalidClassException if a problem exists with the class of an
jaroslav@601
   378
     *          object to be serialized
jaroslav@601
   379
     * @throws  IOException if an I/O error occurs during serialization
jaroslav@601
   380
     * @since 1.4
jaroslav@601
   381
     */
jaroslav@601
   382
    public void writeUnshared(Object obj) throws IOException {
jaroslav@601
   383
        try {
jaroslav@601
   384
            writeObject0(obj, true);
jaroslav@601
   385
        } catch (IOException ex) {
jaroslav@601
   386
            if (depth == 0) {
jaroslav@601
   387
                writeFatalException(ex);
jaroslav@601
   388
            }
jaroslav@601
   389
            throw ex;
jaroslav@601
   390
        }
jaroslav@601
   391
    }
jaroslav@601
   392
jaroslav@601
   393
    /**
jaroslav@601
   394
     * Write the non-static and non-transient fields of the current class to
jaroslav@601
   395
     * this stream.  This may only be called from the writeObject method of the
jaroslav@601
   396
     * class being serialized. It will throw the NotActiveException if it is
jaroslav@601
   397
     * called otherwise.
jaroslav@601
   398
     *
jaroslav@601
   399
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   400
     *          <code>OutputStream</code>
jaroslav@601
   401
     */
jaroslav@601
   402
    public void defaultWriteObject() throws IOException {
jaroslav@601
   403
        if ( curContext == null ) {
jaroslav@601
   404
            throw new NotActiveException("not in call to writeObject");
jaroslav@601
   405
        }
jaroslav@604
   406
        Object curObj = null; // curContext.getObj();
jaroslav@604
   407
        ObjectStreamClass curDesc = null; // curContext.getDesc();
jaroslav@601
   408
        bout.setBlockDataMode(false);
jaroslav@601
   409
        defaultWriteFields(curObj, curDesc);
jaroslav@601
   410
        bout.setBlockDataMode(true);
jaroslav@601
   411
    }
jaroslav@601
   412
jaroslav@601
   413
    /**
jaroslav@601
   414
     * Retrieve the object used to buffer persistent fields to be written to
jaroslav@601
   415
     * the stream.  The fields will be written to the stream when writeFields
jaroslav@601
   416
     * method is called.
jaroslav@601
   417
     *
jaroslav@601
   418
     * @return  an instance of the class Putfield that holds the serializable
jaroslav@601
   419
     *          fields
jaroslav@601
   420
     * @throws  IOException if I/O errors occur
jaroslav@601
   421
     * @since 1.2
jaroslav@601
   422
     */
jaroslav@601
   423
    public ObjectOutputStream.PutField putFields() throws IOException {
jaroslav@601
   424
        if (curPut == null) {
jaroslav@601
   425
            if (curContext == null) {
jaroslav@601
   426
                throw new NotActiveException("not in call to writeObject");
jaroslav@601
   427
            }
jaroslav@604
   428
            Object curObj = null; // curContext.getObj();
jaroslav@604
   429
            ObjectStreamClass curDesc = null; // curContext.getDesc();
jaroslav@601
   430
            curPut = new PutFieldImpl(curDesc);
jaroslav@601
   431
        }
jaroslav@601
   432
        return curPut;
jaroslav@601
   433
    }
jaroslav@601
   434
jaroslav@601
   435
    /**
jaroslav@601
   436
     * Write the buffered fields to the stream.
jaroslav@601
   437
     *
jaroslav@601
   438
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   439
     *          stream
jaroslav@601
   440
     * @throws  NotActiveException Called when a classes writeObject method was
jaroslav@601
   441
     *          not called to write the state of the object.
jaroslav@601
   442
     * @since 1.2
jaroslav@601
   443
     */
jaroslav@601
   444
    public void writeFields() throws IOException {
jaroslav@601
   445
        if (curPut == null) {
jaroslav@601
   446
            throw new NotActiveException("no current PutField object");
jaroslav@601
   447
        }
jaroslav@601
   448
        bout.setBlockDataMode(false);
jaroslav@601
   449
        curPut.writeFields();
jaroslav@601
   450
        bout.setBlockDataMode(true);
jaroslav@601
   451
    }
jaroslav@601
   452
jaroslav@601
   453
    /**
jaroslav@601
   454
     * Reset will disregard the state of any objects already written to the
jaroslav@601
   455
     * stream.  The state is reset to be the same as a new ObjectOutputStream.
jaroslav@601
   456
     * The current point in the stream is marked as reset so the corresponding
jaroslav@601
   457
     * ObjectInputStream will be reset at the same point.  Objects previously
jaroslav@601
   458
     * written to the stream will not be refered to as already being in the
jaroslav@601
   459
     * stream.  They will be written to the stream again.
jaroslav@601
   460
     *
jaroslav@601
   461
     * @throws  IOException if reset() is invoked while serializing an object.
jaroslav@601
   462
     */
jaroslav@601
   463
    public void reset() throws IOException {
jaroslav@601
   464
        if (depth != 0) {
jaroslav@601
   465
            throw new IOException("stream active");
jaroslav@601
   466
        }
jaroslav@601
   467
        bout.setBlockDataMode(false);
jaroslav@601
   468
        bout.writeByte(TC_RESET);
jaroslav@601
   469
        clear();
jaroslav@601
   470
        bout.setBlockDataMode(true);
jaroslav@601
   471
    }
jaroslav@601
   472
jaroslav@601
   473
    /**
jaroslav@601
   474
     * Subclasses may implement this method to allow class data to be stored in
jaroslav@601
   475
     * the stream. By default this method does nothing.  The corresponding
jaroslav@601
   476
     * method in ObjectInputStream is resolveClass.  This method is called
jaroslav@601
   477
     * exactly once for each unique class in the stream.  The class name and
jaroslav@601
   478
     * signature will have already been written to the stream.  This method may
jaroslav@601
   479
     * make free use of the ObjectOutputStream to save any representation of
jaroslav@601
   480
     * the class it deems suitable (for example, the bytes of the class file).
jaroslav@601
   481
     * The resolveClass method in the corresponding subclass of
jaroslav@601
   482
     * ObjectInputStream must read and use any data or objects written by
jaroslav@601
   483
     * annotateClass.
jaroslav@601
   484
     *
jaroslav@601
   485
     * @param   cl the class to annotate custom data for
jaroslav@601
   486
     * @throws  IOException Any exception thrown by the underlying
jaroslav@601
   487
     *          OutputStream.
jaroslav@601
   488
     */
jaroslav@601
   489
    protected void annotateClass(Class<?> cl) throws IOException {
jaroslav@601
   490
    }
jaroslav@601
   491
jaroslav@601
   492
    /**
jaroslav@601
   493
     * Subclasses may implement this method to store custom data in the stream
jaroslav@601
   494
     * along with descriptors for dynamic proxy classes.
jaroslav@601
   495
     *
jaroslav@601
   496
     * <p>This method is called exactly once for each unique proxy class
jaroslav@601
   497
     * descriptor in the stream.  The default implementation of this method in
jaroslav@601
   498
     * <code>ObjectOutputStream</code> does nothing.
jaroslav@601
   499
     *
jaroslav@601
   500
     * <p>The corresponding method in <code>ObjectInputStream</code> is
jaroslav@601
   501
     * <code>resolveProxyClass</code>.  For a given subclass of
jaroslav@601
   502
     * <code>ObjectOutputStream</code> that overrides this method, the
jaroslav@601
   503
     * <code>resolveProxyClass</code> method in the corresponding subclass of
jaroslav@601
   504
     * <code>ObjectInputStream</code> must read any data or objects written by
jaroslav@601
   505
     * <code>annotateProxyClass</code>.
jaroslav@601
   506
     *
jaroslav@601
   507
     * @param   cl the proxy class to annotate custom data for
jaroslav@601
   508
     * @throws  IOException any exception thrown by the underlying
jaroslav@601
   509
     *          <code>OutputStream</code>
jaroslav@601
   510
     * @see ObjectInputStream#resolveProxyClass(String[])
jaroslav@601
   511
     * @since   1.3
jaroslav@601
   512
     */
jaroslav@601
   513
    protected void annotateProxyClass(Class<?> cl) throws IOException {
jaroslav@601
   514
    }
jaroslav@601
   515
jaroslav@601
   516
    /**
jaroslav@601
   517
     * This method will allow trusted subclasses of ObjectOutputStream to
jaroslav@601
   518
     * substitute one object for another during serialization. Replacing
jaroslav@601
   519
     * objects is disabled until enableReplaceObject is called. The
jaroslav@601
   520
     * enableReplaceObject method checks that the stream requesting to do
jaroslav@601
   521
     * replacement can be trusted.  The first occurrence of each object written
jaroslav@601
   522
     * into the serialization stream is passed to replaceObject.  Subsequent
jaroslav@601
   523
     * references to the object are replaced by the object returned by the
jaroslav@601
   524
     * original call to replaceObject.  To ensure that the private state of
jaroslav@601
   525
     * objects is not unintentionally exposed, only trusted streams may use
jaroslav@601
   526
     * replaceObject.
jaroslav@601
   527
     *
jaroslav@601
   528
     * <p>The ObjectOutputStream.writeObject method takes a parameter of type
jaroslav@601
   529
     * Object (as opposed to type Serializable) to allow for cases where
jaroslav@601
   530
     * non-serializable objects are replaced by serializable ones.
jaroslav@601
   531
     *
jaroslav@601
   532
     * <p>When a subclass is replacing objects it must insure that either a
jaroslav@601
   533
     * complementary substitution must be made during deserialization or that
jaroslav@601
   534
     * the substituted object is compatible with every field where the
jaroslav@601
   535
     * reference will be stored.  Objects whose type is not a subclass of the
jaroslav@601
   536
     * type of the field or array element abort the serialization by raising an
jaroslav@601
   537
     * exception and the object is not be stored.
jaroslav@601
   538
     *
jaroslav@601
   539
     * <p>This method is called only once when each object is first
jaroslav@601
   540
     * encountered.  All subsequent references to the object will be redirected
jaroslav@601
   541
     * to the new object. This method should return the object to be
jaroslav@601
   542
     * substituted or the original object.
jaroslav@601
   543
     *
jaroslav@601
   544
     * <p>Null can be returned as the object to be substituted, but may cause
jaroslav@601
   545
     * NullReferenceException in classes that contain references to the
jaroslav@601
   546
     * original object since they may be expecting an object instead of
jaroslav@601
   547
     * null.
jaroslav@601
   548
     *
jaroslav@601
   549
     * @param   obj the object to be replaced
jaroslav@601
   550
     * @return  the alternate object that replaced the specified one
jaroslav@601
   551
     * @throws  IOException Any exception thrown by the underlying
jaroslav@601
   552
     *          OutputStream.
jaroslav@601
   553
     */
jaroslav@601
   554
    protected Object replaceObject(Object obj) throws IOException {
jaroslav@601
   555
        return obj;
jaroslav@601
   556
    }
jaroslav@601
   557
jaroslav@601
   558
    /**
jaroslav@601
   559
     * Enable the stream to do replacement of objects in the stream.  When
jaroslav@601
   560
     * enabled, the replaceObject method is called for every object being
jaroslav@601
   561
     * serialized.
jaroslav@601
   562
     *
jaroslav@601
   563
     * <p>If <code>enable</code> is true, and there is a security manager
jaroslav@601
   564
     * installed, this method first calls the security manager's
jaroslav@601
   565
     * <code>checkPermission</code> method with a
jaroslav@601
   566
     * <code>SerializablePermission("enableSubstitution")</code> permission to
jaroslav@601
   567
     * ensure it's ok to enable the stream to do replacement of objects in the
jaroslav@601
   568
     * stream.
jaroslav@601
   569
     *
jaroslav@601
   570
     * @param   enable boolean parameter to enable replacement of objects
jaroslav@601
   571
     * @return  the previous setting before this method was invoked
jaroslav@601
   572
     * @throws  SecurityException if a security manager exists and its
jaroslav@601
   573
     *          <code>checkPermission</code> method denies enabling the stream
jaroslav@601
   574
     *          to do replacement of objects in the stream.
jaroslav@601
   575
     * @see SecurityManager#checkPermission
jaroslav@601
   576
     * @see java.io.SerializablePermission
jaroslav@601
   577
     */
jaroslav@601
   578
    protected boolean enableReplaceObject(boolean enable)
jaroslav@601
   579
        throws SecurityException
jaroslav@601
   580
    {
jaroslav@604
   581
        throw new SecurityException();
jaroslav@601
   582
    }
jaroslav@601
   583
jaroslav@601
   584
    /**
jaroslav@601
   585
     * The writeStreamHeader method is provided so subclasses can append or
jaroslav@601
   586
     * prepend their own header to the stream.  It writes the magic number and
jaroslav@601
   587
     * version to the stream.
jaroslav@601
   588
     *
jaroslav@601
   589
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   590
     *          stream
jaroslav@601
   591
     */
jaroslav@601
   592
    protected void writeStreamHeader() throws IOException {
jaroslav@601
   593
        bout.writeShort(STREAM_MAGIC);
jaroslav@601
   594
        bout.writeShort(STREAM_VERSION);
jaroslav@601
   595
    }
jaroslav@601
   596
jaroslav@601
   597
    /**
jaroslav@601
   598
     * Write the specified class descriptor to the ObjectOutputStream.  Class
jaroslav@601
   599
     * descriptors are used to identify the classes of objects written to the
jaroslav@601
   600
     * stream.  Subclasses of ObjectOutputStream may override this method to
jaroslav@601
   601
     * customize the way in which class descriptors are written to the
jaroslav@601
   602
     * serialization stream.  The corresponding method in ObjectInputStream,
jaroslav@601
   603
     * <code>readClassDescriptor</code>, should then be overridden to
jaroslav@601
   604
     * reconstitute the class descriptor from its custom stream representation.
jaroslav@601
   605
     * By default, this method writes class descriptors according to the format
jaroslav@601
   606
     * defined in the Object Serialization specification.
jaroslav@601
   607
     *
jaroslav@601
   608
     * <p>Note that this method will only be called if the ObjectOutputStream
jaroslav@601
   609
     * is not using the old serialization stream format (set by calling
jaroslav@601
   610
     * ObjectOutputStream's <code>useProtocolVersion</code> method).  If this
jaroslav@601
   611
     * serialization stream is using the old format
jaroslav@601
   612
     * (<code>PROTOCOL_VERSION_1</code>), the class descriptor will be written
jaroslav@601
   613
     * internally in a manner that cannot be overridden or customized.
jaroslav@601
   614
     *
jaroslav@601
   615
     * @param   desc class descriptor to write to the stream
jaroslav@601
   616
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   617
     * @see java.io.ObjectInputStream#readClassDescriptor()
jaroslav@601
   618
     * @see #useProtocolVersion(int)
jaroslav@601
   619
     * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
jaroslav@601
   620
     * @since 1.3
jaroslav@601
   621
     */
jaroslav@601
   622
    protected void writeClassDescriptor(ObjectStreamClass desc)
jaroslav@601
   623
        throws IOException
jaroslav@601
   624
    {
jaroslav@601
   625
        desc.writeNonProxy(this);
jaroslav@601
   626
    }
jaroslav@601
   627
jaroslav@601
   628
    /**
jaroslav@601
   629
     * Writes a byte. This method will block until the byte is actually
jaroslav@601
   630
     * written.
jaroslav@601
   631
     *
jaroslav@601
   632
     * @param   val the byte to be written to the stream
jaroslav@601
   633
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   634
     */
jaroslav@601
   635
    public void write(int val) throws IOException {
jaroslav@601
   636
        bout.write(val);
jaroslav@601
   637
    }
jaroslav@601
   638
jaroslav@601
   639
    /**
jaroslav@601
   640
     * Writes an array of bytes. This method will block until the bytes are
jaroslav@601
   641
     * actually written.
jaroslav@601
   642
     *
jaroslav@601
   643
     * @param   buf the data to be written
jaroslav@601
   644
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   645
     */
jaroslav@601
   646
    public void write(byte[] buf) throws IOException {
jaroslav@601
   647
        bout.write(buf, 0, buf.length, false);
jaroslav@601
   648
    }
jaroslav@601
   649
jaroslav@601
   650
    /**
jaroslav@601
   651
     * Writes a sub array of bytes.
jaroslav@601
   652
     *
jaroslav@601
   653
     * @param   buf the data to be written
jaroslav@601
   654
     * @param   off the start offset in the data
jaroslav@601
   655
     * @param   len the number of bytes that are written
jaroslav@601
   656
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   657
     */
jaroslav@601
   658
    public void write(byte[] buf, int off, int len) throws IOException {
jaroslav@601
   659
        if (buf == null) {
jaroslav@601
   660
            throw new NullPointerException();
jaroslav@601
   661
        }
jaroslav@601
   662
        int endoff = off + len;
jaroslav@601
   663
        if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
jaroslav@601
   664
            throw new IndexOutOfBoundsException();
jaroslav@601
   665
        }
jaroslav@601
   666
        bout.write(buf, off, len, false);
jaroslav@601
   667
    }
jaroslav@601
   668
jaroslav@601
   669
    /**
jaroslav@601
   670
     * Flushes the stream. This will write any buffered output bytes and flush
jaroslav@601
   671
     * through to the underlying stream.
jaroslav@601
   672
     *
jaroslav@601
   673
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   674
     */
jaroslav@601
   675
    public void flush() throws IOException {
jaroslav@601
   676
        bout.flush();
jaroslav@601
   677
    }
jaroslav@601
   678
jaroslav@601
   679
    /**
jaroslav@601
   680
     * Drain any buffered data in ObjectOutputStream.  Similar to flush but
jaroslav@601
   681
     * does not propagate the flush to the underlying stream.
jaroslav@601
   682
     *
jaroslav@601
   683
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   684
     *          stream
jaroslav@601
   685
     */
jaroslav@601
   686
    protected void drain() throws IOException {
jaroslav@601
   687
        bout.drain();
jaroslav@601
   688
    }
jaroslav@601
   689
jaroslav@601
   690
    /**
jaroslav@601
   691
     * Closes the stream. This method must be called to release any resources
jaroslav@601
   692
     * associated with the stream.
jaroslav@601
   693
     *
jaroslav@601
   694
     * @throws  IOException If an I/O error has occurred.
jaroslav@601
   695
     */
jaroslav@601
   696
    public void close() throws IOException {
jaroslav@601
   697
        flush();
jaroslav@601
   698
        clear();
jaroslav@601
   699
        bout.close();
jaroslav@601
   700
    }
jaroslav@601
   701
jaroslav@601
   702
    /**
jaroslav@601
   703
     * Writes a boolean.
jaroslav@601
   704
     *
jaroslav@601
   705
     * @param   val the boolean to be written
jaroslav@601
   706
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   707
     *          stream
jaroslav@601
   708
     */
jaroslav@601
   709
    public void writeBoolean(boolean val) throws IOException {
jaroslav@601
   710
        bout.writeBoolean(val);
jaroslav@601
   711
    }
jaroslav@601
   712
jaroslav@601
   713
    /**
jaroslav@601
   714
     * Writes an 8 bit byte.
jaroslav@601
   715
     *
jaroslav@601
   716
     * @param   val the byte value to be written
jaroslav@601
   717
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   718
     *          stream
jaroslav@601
   719
     */
jaroslav@601
   720
    public void writeByte(int val) throws IOException  {
jaroslav@601
   721
        bout.writeByte(val);
jaroslav@601
   722
    }
jaroslav@601
   723
jaroslav@601
   724
    /**
jaroslav@601
   725
     * Writes a 16 bit short.
jaroslav@601
   726
     *
jaroslav@601
   727
     * @param   val the short value to be written
jaroslav@601
   728
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   729
     *          stream
jaroslav@601
   730
     */
jaroslav@601
   731
    public void writeShort(int val)  throws IOException {
jaroslav@601
   732
        bout.writeShort(val);
jaroslav@601
   733
    }
jaroslav@601
   734
jaroslav@601
   735
    /**
jaroslav@601
   736
     * Writes a 16 bit char.
jaroslav@601
   737
     *
jaroslav@601
   738
     * @param   val the char value to be written
jaroslav@601
   739
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   740
     *          stream
jaroslav@601
   741
     */
jaroslav@601
   742
    public void writeChar(int val)  throws IOException {
jaroslav@601
   743
        bout.writeChar(val);
jaroslav@601
   744
    }
jaroslav@601
   745
jaroslav@601
   746
    /**
jaroslav@601
   747
     * Writes a 32 bit int.
jaroslav@601
   748
     *
jaroslav@601
   749
     * @param   val the integer value to be written
jaroslav@601
   750
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   751
     *          stream
jaroslav@601
   752
     */
jaroslav@601
   753
    public void writeInt(int val)  throws IOException {
jaroslav@601
   754
        bout.writeInt(val);
jaroslav@601
   755
    }
jaroslav@601
   756
jaroslav@601
   757
    /**
jaroslav@601
   758
     * Writes a 64 bit long.
jaroslav@601
   759
     *
jaroslav@601
   760
     * @param   val the long value to be written
jaroslav@601
   761
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   762
     *          stream
jaroslav@601
   763
     */
jaroslav@601
   764
    public void writeLong(long val)  throws IOException {
jaroslav@601
   765
        bout.writeLong(val);
jaroslav@601
   766
    }
jaroslav@601
   767
jaroslav@601
   768
    /**
jaroslav@601
   769
     * Writes a 32 bit float.
jaroslav@601
   770
     *
jaroslav@601
   771
     * @param   val the float value to be written
jaroslav@601
   772
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   773
     *          stream
jaroslav@601
   774
     */
jaroslav@601
   775
    public void writeFloat(float val) throws IOException {
jaroslav@601
   776
        bout.writeFloat(val);
jaroslav@601
   777
    }
jaroslav@601
   778
jaroslav@601
   779
    /**
jaroslav@601
   780
     * Writes a 64 bit double.
jaroslav@601
   781
     *
jaroslav@601
   782
     * @param   val the double value to be written
jaroslav@601
   783
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   784
     *          stream
jaroslav@601
   785
     */
jaroslav@601
   786
    public void writeDouble(double val) throws IOException {
jaroslav@601
   787
        bout.writeDouble(val);
jaroslav@601
   788
    }
jaroslav@601
   789
jaroslav@601
   790
    /**
jaroslav@601
   791
     * Writes a String as a sequence of bytes.
jaroslav@601
   792
     *
jaroslav@601
   793
     * @param   str the String of bytes to be written
jaroslav@601
   794
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   795
     *          stream
jaroslav@601
   796
     */
jaroslav@601
   797
    public void writeBytes(String str) throws IOException {
jaroslav@601
   798
        bout.writeBytes(str);
jaroslav@601
   799
    }
jaroslav@601
   800
jaroslav@601
   801
    /**
jaroslav@601
   802
     * Writes a String as a sequence of chars.
jaroslav@601
   803
     *
jaroslav@601
   804
     * @param   str the String of chars to be written
jaroslav@601
   805
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   806
     *          stream
jaroslav@601
   807
     */
jaroslav@601
   808
    public void writeChars(String str) throws IOException {
jaroslav@601
   809
        bout.writeChars(str);
jaroslav@601
   810
    }
jaroslav@601
   811
jaroslav@601
   812
    /**
jaroslav@601
   813
     * Primitive data write of this String in
jaroslav@601
   814
     * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
jaroslav@601
   815
     * format.  Note that there is a
jaroslav@601
   816
     * significant difference between writing a String into the stream as
jaroslav@601
   817
     * primitive data or as an Object. A String instance written by writeObject
jaroslav@601
   818
     * is written into the stream as a String initially. Future writeObject()
jaroslav@601
   819
     * calls write references to the string into the stream.
jaroslav@601
   820
     *
jaroslav@601
   821
     * @param   str the String to be written
jaroslav@601
   822
     * @throws  IOException if I/O errors occur while writing to the underlying
jaroslav@601
   823
     *          stream
jaroslav@601
   824
     */
jaroslav@601
   825
    public void writeUTF(String str) throws IOException {
jaroslav@601
   826
        bout.writeUTF(str);
jaroslav@601
   827
    }
jaroslav@601
   828
jaroslav@601
   829
    /**
jaroslav@601
   830
     * Provide programmatic access to the persistent fields to be written
jaroslav@601
   831
     * to ObjectOutput.
jaroslav@601
   832
     *
jaroslav@601
   833
     * @since 1.2
jaroslav@601
   834
     */
jaroslav@601
   835
    public static abstract class PutField {
jaroslav@601
   836
jaroslav@601
   837
        /**
jaroslav@601
   838
         * Put the value of the named boolean field into the persistent field.
jaroslav@601
   839
         *
jaroslav@601
   840
         * @param  name the name of the serializable field
jaroslav@601
   841
         * @param  val the value to assign to the field
jaroslav@601
   842
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   843
         * match the name of a serializable field for the class whose fields
jaroslav@601
   844
         * are being written, or if the type of the named field is not
jaroslav@601
   845
         * <code>boolean</code>
jaroslav@601
   846
         */
jaroslav@601
   847
        public abstract void put(String name, boolean val);
jaroslav@601
   848
jaroslav@601
   849
        /**
jaroslav@601
   850
         * Put the value of the named byte field into the persistent field.
jaroslav@601
   851
         *
jaroslav@601
   852
         * @param  name the name of the serializable field
jaroslav@601
   853
         * @param  val the value to assign to the field
jaroslav@601
   854
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   855
         * match the name of a serializable field for the class whose fields
jaroslav@601
   856
         * are being written, or if the type of the named field is not
jaroslav@601
   857
         * <code>byte</code>
jaroslav@601
   858
         */
jaroslav@601
   859
        public abstract void put(String name, byte val);
jaroslav@601
   860
jaroslav@601
   861
        /**
jaroslav@601
   862
         * Put the value of the named char field into the persistent field.
jaroslav@601
   863
         *
jaroslav@601
   864
         * @param  name the name of the serializable field
jaroslav@601
   865
         * @param  val the value to assign to the field
jaroslav@601
   866
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   867
         * match the name of a serializable field for the class whose fields
jaroslav@601
   868
         * are being written, or if the type of the named field is not
jaroslav@601
   869
         * <code>char</code>
jaroslav@601
   870
         */
jaroslav@601
   871
        public abstract void put(String name, char val);
jaroslav@601
   872
jaroslav@601
   873
        /**
jaroslav@601
   874
         * Put the value of the named short field into the persistent field.
jaroslav@601
   875
         *
jaroslav@601
   876
         * @param  name the name of the serializable field
jaroslav@601
   877
         * @param  val the value to assign to the field
jaroslav@601
   878
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   879
         * match the name of a serializable field for the class whose fields
jaroslav@601
   880
         * are being written, or if the type of the named field is not
jaroslav@601
   881
         * <code>short</code>
jaroslav@601
   882
         */
jaroslav@601
   883
        public abstract void put(String name, short val);
jaroslav@601
   884
jaroslav@601
   885
        /**
jaroslav@601
   886
         * Put the value of the named int field into the persistent field.
jaroslav@601
   887
         *
jaroslav@601
   888
         * @param  name the name of the serializable field
jaroslav@601
   889
         * @param  val the value to assign to the field
jaroslav@601
   890
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   891
         * match the name of a serializable field for the class whose fields
jaroslav@601
   892
         * are being written, or if the type of the named field is not
jaroslav@601
   893
         * <code>int</code>
jaroslav@601
   894
         */
jaroslav@601
   895
        public abstract void put(String name, int val);
jaroslav@601
   896
jaroslav@601
   897
        /**
jaroslav@601
   898
         * Put the value of the named long field into the persistent field.
jaroslav@601
   899
         *
jaroslav@601
   900
         * @param  name the name of the serializable field
jaroslav@601
   901
         * @param  val the value to assign to the field
jaroslav@601
   902
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   903
         * match the name of a serializable field for the class whose fields
jaroslav@601
   904
         * are being written, or if the type of the named field is not
jaroslav@601
   905
         * <code>long</code>
jaroslav@601
   906
         */
jaroslav@601
   907
        public abstract void put(String name, long val);
jaroslav@601
   908
jaroslav@601
   909
        /**
jaroslav@601
   910
         * Put the value of the named float field into the persistent field.
jaroslav@601
   911
         *
jaroslav@601
   912
         * @param  name the name of the serializable field
jaroslav@601
   913
         * @param  val the value to assign to the field
jaroslav@601
   914
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   915
         * match the name of a serializable field for the class whose fields
jaroslav@601
   916
         * are being written, or if the type of the named field is not
jaroslav@601
   917
         * <code>float</code>
jaroslav@601
   918
         */
jaroslav@601
   919
        public abstract void put(String name, float val);
jaroslav@601
   920
jaroslav@601
   921
        /**
jaroslav@601
   922
         * Put the value of the named double field into the persistent field.
jaroslav@601
   923
         *
jaroslav@601
   924
         * @param  name the name of the serializable field
jaroslav@601
   925
         * @param  val the value to assign to the field
jaroslav@601
   926
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   927
         * match the name of a serializable field for the class whose fields
jaroslav@601
   928
         * are being written, or if the type of the named field is not
jaroslav@601
   929
         * <code>double</code>
jaroslav@601
   930
         */
jaroslav@601
   931
        public abstract void put(String name, double val);
jaroslav@601
   932
jaroslav@601
   933
        /**
jaroslav@601
   934
         * Put the value of the named Object field into the persistent field.
jaroslav@601
   935
         *
jaroslav@601
   936
         * @param  name the name of the serializable field
jaroslav@601
   937
         * @param  val the value to assign to the field
jaroslav@601
   938
         *         (which may be <code>null</code>)
jaroslav@601
   939
         * @throws IllegalArgumentException if <code>name</code> does not
jaroslav@601
   940
         * match the name of a serializable field for the class whose fields
jaroslav@601
   941
         * are being written, or if the type of the named field is not a
jaroslav@601
   942
         * reference type
jaroslav@601
   943
         */
jaroslav@601
   944
        public abstract void put(String name, Object val);
jaroslav@601
   945
jaroslav@601
   946
        /**
jaroslav@601
   947
         * Write the data and fields to the specified ObjectOutput stream,
jaroslav@601
   948
         * which must be the same stream that produced this
jaroslav@601
   949
         * <code>PutField</code> object.
jaroslav@601
   950
         *
jaroslav@601
   951
         * @param  out the stream to write the data and fields to
jaroslav@601
   952
         * @throws IOException if I/O errors occur while writing to the
jaroslav@601
   953
         *         underlying stream
jaroslav@601
   954
         * @throws IllegalArgumentException if the specified stream is not
jaroslav@601
   955
         *         the same stream that produced this <code>PutField</code>
jaroslav@601
   956
         *         object
jaroslav@601
   957
         * @deprecated This method does not write the values contained by this
jaroslav@601
   958
         *         <code>PutField</code> object in a proper format, and may
jaroslav@601
   959
         *         result in corruption of the serialization stream.  The
jaroslav@601
   960
         *         correct way to write <code>PutField</code> data is by
jaroslav@601
   961
         *         calling the {@link java.io.ObjectOutputStream#writeFields()}
jaroslav@601
   962
         *         method.
jaroslav@601
   963
         */
jaroslav@601
   964
        @Deprecated
jaroslav@601
   965
        public abstract void write(ObjectOutput out) throws IOException;
jaroslav@601
   966
    }
jaroslav@601
   967
jaroslav@601
   968
jaroslav@601
   969
    /**
jaroslav@601
   970
     * Returns protocol version in use.
jaroslav@601
   971
     */
jaroslav@601
   972
    int getProtocolVersion() {
jaroslav@601
   973
        return protocol;
jaroslav@601
   974
    }
jaroslav@601
   975
jaroslav@601
   976
    /**
jaroslav@601
   977
     * Writes string without allowing it to be replaced in stream.  Used by
jaroslav@601
   978
     * ObjectStreamClass to write class descriptor type strings.
jaroslav@601
   979
     */
jaroslav@601
   980
    void writeTypeString(String str) throws IOException {
jaroslav@601
   981
        int handle;
jaroslav@601
   982
        if (str == null) {
jaroslav@601
   983
            writeNull();
jaroslav@601
   984
        } else if ((handle = handles.lookup(str)) != -1) {
jaroslav@601
   985
            writeHandle(handle);
jaroslav@601
   986
        } else {
jaroslav@601
   987
            writeString(str, false);
jaroslav@601
   988
        }
jaroslav@601
   989
    }
jaroslav@601
   990
jaroslav@601
   991
    /**
jaroslav@601
   992
     * Verifies that this (possibly subclass) instance can be constructed
jaroslav@601
   993
     * without violating security constraints: the subclass must not override
jaroslav@601
   994
     * security-sensitive non-final methods, or else the
jaroslav@601
   995
     * "enableSubclassImplementation" SerializablePermission is checked.
jaroslav@601
   996
     */
jaroslav@601
   997
    private void verifySubclass() {
jaroslav@601
   998
        Class cl = getClass();
jaroslav@601
   999
        if (cl == ObjectOutputStream.class) {
jaroslav@601
  1000
            return;
jaroslav@601
  1001
        }
jaroslav@604
  1002
        throw new SecurityException();
jaroslav@601
  1003
    }
jaroslav@601
  1004
jaroslav@601
  1005
    /**
jaroslav@601
  1006
     * Clears internal data structures.
jaroslav@601
  1007
     */
jaroslav@601
  1008
    private void clear() {
jaroslav@601
  1009
        subs.clear();
jaroslav@601
  1010
        handles.clear();
jaroslav@601
  1011
    }
jaroslav@601
  1012
jaroslav@601
  1013
    /**
jaroslav@601
  1014
     * Underlying writeObject/writeUnshared implementation.
jaroslav@601
  1015
     */
jaroslav@601
  1016
    private void writeObject0(Object obj, boolean unshared)
jaroslav@601
  1017
        throws IOException
jaroslav@601
  1018
    {
jaroslav@601
  1019
        boolean oldMode = bout.setBlockDataMode(false);
jaroslav@601
  1020
        depth++;
jaroslav@601
  1021
        try {
jaroslav@601
  1022
            // handle previously written and non-replaceable objects
jaroslav@601
  1023
            int h;
jaroslav@601
  1024
            if ((obj = subs.lookup(obj)) == null) {
jaroslav@601
  1025
                writeNull();
jaroslav@601
  1026
                return;
jaroslav@601
  1027
            } else if (!unshared && (h = handles.lookup(obj)) != -1) {
jaroslav@601
  1028
                writeHandle(h);
jaroslav@601
  1029
                return;
jaroslav@601
  1030
            } else if (obj instanceof Class) {
jaroslav@601
  1031
                writeClass((Class) obj, unshared);
jaroslav@601
  1032
                return;
jaroslav@601
  1033
            } else if (obj instanceof ObjectStreamClass) {
jaroslav@601
  1034
                writeClassDesc((ObjectStreamClass) obj, unshared);
jaroslav@601
  1035
                return;
jaroslav@601
  1036
            }
jaroslav@601
  1037
jaroslav@601
  1038
            // check for replacement object
jaroslav@601
  1039
            Object orig = obj;
jaroslav@601
  1040
            Class cl = obj.getClass();
jaroslav@601
  1041
            ObjectStreamClass desc;
jaroslav@601
  1042
            for (;;) {
jaroslav@601
  1043
                // REMIND: skip this check for strings/arrays?
jaroslav@601
  1044
                Class repCl;
jaroslav@601
  1045
                desc = ObjectStreamClass.lookup(cl, true);
jaroslav@601
  1046
                if (!desc.hasWriteReplaceMethod() ||
jaroslav@601
  1047
                    (obj = desc.invokeWriteReplace(obj)) == null ||
jaroslav@601
  1048
                    (repCl = obj.getClass()) == cl)
jaroslav@601
  1049
                {
jaroslav@601
  1050
                    break;
jaroslav@601
  1051
                }
jaroslav@601
  1052
                cl = repCl;
jaroslav@601
  1053
            }
jaroslav@601
  1054
            if (enableReplace) {
jaroslav@601
  1055
                Object rep = replaceObject(obj);
jaroslav@601
  1056
                if (rep != obj && rep != null) {
jaroslav@601
  1057
                    cl = rep.getClass();
jaroslav@601
  1058
                    desc = ObjectStreamClass.lookup(cl, true);
jaroslav@601
  1059
                }
jaroslav@601
  1060
                obj = rep;
jaroslav@601
  1061
            }
jaroslav@601
  1062
jaroslav@601
  1063
            // if object replaced, run through original checks a second time
jaroslav@601
  1064
            if (obj != orig) {
jaroslav@601
  1065
                subs.assign(orig, obj);
jaroslav@601
  1066
                if (obj == null) {
jaroslav@601
  1067
                    writeNull();
jaroslav@601
  1068
                    return;
jaroslav@601
  1069
                } else if (!unshared && (h = handles.lookup(obj)) != -1) {
jaroslav@601
  1070
                    writeHandle(h);
jaroslav@601
  1071
                    return;
jaroslav@601
  1072
                } else if (obj instanceof Class) {
jaroslav@601
  1073
                    writeClass((Class) obj, unshared);
jaroslav@601
  1074
                    return;
jaroslav@601
  1075
                } else if (obj instanceof ObjectStreamClass) {
jaroslav@601
  1076
                    writeClassDesc((ObjectStreamClass) obj, unshared);
jaroslav@601
  1077
                    return;
jaroslav@601
  1078
                }
jaroslav@601
  1079
            }
jaroslav@601
  1080
jaroslav@601
  1081
            // remaining cases
jaroslav@601
  1082
            if (obj instanceof String) {
jaroslav@601
  1083
                writeString((String) obj, unshared);
jaroslav@601
  1084
            } else if (cl.isArray()) {
jaroslav@601
  1085
                writeArray(obj, desc, unshared);
jaroslav@601
  1086
            } else if (obj instanceof Enum) {
jaroslav@601
  1087
                writeEnum((Enum) obj, desc, unshared);
jaroslav@601
  1088
            } else if (obj instanceof Serializable) {
jaroslav@601
  1089
                writeOrdinaryObject(obj, desc, unshared);
jaroslav@601
  1090
            } else {
jaroslav@601
  1091
                if (extendedDebugInfo) {
jaroslav@601
  1092
                    throw new NotSerializableException(
jaroslav@601
  1093
                        cl.getName() + "\n" + debugInfoStack.toString());
jaroslav@601
  1094
                } else {
jaroslav@601
  1095
                    throw new NotSerializableException(cl.getName());
jaroslav@601
  1096
                }
jaroslav@601
  1097
            }
jaroslav@601
  1098
        } finally {
jaroslav@601
  1099
            depth--;
jaroslav@601
  1100
            bout.setBlockDataMode(oldMode);
jaroslav@601
  1101
        }
jaroslav@601
  1102
    }
jaroslav@601
  1103
jaroslav@601
  1104
    /**
jaroslav@601
  1105
     * Writes null code to stream.
jaroslav@601
  1106
     */
jaroslav@601
  1107
    private void writeNull() throws IOException {
jaroslav@601
  1108
        bout.writeByte(TC_NULL);
jaroslav@601
  1109
    }
jaroslav@601
  1110
jaroslav@601
  1111
    /**
jaroslav@601
  1112
     * Writes given object handle to stream.
jaroslav@601
  1113
     */
jaroslav@601
  1114
    private void writeHandle(int handle) throws IOException {
jaroslav@601
  1115
        bout.writeByte(TC_REFERENCE);
jaroslav@601
  1116
        bout.writeInt(baseWireHandle + handle);
jaroslav@601
  1117
    }
jaroslav@601
  1118
jaroslav@601
  1119
    /**
jaroslav@601
  1120
     * Writes representation of given class to stream.
jaroslav@601
  1121
     */
jaroslav@601
  1122
    private void writeClass(Class cl, boolean unshared) throws IOException {
jaroslav@601
  1123
        bout.writeByte(TC_CLASS);
jaroslav@601
  1124
        writeClassDesc(ObjectStreamClass.lookup(cl, true), false);
jaroslav@601
  1125
        handles.assign(unshared ? null : cl);
jaroslav@601
  1126
    }
jaroslav@601
  1127
jaroslav@601
  1128
    /**
jaroslav@601
  1129
     * Writes representation of given class descriptor to stream.
jaroslav@601
  1130
     */
jaroslav@601
  1131
    private void writeClassDesc(ObjectStreamClass desc, boolean unshared)
jaroslav@601
  1132
        throws IOException
jaroslav@601
  1133
    {
jaroslav@601
  1134
        int handle;
jaroslav@601
  1135
        if (desc == null) {
jaroslav@601
  1136
            writeNull();
jaroslav@601
  1137
        } else if (!unshared && (handle = handles.lookup(desc)) != -1) {
jaroslav@601
  1138
            writeHandle(handle);
jaroslav@601
  1139
        } else if (desc.isProxy()) {
jaroslav@601
  1140
            writeProxyDesc(desc, unshared);
jaroslav@601
  1141
        } else {
jaroslav@601
  1142
            writeNonProxyDesc(desc, unshared);
jaroslav@601
  1143
        }
jaroslav@601
  1144
    }
jaroslav@601
  1145
jaroslav@601
  1146
    /**
jaroslav@601
  1147
     * Writes class descriptor representing a dynamic proxy class to stream.
jaroslav@601
  1148
     */
jaroslav@601
  1149
    private void writeProxyDesc(ObjectStreamClass desc, boolean unshared)
jaroslav@601
  1150
        throws IOException
jaroslav@601
  1151
    {
jaroslav@601
  1152
        bout.writeByte(TC_PROXYCLASSDESC);
jaroslav@601
  1153
        handles.assign(unshared ? null : desc);
jaroslav@601
  1154
jaroslav@601
  1155
        Class cl = desc.forClass();
jaroslav@601
  1156
        Class[] ifaces = cl.getInterfaces();
jaroslav@601
  1157
        bout.writeInt(ifaces.length);
jaroslav@601
  1158
        for (int i = 0; i < ifaces.length; i++) {
jaroslav@601
  1159
            bout.writeUTF(ifaces[i].getName());
jaroslav@601
  1160
        }
jaroslav@601
  1161
jaroslav@601
  1162
        bout.setBlockDataMode(true);
jaroslav@601
  1163
        annotateProxyClass(cl);
jaroslav@601
  1164
        bout.setBlockDataMode(false);
jaroslav@601
  1165
        bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1166
jaroslav@601
  1167
        writeClassDesc(desc.getSuperDesc(), false);
jaroslav@601
  1168
    }
jaroslav@601
  1169
jaroslav@601
  1170
    /**
jaroslav@601
  1171
     * Writes class descriptor representing a standard (i.e., not a dynamic
jaroslav@601
  1172
     * proxy) class to stream.
jaroslav@601
  1173
     */
jaroslav@601
  1174
    private void writeNonProxyDesc(ObjectStreamClass desc, boolean unshared)
jaroslav@601
  1175
        throws IOException
jaroslav@601
  1176
    {
jaroslav@601
  1177
        bout.writeByte(TC_CLASSDESC);
jaroslav@601
  1178
        handles.assign(unshared ? null : desc);
jaroslav@601
  1179
jaroslav@601
  1180
        if (protocol == PROTOCOL_VERSION_1) {
jaroslav@601
  1181
            // do not invoke class descriptor write hook with old protocol
jaroslav@601
  1182
            desc.writeNonProxy(this);
jaroslav@601
  1183
        } else {
jaroslav@601
  1184
            writeClassDescriptor(desc);
jaroslav@601
  1185
        }
jaroslav@601
  1186
jaroslav@601
  1187
        Class cl = desc.forClass();
jaroslav@601
  1188
        bout.setBlockDataMode(true);
jaroslav@601
  1189
        annotateClass(cl);
jaroslav@601
  1190
        bout.setBlockDataMode(false);
jaroslav@601
  1191
        bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1192
jaroslav@601
  1193
        writeClassDesc(desc.getSuperDesc(), false);
jaroslav@601
  1194
    }
jaroslav@601
  1195
jaroslav@601
  1196
    /**
jaroslav@601
  1197
     * Writes given string to stream, using standard or long UTF format
jaroslav@601
  1198
     * depending on string length.
jaroslav@601
  1199
     */
jaroslav@601
  1200
    private void writeString(String str, boolean unshared) throws IOException {
jaroslav@601
  1201
        handles.assign(unshared ? null : str);
jaroslav@601
  1202
        long utflen = bout.getUTFLength(str);
jaroslav@601
  1203
        if (utflen <= 0xFFFF) {
jaroslav@601
  1204
            bout.writeByte(TC_STRING);
jaroslav@601
  1205
            bout.writeUTF(str, utflen);
jaroslav@601
  1206
        } else {
jaroslav@601
  1207
            bout.writeByte(TC_LONGSTRING);
jaroslav@601
  1208
            bout.writeLongUTF(str, utflen);
jaroslav@601
  1209
        }
jaroslav@601
  1210
    }
jaroslav@601
  1211
jaroslav@601
  1212
    /**
jaroslav@601
  1213
     * Writes given array object to stream.
jaroslav@601
  1214
     */
jaroslav@601
  1215
    private void writeArray(Object array,
jaroslav@601
  1216
                            ObjectStreamClass desc,
jaroslav@601
  1217
                            boolean unshared)
jaroslav@601
  1218
        throws IOException
jaroslav@601
  1219
    {
jaroslav@601
  1220
        bout.writeByte(TC_ARRAY);
jaroslav@601
  1221
        writeClassDesc(desc, false);
jaroslav@601
  1222
        handles.assign(unshared ? null : array);
jaroslav@601
  1223
jaroslav@601
  1224
        Class ccl = desc.forClass().getComponentType();
jaroslav@601
  1225
        if (ccl.isPrimitive()) {
jaroslav@601
  1226
            if (ccl == Integer.TYPE) {
jaroslav@601
  1227
                int[] ia = (int[]) array;
jaroslav@601
  1228
                bout.writeInt(ia.length);
jaroslav@601
  1229
                bout.writeInts(ia, 0, ia.length);
jaroslav@601
  1230
            } else if (ccl == Byte.TYPE) {
jaroslav@601
  1231
                byte[] ba = (byte[]) array;
jaroslav@601
  1232
                bout.writeInt(ba.length);
jaroslav@601
  1233
                bout.write(ba, 0, ba.length, true);
jaroslav@601
  1234
            } else if (ccl == Long.TYPE) {
jaroslav@601
  1235
                long[] ja = (long[]) array;
jaroslav@601
  1236
                bout.writeInt(ja.length);
jaroslav@601
  1237
                bout.writeLongs(ja, 0, ja.length);
jaroslav@601
  1238
            } else if (ccl == Float.TYPE) {
jaroslav@601
  1239
                float[] fa = (float[]) array;
jaroslav@601
  1240
                bout.writeInt(fa.length);
jaroslav@601
  1241
                bout.writeFloats(fa, 0, fa.length);
jaroslav@601
  1242
            } else if (ccl == Double.TYPE) {
jaroslav@601
  1243
                double[] da = (double[]) array;
jaroslav@601
  1244
                bout.writeInt(da.length);
jaroslav@601
  1245
                bout.writeDoubles(da, 0, da.length);
jaroslav@601
  1246
            } else if (ccl == Short.TYPE) {
jaroslav@601
  1247
                short[] sa = (short[]) array;
jaroslav@601
  1248
                bout.writeInt(sa.length);
jaroslav@601
  1249
                bout.writeShorts(sa, 0, sa.length);
jaroslav@601
  1250
            } else if (ccl == Character.TYPE) {
jaroslav@601
  1251
                char[] ca = (char[]) array;
jaroslav@601
  1252
                bout.writeInt(ca.length);
jaroslav@601
  1253
                bout.writeChars(ca, 0, ca.length);
jaroslav@601
  1254
            } else if (ccl == Boolean.TYPE) {
jaroslav@601
  1255
                boolean[] za = (boolean[]) array;
jaroslav@601
  1256
                bout.writeInt(za.length);
jaroslav@601
  1257
                bout.writeBooleans(za, 0, za.length);
jaroslav@601
  1258
            } else {
jaroslav@601
  1259
                throw new InternalError();
jaroslav@601
  1260
            }
jaroslav@601
  1261
        } else {
jaroslav@601
  1262
            Object[] objs = (Object[]) array;
jaroslav@601
  1263
            int len = objs.length;
jaroslav@601
  1264
            bout.writeInt(len);
jaroslav@601
  1265
            if (extendedDebugInfo) {
jaroslav@601
  1266
                debugInfoStack.push(
jaroslav@601
  1267
                    "array (class \"" + array.getClass().getName() +
jaroslav@601
  1268
                    "\", size: " + len  + ")");
jaroslav@601
  1269
            }
jaroslav@601
  1270
            try {
jaroslav@601
  1271
                for (int i = 0; i < len; i++) {
jaroslav@601
  1272
                    if (extendedDebugInfo) {
jaroslav@601
  1273
                        debugInfoStack.push(
jaroslav@601
  1274
                            "element of array (index: " + i + ")");
jaroslav@601
  1275
                    }
jaroslav@601
  1276
                    try {
jaroslav@601
  1277
                        writeObject0(objs[i], false);
jaroslav@601
  1278
                    } finally {
jaroslav@601
  1279
                        if (extendedDebugInfo) {
jaroslav@601
  1280
                            debugInfoStack.pop();
jaroslav@601
  1281
                        }
jaroslav@601
  1282
                    }
jaroslav@601
  1283
                }
jaroslav@601
  1284
            } finally {
jaroslav@601
  1285
                if (extendedDebugInfo) {
jaroslav@601
  1286
                    debugInfoStack.pop();
jaroslav@601
  1287
                }
jaroslav@601
  1288
            }
jaroslav@601
  1289
        }
jaroslav@601
  1290
    }
jaroslav@601
  1291
jaroslav@601
  1292
    /**
jaroslav@601
  1293
     * Writes given enum constant to stream.
jaroslav@601
  1294
     */
jaroslav@601
  1295
    private void writeEnum(Enum en,
jaroslav@601
  1296
                           ObjectStreamClass desc,
jaroslav@601
  1297
                           boolean unshared)
jaroslav@601
  1298
        throws IOException
jaroslav@601
  1299
    {
jaroslav@601
  1300
        bout.writeByte(TC_ENUM);
jaroslav@601
  1301
        ObjectStreamClass sdesc = desc.getSuperDesc();
jaroslav@601
  1302
        writeClassDesc((sdesc.forClass() == Enum.class) ? desc : sdesc, false);
jaroslav@601
  1303
        handles.assign(unshared ? null : en);
jaroslav@601
  1304
        writeString(en.name(), false);
jaroslav@601
  1305
    }
jaroslav@601
  1306
jaroslav@601
  1307
    /**
jaroslav@601
  1308
     * Writes representation of a "ordinary" (i.e., not a String, Class,
jaroslav@601
  1309
     * ObjectStreamClass, array, or enum constant) serializable object to the
jaroslav@601
  1310
     * stream.
jaroslav@601
  1311
     */
jaroslav@601
  1312
    private void writeOrdinaryObject(Object obj,
jaroslav@601
  1313
                                     ObjectStreamClass desc,
jaroslav@601
  1314
                                     boolean unshared)
jaroslav@601
  1315
        throws IOException
jaroslav@601
  1316
    {
jaroslav@601
  1317
        if (extendedDebugInfo) {
jaroslav@601
  1318
            debugInfoStack.push(
jaroslav@601
  1319
                (depth == 1 ? "root " : "") + "object (class \"" +
jaroslav@601
  1320
                obj.getClass().getName() + "\", " + obj.toString() + ")");
jaroslav@601
  1321
        }
jaroslav@601
  1322
        try {
jaroslav@601
  1323
            desc.checkSerialize();
jaroslav@601
  1324
jaroslav@601
  1325
            bout.writeByte(TC_OBJECT);
jaroslav@601
  1326
            writeClassDesc(desc, false);
jaroslav@601
  1327
            handles.assign(unshared ? null : obj);
jaroslav@601
  1328
            if (desc.isExternalizable() && !desc.isProxy()) {
jaroslav@601
  1329
                writeExternalData((Externalizable) obj);
jaroslav@601
  1330
            } else {
jaroslav@601
  1331
                writeSerialData(obj, desc);
jaroslav@601
  1332
            }
jaroslav@601
  1333
        } finally {
jaroslav@601
  1334
            if (extendedDebugInfo) {
jaroslav@601
  1335
                debugInfoStack.pop();
jaroslav@601
  1336
            }
jaroslav@601
  1337
        }
jaroslav@601
  1338
    }
jaroslav@601
  1339
jaroslav@601
  1340
    /**
jaroslav@601
  1341
     * Writes externalizable data of given object by invoking its
jaroslav@601
  1342
     * writeExternal() method.
jaroslav@601
  1343
     */
jaroslav@601
  1344
    private void writeExternalData(Externalizable obj) throws IOException {
jaroslav@601
  1345
        PutFieldImpl oldPut = curPut;
jaroslav@601
  1346
        curPut = null;
jaroslav@601
  1347
jaroslav@601
  1348
        if (extendedDebugInfo) {
jaroslav@601
  1349
            debugInfoStack.push("writeExternal data");
jaroslav@601
  1350
        }
jaroslav@604
  1351
        Object oldContext = curContext;
jaroslav@601
  1352
        try {
jaroslav@601
  1353
            curContext = null;
jaroslav@601
  1354
            if (protocol == PROTOCOL_VERSION_1) {
jaroslav@601
  1355
                obj.writeExternal(this);
jaroslav@601
  1356
            } else {
jaroslav@601
  1357
                bout.setBlockDataMode(true);
jaroslav@601
  1358
                obj.writeExternal(this);
jaroslav@601
  1359
                bout.setBlockDataMode(false);
jaroslav@601
  1360
                bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1361
            }
jaroslav@601
  1362
        } finally {
jaroslav@601
  1363
            curContext = oldContext;
jaroslav@601
  1364
            if (extendedDebugInfo) {
jaroslav@601
  1365
                debugInfoStack.pop();
jaroslav@601
  1366
            }
jaroslav@601
  1367
        }
jaroslav@601
  1368
jaroslav@601
  1369
        curPut = oldPut;
jaroslav@601
  1370
    }
jaroslav@601
  1371
jaroslav@601
  1372
    /**
jaroslav@601
  1373
     * Writes instance data for each serializable class of given object, from
jaroslav@601
  1374
     * superclass to subclass.
jaroslav@601
  1375
     */
jaroslav@601
  1376
    private void writeSerialData(Object obj, ObjectStreamClass desc)
jaroslav@601
  1377
        throws IOException
jaroslav@601
  1378
    {
jaroslav@601
  1379
        ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
jaroslav@601
  1380
        for (int i = 0; i < slots.length; i++) {
jaroslav@601
  1381
            ObjectStreamClass slotDesc = slots[i].desc;
jaroslav@601
  1382
            if (slotDesc.hasWriteObjectMethod()) {
jaroslav@601
  1383
                PutFieldImpl oldPut = curPut;
jaroslav@601
  1384
                curPut = null;
jaroslav@604
  1385
                Object oldContext = curContext;
jaroslav@601
  1386
jaroslav@601
  1387
                if (extendedDebugInfo) {
jaroslav@601
  1388
                    debugInfoStack.push(
jaroslav@601
  1389
                        "custom writeObject data (class \"" +
jaroslav@601
  1390
                        slotDesc.getName() + "\")");
jaroslav@601
  1391
                }
jaroslav@601
  1392
                try {
jaroslav@604
  1393
                    curContext = new Object(); //new SerialCallbackContext(obj, slotDesc);
jaroslav@601
  1394
                    bout.setBlockDataMode(true);
jaroslav@601
  1395
                    slotDesc.invokeWriteObject(obj, this);
jaroslav@601
  1396
                    bout.setBlockDataMode(false);
jaroslav@601
  1397
                    bout.writeByte(TC_ENDBLOCKDATA);
jaroslav@601
  1398
                } finally {
jaroslav@604
  1399
                    //curContext.setUsed();
jaroslav@601
  1400
                    curContext = oldContext;
jaroslav@601
  1401
                    if (extendedDebugInfo) {
jaroslav@601
  1402
                        debugInfoStack.pop();
jaroslav@601
  1403
                    }
jaroslav@601
  1404
                }
jaroslav@601
  1405
jaroslav@601
  1406
                curPut = oldPut;
jaroslav@601
  1407
            } else {
jaroslav@601
  1408
                defaultWriteFields(obj, slotDesc);
jaroslav@601
  1409
            }
jaroslav@601
  1410
        }
jaroslav@601
  1411
    }
jaroslav@601
  1412
jaroslav@601
  1413
    /**
jaroslav@601
  1414
     * Fetches and writes values of serializable fields of given object to
jaroslav@601
  1415
     * stream.  The given class descriptor specifies which field values to
jaroslav@601
  1416
     * write, and in which order they should be written.
jaroslav@601
  1417
     */
jaroslav@601
  1418
    private void defaultWriteFields(Object obj, ObjectStreamClass desc)
jaroslav@601
  1419
        throws IOException
jaroslav@601
  1420
    {
jaroslav@601
  1421
        // REMIND: perform conservative isInstance check here?
jaroslav@601
  1422
        desc.checkDefaultSerialize();
jaroslav@601
  1423
jaroslav@601
  1424
        int primDataSize = desc.getPrimDataSize();
jaroslav@601
  1425
        if (primVals == null || primVals.length < primDataSize) {
jaroslav@601
  1426
            primVals = new byte[primDataSize];
jaroslav@601
  1427
        }
jaroslav@601
  1428
        desc.getPrimFieldValues(obj, primVals);
jaroslav@601
  1429
        bout.write(primVals, 0, primDataSize, false);
jaroslav@601
  1430
jaroslav@601
  1431
        ObjectStreamField[] fields = desc.getFields(false);
jaroslav@601
  1432
        Object[] objVals = new Object[desc.getNumObjFields()];
jaroslav@601
  1433
        int numPrimFields = fields.length - objVals.length;
jaroslav@601
  1434
        desc.getObjFieldValues(obj, objVals);
jaroslav@601
  1435
        for (int i = 0; i < objVals.length; i++) {
jaroslav@601
  1436
            if (extendedDebugInfo) {
jaroslav@601
  1437
                debugInfoStack.push(
jaroslav@601
  1438
                    "field (class \"" + desc.getName() + "\", name: \"" +
jaroslav@601
  1439
                    fields[numPrimFields + i].getName() + "\", type: \"" +
jaroslav@601
  1440
                    fields[numPrimFields + i].getType() + "\")");
jaroslav@601
  1441
            }
jaroslav@601
  1442
            try {
jaroslav@601
  1443
                writeObject0(objVals[i],
jaroslav@601
  1444
                             fields[numPrimFields + i].isUnshared());
jaroslav@601
  1445
            } finally {
jaroslav@601
  1446
                if (extendedDebugInfo) {
jaroslav@601
  1447
                    debugInfoStack.pop();
jaroslav@601
  1448
                }
jaroslav@601
  1449
            }
jaroslav@601
  1450
        }
jaroslav@601
  1451
    }
jaroslav@601
  1452
jaroslav@601
  1453
    /**
jaroslav@601
  1454
     * Attempts to write to stream fatal IOException that has caused
jaroslav@601
  1455
     * serialization to abort.
jaroslav@601
  1456
     */
jaroslav@601
  1457
    private void writeFatalException(IOException ex) throws IOException {
jaroslav@601
  1458
        /*
jaroslav@601
  1459
         * Note: the serialization specification states that if a second
jaroslav@601
  1460
         * IOException occurs while attempting to serialize the original fatal
jaroslav@601
  1461
         * exception to the stream, then a StreamCorruptedException should be
jaroslav@601
  1462
         * thrown (section 2.1).  However, due to a bug in previous
jaroslav@601
  1463
         * implementations of serialization, StreamCorruptedExceptions were
jaroslav@601
  1464
         * rarely (if ever) actually thrown--the "root" exceptions from
jaroslav@601
  1465
         * underlying streams were thrown instead.  This historical behavior is
jaroslav@601
  1466
         * followed here for consistency.
jaroslav@601
  1467
         */
jaroslav@601
  1468
        clear();
jaroslav@601
  1469
        boolean oldMode = bout.setBlockDataMode(false);
jaroslav@601
  1470
        try {
jaroslav@601
  1471
            bout.writeByte(TC_EXCEPTION);
jaroslav@601
  1472
            writeObject0(ex, false);
jaroslav@601
  1473
            clear();
jaroslav@601
  1474
        } finally {
jaroslav@601
  1475
            bout.setBlockDataMode(oldMode);
jaroslav@601
  1476
        }
jaroslav@601
  1477
    }
jaroslav@601
  1478
jaroslav@601
  1479
    /**
jaroslav@601
  1480
     * Converts specified span of float values into byte values.
jaroslav@601
  1481
     */
jaroslav@601
  1482
    // REMIND: remove once hotspot inlines Float.floatToIntBits
jaroslav@601
  1483
    private static native void floatsToBytes(float[] src, int srcpos,
jaroslav@601
  1484
                                             byte[] dst, int dstpos,
jaroslav@601
  1485
                                             int nfloats);
jaroslav@601
  1486
jaroslav@601
  1487
    /**
jaroslav@601
  1488
     * Converts specified span of double values into byte values.
jaroslav@601
  1489
     */
jaroslav@601
  1490
    // REMIND: remove once hotspot inlines Double.doubleToLongBits
jaroslav@601
  1491
    private static native void doublesToBytes(double[] src, int srcpos,
jaroslav@601
  1492
                                              byte[] dst, int dstpos,
jaroslav@601
  1493
                                              int ndoubles);
jaroslav@601
  1494
jaroslav@601
  1495
    /**
jaroslav@601
  1496
     * Default PutField implementation.
jaroslav@601
  1497
     */
jaroslav@601
  1498
    private class PutFieldImpl extends PutField {
jaroslav@601
  1499
jaroslav@601
  1500
        /** class descriptor describing serializable fields */
jaroslav@601
  1501
        private final ObjectStreamClass desc;
jaroslav@601
  1502
        /** primitive field values */
jaroslav@601
  1503
        private final byte[] primVals;
jaroslav@601
  1504
        /** object field values */
jaroslav@601
  1505
        private final Object[] objVals;
jaroslav@601
  1506
jaroslav@601
  1507
        /**
jaroslav@601
  1508
         * Creates PutFieldImpl object for writing fields defined in given
jaroslav@601
  1509
         * class descriptor.
jaroslav@601
  1510
         */
jaroslav@601
  1511
        PutFieldImpl(ObjectStreamClass desc) {
jaroslav@601
  1512
            this.desc = desc;
jaroslav@601
  1513
            primVals = new byte[desc.getPrimDataSize()];
jaroslav@601
  1514
            objVals = new Object[desc.getNumObjFields()];
jaroslav@601
  1515
        }
jaroslav@601
  1516
jaroslav@601
  1517
        public void put(String name, boolean val) {
jaroslav@601
  1518
            Bits.putBoolean(primVals, getFieldOffset(name, Boolean.TYPE), val);
jaroslav@601
  1519
        }
jaroslav@601
  1520
jaroslav@601
  1521
        public void put(String name, byte val) {
jaroslav@601
  1522
            primVals[getFieldOffset(name, Byte.TYPE)] = val;
jaroslav@601
  1523
        }
jaroslav@601
  1524
jaroslav@601
  1525
        public void put(String name, char val) {
jaroslav@601
  1526
            Bits.putChar(primVals, getFieldOffset(name, Character.TYPE), val);
jaroslav@601
  1527
        }
jaroslav@601
  1528
jaroslav@601
  1529
        public void put(String name, short val) {
jaroslav@601
  1530
            Bits.putShort(primVals, getFieldOffset(name, Short.TYPE), val);
jaroslav@601
  1531
        }
jaroslav@601
  1532
jaroslav@601
  1533
        public void put(String name, int val) {
jaroslav@601
  1534
            Bits.putInt(primVals, getFieldOffset(name, Integer.TYPE), val);
jaroslav@601
  1535
        }
jaroslav@601
  1536
jaroslav@601
  1537
        public void put(String name, float val) {
jaroslav@601
  1538
            Bits.putFloat(primVals, getFieldOffset(name, Float.TYPE), val);
jaroslav@601
  1539
        }
jaroslav@601
  1540
jaroslav@601
  1541
        public void put(String name, long val) {
jaroslav@601
  1542
            Bits.putLong(primVals, getFieldOffset(name, Long.TYPE), val);
jaroslav@601
  1543
        }
jaroslav@601
  1544
jaroslav@601
  1545
        public void put(String name, double val) {
jaroslav@601
  1546
            Bits.putDouble(primVals, getFieldOffset(name, Double.TYPE), val);
jaroslav@601
  1547
        }
jaroslav@601
  1548
jaroslav@601
  1549
        public void put(String name, Object val) {
jaroslav@601
  1550
            objVals[getFieldOffset(name, Object.class)] = val;
jaroslav@601
  1551
        }
jaroslav@601
  1552
jaroslav@601
  1553
        // deprecated in ObjectOutputStream.PutField
jaroslav@601
  1554
        public void write(ObjectOutput out) throws IOException {
jaroslav@601
  1555
            /*
jaroslav@601
  1556
             * Applications should *not* use this method to write PutField
jaroslav@601
  1557
             * data, as it will lead to stream corruption if the PutField
jaroslav@601
  1558
             * object writes any primitive data (since block data mode is not
jaroslav@601
  1559
             * unset/set properly, as is done in OOS.writeFields()).  This
jaroslav@601
  1560
             * broken implementation is being retained solely for behavioral
jaroslav@601
  1561
             * compatibility, in order to support applications which use
jaroslav@601
  1562
             * OOS.PutField.write() for writing only non-primitive data.
jaroslav@601
  1563
             *
jaroslav@601
  1564
             * Serialization of unshared objects is not implemented here since
jaroslav@601
  1565
             * it is not necessary for backwards compatibility; also, unshared
jaroslav@601
  1566
             * semantics may not be supported by the given ObjectOutput
jaroslav@601
  1567
             * instance.  Applications which write unshared objects using the
jaroslav@601
  1568
             * PutField API must use OOS.writeFields().
jaroslav@601
  1569
             */
jaroslav@601
  1570
            if (ObjectOutputStream.this != out) {
jaroslav@601
  1571
                throw new IllegalArgumentException("wrong stream");
jaroslav@601
  1572
            }
jaroslav@601
  1573
            out.write(primVals, 0, primVals.length);
jaroslav@601
  1574
jaroslav@601
  1575
            ObjectStreamField[] fields = desc.getFields(false);
jaroslav@601
  1576
            int numPrimFields = fields.length - objVals.length;
jaroslav@601
  1577
            // REMIND: warn if numPrimFields > 0?
jaroslav@601
  1578
            for (int i = 0; i < objVals.length; i++) {
jaroslav@601
  1579
                if (fields[numPrimFields + i].isUnshared()) {
jaroslav@601
  1580
                    throw new IOException("cannot write unshared object");
jaroslav@601
  1581
                }
jaroslav@601
  1582
                out.writeObject(objVals[i]);
jaroslav@601
  1583
            }
jaroslav@601
  1584
        }
jaroslav@601
  1585
jaroslav@601
  1586
        /**
jaroslav@601
  1587
         * Writes buffered primitive data and object fields to stream.
jaroslav@601
  1588
         */
jaroslav@601
  1589
        void writeFields() throws IOException {
jaroslav@601
  1590
            bout.write(primVals, 0, primVals.length, false);
jaroslav@601
  1591
jaroslav@601
  1592
            ObjectStreamField[] fields = desc.getFields(false);
jaroslav@601
  1593
            int numPrimFields = fields.length - objVals.length;
jaroslav@601
  1594
            for (int i = 0; i < objVals.length; i++) {
jaroslav@601
  1595
                if (extendedDebugInfo) {
jaroslav@601
  1596
                    debugInfoStack.push(
jaroslav@601
  1597
                        "field (class \"" + desc.getName() + "\", name: \"" +
jaroslav@601
  1598
                        fields[numPrimFields + i].getName() + "\", type: \"" +
jaroslav@601
  1599
                        fields[numPrimFields + i].getType() + "\")");
jaroslav@601
  1600
                }
jaroslav@601
  1601
                try {
jaroslav@601
  1602
                    writeObject0(objVals[i],
jaroslav@601
  1603
                                 fields[numPrimFields + i].isUnshared());
jaroslav@601
  1604
                } finally {
jaroslav@601
  1605
                    if (extendedDebugInfo) {
jaroslav@601
  1606
                        debugInfoStack.pop();
jaroslav@601
  1607
                    }
jaroslav@601
  1608
                }
jaroslav@601
  1609
            }
jaroslav@601
  1610
        }
jaroslav@601
  1611
jaroslav@601
  1612
        /**
jaroslav@601
  1613
         * Returns offset of field with given name and type.  A specified type
jaroslav@601
  1614
         * of null matches all types, Object.class matches all non-primitive
jaroslav@601
  1615
         * types, and any other non-null type matches assignable types only.
jaroslav@601
  1616
         * Throws IllegalArgumentException if no matching field found.
jaroslav@601
  1617
         */
jaroslav@601
  1618
        private int getFieldOffset(String name, Class type) {
jaroslav@601
  1619
            ObjectStreamField field = desc.getField(name, type);
jaroslav@601
  1620
            if (field == null) {
jaroslav@601
  1621
                throw new IllegalArgumentException("no such field " + name +
jaroslav@601
  1622
                                                   " with type " + type);
jaroslav@601
  1623
            }
jaroslav@601
  1624
            return field.getOffset();
jaroslav@601
  1625
        }
jaroslav@601
  1626
    }
jaroslav@601
  1627
jaroslav@601
  1628
    /**
jaroslav@601
  1629
     * Buffered output stream with two modes: in default mode, outputs data in
jaroslav@601
  1630
     * same format as DataOutputStream; in "block data" mode, outputs data
jaroslav@601
  1631
     * bracketed by block data markers (see object serialization specification
jaroslav@601
  1632
     * for details).
jaroslav@601
  1633
     */
jaroslav@601
  1634
    private static class BlockDataOutputStream
jaroslav@601
  1635
        extends OutputStream implements DataOutput
jaroslav@601
  1636
    {
jaroslav@601
  1637
        /** maximum data block length */
jaroslav@601
  1638
        private static final int MAX_BLOCK_SIZE = 1024;
jaroslav@601
  1639
        /** maximum data block header length */
jaroslav@601
  1640
        private static final int MAX_HEADER_SIZE = 5;
jaroslav@601
  1641
        /** (tunable) length of char buffer (for writing strings) */
jaroslav@601
  1642
        private static final int CHAR_BUF_SIZE = 256;
jaroslav@601
  1643
jaroslav@601
  1644
        /** buffer for writing general/block data */
jaroslav@601
  1645
        private final byte[] buf = new byte[MAX_BLOCK_SIZE];
jaroslav@601
  1646
        /** buffer for writing block data headers */
jaroslav@601
  1647
        private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
jaroslav@601
  1648
        /** char buffer for fast string writes */
jaroslav@601
  1649
        private final char[] cbuf = new char[CHAR_BUF_SIZE];
jaroslav@601
  1650
jaroslav@601
  1651
        /** block data mode */
jaroslav@601
  1652
        private boolean blkmode = false;
jaroslav@601
  1653
        /** current offset into buf */
jaroslav@601
  1654
        private int pos = 0;
jaroslav@601
  1655
jaroslav@601
  1656
        /** underlying output stream */
jaroslav@601
  1657
        private final OutputStream out;
jaroslav@601
  1658
        /** loopback stream (for data writes that span data blocks) */
jaroslav@601
  1659
        private final DataOutputStream dout;
jaroslav@601
  1660
jaroslav@601
  1661
        /**
jaroslav@601
  1662
         * Creates new BlockDataOutputStream on top of given underlying stream.
jaroslav@601
  1663
         * Block data mode is turned off by default.
jaroslav@601
  1664
         */
jaroslav@601
  1665
        BlockDataOutputStream(OutputStream out) {
jaroslav@601
  1666
            this.out = out;
jaroslav@601
  1667
            dout = new DataOutputStream(this);
jaroslav@601
  1668
        }
jaroslav@601
  1669
jaroslav@601
  1670
        /**
jaroslav@601
  1671
         * Sets block data mode to the given mode (true == on, false == off)
jaroslav@601
  1672
         * and returns the previous mode value.  If the new mode is the same as
jaroslav@601
  1673
         * the old mode, no action is taken.  If the new mode differs from the
jaroslav@601
  1674
         * old mode, any buffered data is flushed before switching to the new
jaroslav@601
  1675
         * mode.
jaroslav@601
  1676
         */
jaroslav@601
  1677
        boolean setBlockDataMode(boolean mode) throws IOException {
jaroslav@601
  1678
            if (blkmode == mode) {
jaroslav@601
  1679
                return blkmode;
jaroslav@601
  1680
            }
jaroslav@601
  1681
            drain();
jaroslav@601
  1682
            blkmode = mode;
jaroslav@601
  1683
            return !blkmode;
jaroslav@601
  1684
        }
jaroslav@601
  1685
jaroslav@601
  1686
        /**
jaroslav@601
  1687
         * Returns true if the stream is currently in block data mode, false
jaroslav@601
  1688
         * otherwise.
jaroslav@601
  1689
         */
jaroslav@601
  1690
        boolean getBlockDataMode() {
jaroslav@601
  1691
            return blkmode;
jaroslav@601
  1692
        }
jaroslav@601
  1693
jaroslav@601
  1694
        /* ----------------- generic output stream methods ----------------- */
jaroslav@601
  1695
        /*
jaroslav@601
  1696
         * The following methods are equivalent to their counterparts in
jaroslav@601
  1697
         * OutputStream, except that they partition written data into data
jaroslav@601
  1698
         * blocks when in block data mode.
jaroslav@601
  1699
         */
jaroslav@601
  1700
jaroslav@601
  1701
        public void write(int b) throws IOException {
jaroslav@601
  1702
            if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1703
                drain();
jaroslav@601
  1704
            }
jaroslav@601
  1705
            buf[pos++] = (byte) b;
jaroslav@601
  1706
        }
jaroslav@601
  1707
jaroslav@601
  1708
        public void write(byte[] b) throws IOException {
jaroslav@601
  1709
            write(b, 0, b.length, false);
jaroslav@601
  1710
        }
jaroslav@601
  1711
jaroslav@601
  1712
        public void write(byte[] b, int off, int len) throws IOException {
jaroslav@601
  1713
            write(b, off, len, false);
jaroslav@601
  1714
        }
jaroslav@601
  1715
jaroslav@601
  1716
        public void flush() throws IOException {
jaroslav@601
  1717
            drain();
jaroslav@601
  1718
            out.flush();
jaroslav@601
  1719
        }
jaroslav@601
  1720
jaroslav@601
  1721
        public void close() throws IOException {
jaroslav@601
  1722
            flush();
jaroslav@601
  1723
            out.close();
jaroslav@601
  1724
        }
jaroslav@601
  1725
jaroslav@601
  1726
        /**
jaroslav@601
  1727
         * Writes specified span of byte values from given array.  If copy is
jaroslav@601
  1728
         * true, copies the values to an intermediate buffer before writing
jaroslav@601
  1729
         * them to underlying stream (to avoid exposing a reference to the
jaroslav@601
  1730
         * original byte array).
jaroslav@601
  1731
         */
jaroslav@601
  1732
        void write(byte[] b, int off, int len, boolean copy)
jaroslav@601
  1733
            throws IOException
jaroslav@601
  1734
        {
jaroslav@601
  1735
            if (!(copy || blkmode)) {           // write directly
jaroslav@601
  1736
                drain();
jaroslav@601
  1737
                out.write(b, off, len);
jaroslav@601
  1738
                return;
jaroslav@601
  1739
            }
jaroslav@601
  1740
jaroslav@601
  1741
            while (len > 0) {
jaroslav@601
  1742
                if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1743
                    drain();
jaroslav@601
  1744
                }
jaroslav@601
  1745
                if (len >= MAX_BLOCK_SIZE && !copy && pos == 0) {
jaroslav@601
  1746
                    // avoid unnecessary copy
jaroslav@601
  1747
                    writeBlockHeader(MAX_BLOCK_SIZE);
jaroslav@601
  1748
                    out.write(b, off, MAX_BLOCK_SIZE);
jaroslav@601
  1749
                    off += MAX_BLOCK_SIZE;
jaroslav@601
  1750
                    len -= MAX_BLOCK_SIZE;
jaroslav@601
  1751
                } else {
jaroslav@601
  1752
                    int wlen = Math.min(len, MAX_BLOCK_SIZE - pos);
jaroslav@601
  1753
                    System.arraycopy(b, off, buf, pos, wlen);
jaroslav@601
  1754
                    pos += wlen;
jaroslav@601
  1755
                    off += wlen;
jaroslav@601
  1756
                    len -= wlen;
jaroslav@601
  1757
                }
jaroslav@601
  1758
            }
jaroslav@601
  1759
        }
jaroslav@601
  1760
jaroslav@601
  1761
        /**
jaroslav@601
  1762
         * Writes all buffered data from this stream to the underlying stream,
jaroslav@601
  1763
         * but does not flush underlying stream.
jaroslav@601
  1764
         */
jaroslav@601
  1765
        void drain() throws IOException {
jaroslav@601
  1766
            if (pos == 0) {
jaroslav@601
  1767
                return;
jaroslav@601
  1768
            }
jaroslav@601
  1769
            if (blkmode) {
jaroslav@601
  1770
                writeBlockHeader(pos);
jaroslav@601
  1771
            }
jaroslav@601
  1772
            out.write(buf, 0, pos);
jaroslav@601
  1773
            pos = 0;
jaroslav@601
  1774
        }
jaroslav@601
  1775
jaroslav@601
  1776
        /**
jaroslav@601
  1777
         * Writes block data header.  Data blocks shorter than 256 bytes are
jaroslav@601
  1778
         * prefixed with a 2-byte header; all others start with a 5-byte
jaroslav@601
  1779
         * header.
jaroslav@601
  1780
         */
jaroslav@601
  1781
        private void writeBlockHeader(int len) throws IOException {
jaroslav@601
  1782
            if (len <= 0xFF) {
jaroslav@601
  1783
                hbuf[0] = TC_BLOCKDATA;
jaroslav@601
  1784
                hbuf[1] = (byte) len;
jaroslav@601
  1785
                out.write(hbuf, 0, 2);
jaroslav@601
  1786
            } else {
jaroslav@601
  1787
                hbuf[0] = TC_BLOCKDATALONG;
jaroslav@601
  1788
                Bits.putInt(hbuf, 1, len);
jaroslav@601
  1789
                out.write(hbuf, 0, 5);
jaroslav@601
  1790
            }
jaroslav@601
  1791
        }
jaroslav@601
  1792
jaroslav@601
  1793
jaroslav@601
  1794
        /* ----------------- primitive data output methods ----------------- */
jaroslav@601
  1795
        /*
jaroslav@601
  1796
         * The following methods are equivalent to their counterparts in
jaroslav@601
  1797
         * DataOutputStream, except that they partition written data into data
jaroslav@601
  1798
         * blocks when in block data mode.
jaroslav@601
  1799
         */
jaroslav@601
  1800
jaroslav@601
  1801
        public void writeBoolean(boolean v) throws IOException {
jaroslav@601
  1802
            if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1803
                drain();
jaroslav@601
  1804
            }
jaroslav@601
  1805
            Bits.putBoolean(buf, pos++, v);
jaroslav@601
  1806
        }
jaroslav@601
  1807
jaroslav@601
  1808
        public void writeByte(int v) throws IOException {
jaroslav@601
  1809
            if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1810
                drain();
jaroslav@601
  1811
            }
jaroslav@601
  1812
            buf[pos++] = (byte) v;
jaroslav@601
  1813
        }
jaroslav@601
  1814
jaroslav@601
  1815
        public void writeChar(int v) throws IOException {
jaroslav@601
  1816
            if (pos + 2 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1817
                Bits.putChar(buf, pos, (char) v);
jaroslav@601
  1818
                pos += 2;
jaroslav@601
  1819
            } else {
jaroslav@601
  1820
                dout.writeChar(v);
jaroslav@601
  1821
            }
jaroslav@601
  1822
        }
jaroslav@601
  1823
jaroslav@601
  1824
        public void writeShort(int v) throws IOException {
jaroslav@601
  1825
            if (pos + 2 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1826
                Bits.putShort(buf, pos, (short) v);
jaroslav@601
  1827
                pos += 2;
jaroslav@601
  1828
            } else {
jaroslav@601
  1829
                dout.writeShort(v);
jaroslav@601
  1830
            }
jaroslav@601
  1831
        }
jaroslav@601
  1832
jaroslav@601
  1833
        public void writeInt(int v) throws IOException {
jaroslav@601
  1834
            if (pos + 4 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1835
                Bits.putInt(buf, pos, v);
jaroslav@601
  1836
                pos += 4;
jaroslav@601
  1837
            } else {
jaroslav@601
  1838
                dout.writeInt(v);
jaroslav@601
  1839
            }
jaroslav@601
  1840
        }
jaroslav@601
  1841
jaroslav@601
  1842
        public void writeFloat(float v) throws IOException {
jaroslav@601
  1843
            if (pos + 4 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1844
                Bits.putFloat(buf, pos, v);
jaroslav@601
  1845
                pos += 4;
jaroslav@601
  1846
            } else {
jaroslav@601
  1847
                dout.writeFloat(v);
jaroslav@601
  1848
            }
jaroslav@601
  1849
        }
jaroslav@601
  1850
jaroslav@601
  1851
        public void writeLong(long v) throws IOException {
jaroslav@601
  1852
            if (pos + 8 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1853
                Bits.putLong(buf, pos, v);
jaroslav@601
  1854
                pos += 8;
jaroslav@601
  1855
            } else {
jaroslav@601
  1856
                dout.writeLong(v);
jaroslav@601
  1857
            }
jaroslav@601
  1858
        }
jaroslav@601
  1859
jaroslav@601
  1860
        public void writeDouble(double v) throws IOException {
jaroslav@601
  1861
            if (pos + 8 <= MAX_BLOCK_SIZE) {
jaroslav@601
  1862
                Bits.putDouble(buf, pos, v);
jaroslav@601
  1863
                pos += 8;
jaroslav@601
  1864
            } else {
jaroslav@601
  1865
                dout.writeDouble(v);
jaroslav@601
  1866
            }
jaroslav@601
  1867
        }
jaroslav@601
  1868
jaroslav@601
  1869
        public void writeBytes(String s) throws IOException {
jaroslav@601
  1870
            int endoff = s.length();
jaroslav@601
  1871
            int cpos = 0;
jaroslav@601
  1872
            int csize = 0;
jaroslav@601
  1873
            for (int off = 0; off < endoff; ) {
jaroslav@601
  1874
                if (cpos >= csize) {
jaroslav@601
  1875
                    cpos = 0;
jaroslav@601
  1876
                    csize = Math.min(endoff - off, CHAR_BUF_SIZE);
jaroslav@601
  1877
                    s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  1878
                }
jaroslav@601
  1879
                if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1880
                    drain();
jaroslav@601
  1881
                }
jaroslav@601
  1882
                int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos);
jaroslav@601
  1883
                int stop = pos + n;
jaroslav@601
  1884
                while (pos < stop) {
jaroslav@601
  1885
                    buf[pos++] = (byte) cbuf[cpos++];
jaroslav@601
  1886
                }
jaroslav@601
  1887
                off += n;
jaroslav@601
  1888
            }
jaroslav@601
  1889
        }
jaroslav@601
  1890
jaroslav@601
  1891
        public void writeChars(String s) throws IOException {
jaroslav@601
  1892
            int endoff = s.length();
jaroslav@601
  1893
            for (int off = 0; off < endoff; ) {
jaroslav@601
  1894
                int csize = Math.min(endoff - off, CHAR_BUF_SIZE);
jaroslav@601
  1895
                s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  1896
                writeChars(cbuf, 0, csize);
jaroslav@601
  1897
                off += csize;
jaroslav@601
  1898
            }
jaroslav@601
  1899
        }
jaroslav@601
  1900
jaroslav@601
  1901
        public void writeUTF(String s) throws IOException {
jaroslav@601
  1902
            writeUTF(s, getUTFLength(s));
jaroslav@601
  1903
        }
jaroslav@601
  1904
jaroslav@601
  1905
jaroslav@601
  1906
        /* -------------- primitive data array output methods -------------- */
jaroslav@601
  1907
        /*
jaroslav@601
  1908
         * The following methods write out spans of primitive data values.
jaroslav@601
  1909
         * Though equivalent to calling the corresponding primitive write
jaroslav@601
  1910
         * methods repeatedly, these methods are optimized for writing groups
jaroslav@601
  1911
         * of primitive data values more efficiently.
jaroslav@601
  1912
         */
jaroslav@601
  1913
jaroslav@601
  1914
        void writeBooleans(boolean[] v, int off, int len) throws IOException {
jaroslav@601
  1915
            int endoff = off + len;
jaroslav@601
  1916
            while (off < endoff) {
jaroslav@601
  1917
                if (pos >= MAX_BLOCK_SIZE) {
jaroslav@601
  1918
                    drain();
jaroslav@601
  1919
                }
jaroslav@601
  1920
                int stop = Math.min(endoff, off + (MAX_BLOCK_SIZE - pos));
jaroslav@601
  1921
                while (off < stop) {
jaroslav@601
  1922
                    Bits.putBoolean(buf, pos++, v[off++]);
jaroslav@601
  1923
                }
jaroslav@601
  1924
            }
jaroslav@601
  1925
        }
jaroslav@601
  1926
jaroslav@601
  1927
        void writeChars(char[] v, int off, int len) throws IOException {
jaroslav@601
  1928
            int limit = MAX_BLOCK_SIZE - 2;
jaroslav@601
  1929
            int endoff = off + len;
jaroslav@601
  1930
            while (off < endoff) {
jaroslav@601
  1931
                if (pos <= limit) {
jaroslav@601
  1932
                    int avail = (MAX_BLOCK_SIZE - pos) >> 1;
jaroslav@601
  1933
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  1934
                    while (off < stop) {
jaroslav@601
  1935
                        Bits.putChar(buf, pos, v[off++]);
jaroslav@601
  1936
                        pos += 2;
jaroslav@601
  1937
                    }
jaroslav@601
  1938
                } else {
jaroslav@601
  1939
                    dout.writeChar(v[off++]);
jaroslav@601
  1940
                }
jaroslav@601
  1941
            }
jaroslav@601
  1942
        }
jaroslav@601
  1943
jaroslav@601
  1944
        void writeShorts(short[] v, int off, int len) throws IOException {
jaroslav@601
  1945
            int limit = MAX_BLOCK_SIZE - 2;
jaroslav@601
  1946
            int endoff = off + len;
jaroslav@601
  1947
            while (off < endoff) {
jaroslav@601
  1948
                if (pos <= limit) {
jaroslav@601
  1949
                    int avail = (MAX_BLOCK_SIZE - pos) >> 1;
jaroslav@601
  1950
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  1951
                    while (off < stop) {
jaroslav@601
  1952
                        Bits.putShort(buf, pos, v[off++]);
jaroslav@601
  1953
                        pos += 2;
jaroslav@601
  1954
                    }
jaroslav@601
  1955
                } else {
jaroslav@601
  1956
                    dout.writeShort(v[off++]);
jaroslav@601
  1957
                }
jaroslav@601
  1958
            }
jaroslav@601
  1959
        }
jaroslav@601
  1960
jaroslav@601
  1961
        void writeInts(int[] v, int off, int len) throws IOException {
jaroslav@601
  1962
            int limit = MAX_BLOCK_SIZE - 4;
jaroslav@601
  1963
            int endoff = off + len;
jaroslav@601
  1964
            while (off < endoff) {
jaroslav@601
  1965
                if (pos <= limit) {
jaroslav@601
  1966
                    int avail = (MAX_BLOCK_SIZE - pos) >> 2;
jaroslav@601
  1967
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  1968
                    while (off < stop) {
jaroslav@601
  1969
                        Bits.putInt(buf, pos, v[off++]);
jaroslav@601
  1970
                        pos += 4;
jaroslav@601
  1971
                    }
jaroslav@601
  1972
                } else {
jaroslav@601
  1973
                    dout.writeInt(v[off++]);
jaroslav@601
  1974
                }
jaroslav@601
  1975
            }
jaroslav@601
  1976
        }
jaroslav@601
  1977
jaroslav@601
  1978
        void writeFloats(float[] v, int off, int len) throws IOException {
jaroslav@601
  1979
            int limit = MAX_BLOCK_SIZE - 4;
jaroslav@601
  1980
            int endoff = off + len;
jaroslav@601
  1981
            while (off < endoff) {
jaroslav@601
  1982
                if (pos <= limit) {
jaroslav@601
  1983
                    int avail = (MAX_BLOCK_SIZE - pos) >> 2;
jaroslav@601
  1984
                    int chunklen = Math.min(endoff - off, avail);
jaroslav@601
  1985
                    floatsToBytes(v, off, buf, pos, chunklen);
jaroslav@601
  1986
                    off += chunklen;
jaroslav@601
  1987
                    pos += chunklen << 2;
jaroslav@601
  1988
                } else {
jaroslav@601
  1989
                    dout.writeFloat(v[off++]);
jaroslav@601
  1990
                }
jaroslav@601
  1991
            }
jaroslav@601
  1992
        }
jaroslav@601
  1993
jaroslav@601
  1994
        void writeLongs(long[] v, int off, int len) throws IOException {
jaroslav@601
  1995
            int limit = MAX_BLOCK_SIZE - 8;
jaroslav@601
  1996
            int endoff = off + len;
jaroslav@601
  1997
            while (off < endoff) {
jaroslav@601
  1998
                if (pos <= limit) {
jaroslav@601
  1999
                    int avail = (MAX_BLOCK_SIZE - pos) >> 3;
jaroslav@601
  2000
                    int stop = Math.min(endoff, off + avail);
jaroslav@601
  2001
                    while (off < stop) {
jaroslav@601
  2002
                        Bits.putLong(buf, pos, v[off++]);
jaroslav@601
  2003
                        pos += 8;
jaroslav@601
  2004
                    }
jaroslav@601
  2005
                } else {
jaroslav@601
  2006
                    dout.writeLong(v[off++]);
jaroslav@601
  2007
                }
jaroslav@601
  2008
            }
jaroslav@601
  2009
        }
jaroslav@601
  2010
jaroslav@601
  2011
        void writeDoubles(double[] v, int off, int len) throws IOException {
jaroslav@601
  2012
            int limit = MAX_BLOCK_SIZE - 8;
jaroslav@601
  2013
            int endoff = off + len;
jaroslav@601
  2014
            while (off < endoff) {
jaroslav@601
  2015
                if (pos <= limit) {
jaroslav@601
  2016
                    int avail = (MAX_BLOCK_SIZE - pos) >> 3;
jaroslav@601
  2017
                    int chunklen = Math.min(endoff - off, avail);
jaroslav@601
  2018
                    doublesToBytes(v, off, buf, pos, chunklen);
jaroslav@601
  2019
                    off += chunklen;
jaroslav@601
  2020
                    pos += chunklen << 3;
jaroslav@601
  2021
                } else {
jaroslav@601
  2022
                    dout.writeDouble(v[off++]);
jaroslav@601
  2023
                }
jaroslav@601
  2024
            }
jaroslav@601
  2025
        }
jaroslav@601
  2026
jaroslav@601
  2027
        /**
jaroslav@601
  2028
         * Returns the length in bytes of the UTF encoding of the given string.
jaroslav@601
  2029
         */
jaroslav@601
  2030
        long getUTFLength(String s) {
jaroslav@601
  2031
            int len = s.length();
jaroslav@601
  2032
            long utflen = 0;
jaroslav@601
  2033
            for (int off = 0; off < len; ) {
jaroslav@601
  2034
                int csize = Math.min(len - off, CHAR_BUF_SIZE);
jaroslav@601
  2035
                s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  2036
                for (int cpos = 0; cpos < csize; cpos++) {
jaroslav@601
  2037
                    char c = cbuf[cpos];
jaroslav@601
  2038
                    if (c >= 0x0001 && c <= 0x007F) {
jaroslav@601
  2039
                        utflen++;
jaroslav@601
  2040
                    } else if (c > 0x07FF) {
jaroslav@601
  2041
                        utflen += 3;
jaroslav@601
  2042
                    } else {
jaroslav@601
  2043
                        utflen += 2;
jaroslav@601
  2044
                    }
jaroslav@601
  2045
                }
jaroslav@601
  2046
                off += csize;
jaroslav@601
  2047
            }
jaroslav@601
  2048
            return utflen;
jaroslav@601
  2049
        }
jaroslav@601
  2050
jaroslav@601
  2051
        /**
jaroslav@601
  2052
         * Writes the given string in UTF format.  This method is used in
jaroslav@601
  2053
         * situations where the UTF encoding length of the string is already
jaroslav@601
  2054
         * known; specifying it explicitly avoids a prescan of the string to
jaroslav@601
  2055
         * determine its UTF length.
jaroslav@601
  2056
         */
jaroslav@601
  2057
        void writeUTF(String s, long utflen) throws IOException {
jaroslav@601
  2058
            if (utflen > 0xFFFFL) {
jaroslav@601
  2059
                throw new UTFDataFormatException();
jaroslav@601
  2060
            }
jaroslav@601
  2061
            writeShort((int) utflen);
jaroslav@601
  2062
            if (utflen == (long) s.length()) {
jaroslav@601
  2063
                writeBytes(s);
jaroslav@601
  2064
            } else {
jaroslav@601
  2065
                writeUTFBody(s);
jaroslav@601
  2066
            }
jaroslav@601
  2067
        }
jaroslav@601
  2068
jaroslav@601
  2069
        /**
jaroslav@601
  2070
         * Writes given string in "long" UTF format.  "Long" UTF format is
jaroslav@601
  2071
         * identical to standard UTF, except that it uses an 8 byte header
jaroslav@601
  2072
         * (instead of the standard 2 bytes) to convey the UTF encoding length.
jaroslav@601
  2073
         */
jaroslav@601
  2074
        void writeLongUTF(String s) throws IOException {
jaroslav@601
  2075
            writeLongUTF(s, getUTFLength(s));
jaroslav@601
  2076
        }
jaroslav@601
  2077
jaroslav@601
  2078
        /**
jaroslav@601
  2079
         * Writes given string in "long" UTF format, where the UTF encoding
jaroslav@601
  2080
         * length of the string is already known.
jaroslav@601
  2081
         */
jaroslav@601
  2082
        void writeLongUTF(String s, long utflen) throws IOException {
jaroslav@601
  2083
            writeLong(utflen);
jaroslav@601
  2084
            if (utflen == (long) s.length()) {
jaroslav@601
  2085
                writeBytes(s);
jaroslav@601
  2086
            } else {
jaroslav@601
  2087
                writeUTFBody(s);
jaroslav@601
  2088
            }
jaroslav@601
  2089
        }
jaroslav@601
  2090
jaroslav@601
  2091
        /**
jaroslav@601
  2092
         * Writes the "body" (i.e., the UTF representation minus the 2-byte or
jaroslav@601
  2093
         * 8-byte length header) of the UTF encoding for the given string.
jaroslav@601
  2094
         */
jaroslav@601
  2095
        private void writeUTFBody(String s) throws IOException {
jaroslav@601
  2096
            int limit = MAX_BLOCK_SIZE - 3;
jaroslav@601
  2097
            int len = s.length();
jaroslav@601
  2098
            for (int off = 0; off < len; ) {
jaroslav@601
  2099
                int csize = Math.min(len - off, CHAR_BUF_SIZE);
jaroslav@601
  2100
                s.getChars(off, off + csize, cbuf, 0);
jaroslav@601
  2101
                for (int cpos = 0; cpos < csize; cpos++) {
jaroslav@601
  2102
                    char c = cbuf[cpos];
jaroslav@601
  2103
                    if (pos <= limit) {
jaroslav@601
  2104
                        if (c <= 0x007F && c != 0) {
jaroslav@601
  2105
                            buf[pos++] = (byte) c;
jaroslav@601
  2106
                        } else if (c > 0x07FF) {
jaroslav@601
  2107
                            buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2108
                            buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F));
jaroslav@601
  2109
                            buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F));
jaroslav@601
  2110
                            pos += 3;
jaroslav@601
  2111
                        } else {
jaroslav@601
  2112
                            buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2113
                            buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F));
jaroslav@601
  2114
                            pos += 2;
jaroslav@601
  2115
                        }
jaroslav@601
  2116
                    } else {    // write one byte at a time to normalize block
jaroslav@601
  2117
                        if (c <= 0x007F && c != 0) {
jaroslav@601
  2118
                            write(c);
jaroslav@601
  2119
                        } else if (c > 0x07FF) {
jaroslav@601
  2120
                            write(0xE0 | ((c >> 12) & 0x0F));
jaroslav@601
  2121
                            write(0x80 | ((c >> 6) & 0x3F));
jaroslav@601
  2122
                            write(0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2123
                        } else {
jaroslav@601
  2124
                            write(0xC0 | ((c >> 6) & 0x1F));
jaroslav@601
  2125
                            write(0x80 | ((c >> 0) & 0x3F));
jaroslav@601
  2126
                        }
jaroslav@601
  2127
                    }
jaroslav@601
  2128
                }
jaroslav@601
  2129
                off += csize;
jaroslav@601
  2130
            }
jaroslav@601
  2131
        }
jaroslav@601
  2132
    }
jaroslav@601
  2133
jaroslav@601
  2134
    /**
jaroslav@601
  2135
     * Lightweight identity hash table which maps objects to integer handles,
jaroslav@601
  2136
     * assigned in ascending order.
jaroslav@601
  2137
     */
jaroslav@601
  2138
    private static class HandleTable {
jaroslav@601
  2139
jaroslav@601
  2140
        /* number of mappings in table/next available handle */
jaroslav@601
  2141
        private int size;
jaroslav@601
  2142
        /* size threshold determining when to expand hash spine */
jaroslav@601
  2143
        private int threshold;
jaroslav@601
  2144
        /* factor for computing size threshold */
jaroslav@601
  2145
        private final float loadFactor;
jaroslav@601
  2146
        /* maps hash value -> candidate handle value */
jaroslav@601
  2147
        private int[] spine;
jaroslav@601
  2148
        /* maps handle value -> next candidate handle value */
jaroslav@601
  2149
        private int[] next;
jaroslav@601
  2150
        /* maps handle value -> associated object */
jaroslav@601
  2151
        private Object[] objs;
jaroslav@601
  2152
jaroslav@601
  2153
        /**
jaroslav@601
  2154
         * Creates new HandleTable with given capacity and load factor.
jaroslav@601
  2155
         */
jaroslav@601
  2156
        HandleTable(int initialCapacity, float loadFactor) {
jaroslav@601
  2157
            this.loadFactor = loadFactor;
jaroslav@601
  2158
            spine = new int[initialCapacity];
jaroslav@601
  2159
            next = new int[initialCapacity];
jaroslav@601
  2160
            objs = new Object[initialCapacity];
jaroslav@601
  2161
            threshold = (int) (initialCapacity * loadFactor);
jaroslav@601
  2162
            clear();
jaroslav@601
  2163
        }
jaroslav@601
  2164
jaroslav@601
  2165
        /**
jaroslav@601
  2166
         * Assigns next available handle to given object, and returns handle
jaroslav@601
  2167
         * value.  Handles are assigned in ascending order starting at 0.
jaroslav@601
  2168
         */
jaroslav@601
  2169
        int assign(Object obj) {
jaroslav@601
  2170
            if (size >= next.length) {
jaroslav@601
  2171
                growEntries();
jaroslav@601
  2172
            }
jaroslav@601
  2173
            if (size >= threshold) {
jaroslav@601
  2174
                growSpine();
jaroslav@601
  2175
            }
jaroslav@601
  2176
            insert(obj, size);
jaroslav@601
  2177
            return size++;
jaroslav@601
  2178
        }
jaroslav@601
  2179
jaroslav@601
  2180
        /**
jaroslav@601
  2181
         * Looks up and returns handle associated with given object, or -1 if
jaroslav@601
  2182
         * no mapping found.
jaroslav@601
  2183
         */
jaroslav@601
  2184
        int lookup(Object obj) {
jaroslav@601
  2185
            if (size == 0) {
jaroslav@601
  2186
                return -1;
jaroslav@601
  2187
            }
jaroslav@601
  2188
            int index = hash(obj) % spine.length;
jaroslav@601
  2189
            for (int i = spine[index]; i >= 0; i = next[i]) {
jaroslav@601
  2190
                if (objs[i] == obj) {
jaroslav@601
  2191
                    return i;
jaroslav@601
  2192
                }
jaroslav@601
  2193
            }
jaroslav@601
  2194
            return -1;
jaroslav@601
  2195
        }
jaroslav@601
  2196
jaroslav@601
  2197
        /**
jaroslav@601
  2198
         * Resets table to its initial (empty) state.
jaroslav@601
  2199
         */
jaroslav@601
  2200
        void clear() {
jaroslav@601
  2201
            Arrays.fill(spine, -1);
jaroslav@601
  2202
            Arrays.fill(objs, 0, size, null);
jaroslav@601
  2203
            size = 0;
jaroslav@601
  2204
        }
jaroslav@601
  2205
jaroslav@601
  2206
        /**
jaroslav@601
  2207
         * Returns the number of mappings currently in table.
jaroslav@601
  2208
         */
jaroslav@601
  2209
        int size() {
jaroslav@601
  2210
            return size;
jaroslav@601
  2211
        }
jaroslav@601
  2212
jaroslav@601
  2213
        /**
jaroslav@601
  2214
         * Inserts mapping object -> handle mapping into table.  Assumes table
jaroslav@601
  2215
         * is large enough to accommodate new mapping.
jaroslav@601
  2216
         */
jaroslav@601
  2217
        private void insert(Object obj, int handle) {
jaroslav@601
  2218
            int index = hash(obj) % spine.length;
jaroslav@601
  2219
            objs[handle] = obj;
jaroslav@601
  2220
            next[handle] = spine[index];
jaroslav@601
  2221
            spine[index] = handle;
jaroslav@601
  2222
        }
jaroslav@601
  2223
jaroslav@601
  2224
        /**
jaroslav@601
  2225
         * Expands the hash "spine" -- equivalent to increasing the number of
jaroslav@601
  2226
         * buckets in a conventional hash table.
jaroslav@601
  2227
         */
jaroslav@601
  2228
        private void growSpine() {
jaroslav@601
  2229
            spine = new int[(spine.length << 1) + 1];
jaroslav@601
  2230
            threshold = (int) (spine.length * loadFactor);
jaroslav@601
  2231
            Arrays.fill(spine, -1);
jaroslav@601
  2232
            for (int i = 0; i < size; i++) {
jaroslav@601
  2233
                insert(objs[i], i);
jaroslav@601
  2234
            }
jaroslav@601
  2235
        }
jaroslav@601
  2236
jaroslav@601
  2237
        /**
jaroslav@601
  2238
         * Increases hash table capacity by lengthening entry arrays.
jaroslav@601
  2239
         */
jaroslav@601
  2240
        private void growEntries() {
jaroslav@601
  2241
            int newLength = (next.length << 1) + 1;
jaroslav@601
  2242
            int[] newNext = new int[newLength];
jaroslav@601
  2243
            System.arraycopy(next, 0, newNext, 0, size);
jaroslav@601
  2244
            next = newNext;
jaroslav@601
  2245
jaroslav@601
  2246
            Object[] newObjs = new Object[newLength];
jaroslav@601
  2247
            System.arraycopy(objs, 0, newObjs, 0, size);
jaroslav@601
  2248
            objs = newObjs;
jaroslav@601
  2249
        }
jaroslav@601
  2250
jaroslav@601
  2251
        /**
jaroslav@601
  2252
         * Returns hash value for given object.
jaroslav@601
  2253
         */
jaroslav@601
  2254
        private int hash(Object obj) {
jaroslav@601
  2255
            return System.identityHashCode(obj) & 0x7FFFFFFF;
jaroslav@601
  2256
        }
jaroslav@601
  2257
    }
jaroslav@601
  2258
jaroslav@601
  2259
    /**
jaroslav@601
  2260
     * Lightweight identity hash table which maps objects to replacement
jaroslav@601
  2261
     * objects.
jaroslav@601
  2262
     */
jaroslav@601
  2263
    private static class ReplaceTable {
jaroslav@601
  2264
jaroslav@601
  2265
        /* maps object -> index */
jaroslav@601
  2266
        private final HandleTable htab;
jaroslav@601
  2267
        /* maps index -> replacement object */
jaroslav@601
  2268
        private Object[] reps;
jaroslav@601
  2269
jaroslav@601
  2270
        /**
jaroslav@601
  2271
         * Creates new ReplaceTable with given capacity and load factor.
jaroslav@601
  2272
         */
jaroslav@601
  2273
        ReplaceTable(int initialCapacity, float loadFactor) {
jaroslav@601
  2274
            htab = new HandleTable(initialCapacity, loadFactor);
jaroslav@601
  2275
            reps = new Object[initialCapacity];
jaroslav@601
  2276
        }
jaroslav@601
  2277
jaroslav@601
  2278
        /**
jaroslav@601
  2279
         * Enters mapping from object to replacement object.
jaroslav@601
  2280
         */
jaroslav@601
  2281
        void assign(Object obj, Object rep) {
jaroslav@601
  2282
            int index = htab.assign(obj);
jaroslav@601
  2283
            while (index >= reps.length) {
jaroslav@601
  2284
                grow();
jaroslav@601
  2285
            }
jaroslav@601
  2286
            reps[index] = rep;
jaroslav@601
  2287
        }
jaroslav@601
  2288
jaroslav@601
  2289
        /**
jaroslav@601
  2290
         * Looks up and returns replacement for given object.  If no
jaroslav@601
  2291
         * replacement is found, returns the lookup object itself.
jaroslav@601
  2292
         */
jaroslav@601
  2293
        Object lookup(Object obj) {
jaroslav@601
  2294
            int index = htab.lookup(obj);
jaroslav@601
  2295
            return (index >= 0) ? reps[index] : obj;
jaroslav@601
  2296
        }
jaroslav@601
  2297
jaroslav@601
  2298
        /**
jaroslav@601
  2299
         * Resets table to its initial (empty) state.
jaroslav@601
  2300
         */
jaroslav@601
  2301
        void clear() {
jaroslav@601
  2302
            Arrays.fill(reps, 0, htab.size(), null);
jaroslav@601
  2303
            htab.clear();
jaroslav@601
  2304
        }
jaroslav@601
  2305
jaroslav@601
  2306
        /**
jaroslav@601
  2307
         * Returns the number of mappings currently in table.
jaroslav@601
  2308
         */
jaroslav@601
  2309
        int size() {
jaroslav@601
  2310
            return htab.size();
jaroslav@601
  2311
        }
jaroslav@601
  2312
jaroslav@601
  2313
        /**
jaroslav@601
  2314
         * Increases table capacity.
jaroslav@601
  2315
         */
jaroslav@601
  2316
        private void grow() {
jaroslav@601
  2317
            Object[] newReps = new Object[(reps.length << 1) + 1];
jaroslav@601
  2318
            System.arraycopy(reps, 0, newReps, 0, reps.length);
jaroslav@601
  2319
            reps = newReps;
jaroslav@601
  2320
        }
jaroslav@601
  2321
    }
jaroslav@601
  2322
jaroslav@601
  2323
    /**
jaroslav@601
  2324
     * Stack to keep debug information about the state of the
jaroslav@601
  2325
     * serialization process, for embedding in exception messages.
jaroslav@601
  2326
     */
jaroslav@601
  2327
    private static class DebugTraceInfoStack {
jaroslav@601
  2328
        private final List<String> stack;
jaroslav@601
  2329
jaroslav@601
  2330
        DebugTraceInfoStack() {
jaroslav@601
  2331
            stack = new ArrayList<>();
jaroslav@601
  2332
        }
jaroslav@601
  2333
jaroslav@601
  2334
        /**
jaroslav@601
  2335
         * Removes all of the elements from enclosed list.
jaroslav@601
  2336
         */
jaroslav@601
  2337
        void clear() {
jaroslav@601
  2338
            stack.clear();
jaroslav@601
  2339
        }
jaroslav@601
  2340
jaroslav@601
  2341
        /**
jaroslav@601
  2342
         * Removes the object at the top of enclosed list.
jaroslav@601
  2343
         */
jaroslav@601
  2344
        void pop() {
jaroslav@601
  2345
            stack.remove(stack.size()-1);
jaroslav@601
  2346
        }
jaroslav@601
  2347
jaroslav@601
  2348
        /**
jaroslav@601
  2349
         * Pushes a String onto the top of enclosed list.
jaroslav@601
  2350
         */
jaroslav@601
  2351
        void push(String entry) {
jaroslav@601
  2352
            stack.add("\t- " + entry);
jaroslav@601
  2353
        }
jaroslav@601
  2354
jaroslav@601
  2355
        /**
jaroslav@601
  2356
         * Returns a string representation of this object
jaroslav@601
  2357
         */
jaroslav@601
  2358
        public String toString() {
jaroslav@601
  2359
            StringBuilder buffer = new StringBuilder();
jaroslav@601
  2360
            if (!stack.isEmpty()) {
jaroslav@601
  2361
                for(int i = stack.size(); i > 0; i-- ) {
jaroslav@601
  2362
                    buffer.append(stack.get(i-1) + ((i != 1) ? "\n" : ""));
jaroslav@601
  2363
                }
jaroslav@601
  2364
            }
jaroslav@601
  2365
            return buffer.toString();
jaroslav@601
  2366
        }
jaroslav@601
  2367
    }
jaroslav@601
  2368
jaroslav@601
  2369
}