aboutsummaryrefslogtreecommitdiffhomepage
path: root/third_party/java/dd_plist/java/com/dd/plist/BinaryPropertyListWriter.java
blob: 21645befccdb132741639f510882dbcec9988a70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
 * plist - An open source library to parse and generate property lists
 * Copyright (C) 2012 Keith Randall
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.dd.plist;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * A BinaryPropertyListWriter is a helper class for writing out
 * binary property list files.  It contains an output stream and
 * various structures for keeping track of which NSObjects have
 * already been serialized, and where they were put in the file.
 *
 * @author Keith Randall
 */
public class BinaryPropertyListWriter {

    public static final int VERSION_00 = 0;
    public static final int VERSION_10 = 10;
    public static final int VERSION_15 = 15;
    public static final int VERSION_20 = 20;

    /**
     * Finds out the minimum binary property list format version that
     * can be used to save the given NSObject tree.
     *
     * @param root Object root
     * @return Version code
     */
    private static int getMinimumRequiredVersion(NSObject root) {
        int minVersion = VERSION_00;
        if (root == null) {
            minVersion = VERSION_10;
        }
        if (root instanceof NSDictionary) {
            NSDictionary dict = (NSDictionary) root;
            for (NSObject o : dict.getHashMap().values()) {
                int v = getMinimumRequiredVersion(o);
                if (v > minVersion)
                    minVersion = v;
            }
        } else if (root instanceof NSArray) {
            NSArray array = (NSArray) root;
            for (NSObject o : array.getArray()) {
                int v = getMinimumRequiredVersion(o);
                if (v > minVersion)
                    minVersion = v;
            }
        } else if (root instanceof NSSet) {
            //Sets are only allowed in property lists v1+
            minVersion = VERSION_10;
            NSSet set = (NSSet) root;
            for (NSObject o : set.allObjects()) {
                int v = getMinimumRequiredVersion(o);
                if (v > minVersion)
                    minVersion = v;
            }
        }
        return minVersion;
    }

    /**
     * Writes a binary plist file with the given object as the root.
     *
     * @param file the file to write to
     * @param root the source of the data to write to the file
     * @throws IOException When an IO error occurs while writing to the file or the object structure contains
     *                     data that cannot be saved.
     */
    public static void write(File file, NSObject root) throws IOException {
        OutputStream out = new FileOutputStream(file);
        write(out, root);
        out.close();
    }

    /**
     * Writes a binary plist serialization of the given object as the root.
     *
     * @param out  the stream to write to
     * @param root the source of the data to write to the stream
     * @throws IOException When an IO error occurs while writing to the stream or the object structure contains
     *                     data that cannot be saved.
     */
    public static void write(OutputStream out, NSObject root) throws IOException {
        int minVersion = getMinimumRequiredVersion(root);
        if (minVersion > VERSION_00) {
            String versionString = ((minVersion == VERSION_10) ? "v1.0" : ((minVersion == VERSION_15) ? "v1.5" : ((minVersion == VERSION_20) ? "v2.0" : "v0.0")));
            throw new IOException("The given property list structure cannot be saved. " +
                    "The required version of the binary format (" + versionString + ") is not yet supported.");
        }
        BinaryPropertyListWriter w = new BinaryPropertyListWriter(out, minVersion);
        w.write(root);
    }

    /**
     * Writes a binary plist serialization of the given object as the root
     * into a byte array.
     *
     * @param root The root object of the property list
     * @return The byte array containing the serialized property list
     * @throws IOException When an IO error occurs while writing to the stream or the object structure contains
     *                     data that cannot be saved.
     */
    public static byte[] writeToArray(NSObject root) throws IOException {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        write(bout, root);
        return bout.toByteArray();
    }

    private int version = VERSION_00;

    // raw output stream to result file
    private OutputStream out;

    // # of bytes written so far
    private long count;

    // map from object to its ID
    private Map<NSObject, Integer> idMap = new LinkedHashMap<NSObject, Integer>();
    private int idSizeInBytes;

    /**
     * Creates a new binary property list writer
     *
     * @param outStr The output stream into which the binary property list will be written
     * @throws IOException When an IO error occurs while writing to the stream or the object structure contains
     *                     data that cannot be saved.
     */
    BinaryPropertyListWriter(OutputStream outStr) throws IOException {
        out = new BufferedOutputStream(outStr);
    }

    BinaryPropertyListWriter(OutputStream outStr, int version) throws IOException {
        this.version = version;
        out = new BufferedOutputStream(outStr);
    }

    void write(NSObject root) throws IOException {
        // magic bytes
        write(new byte[]{'b', 'p', 'l', 'i', 's', 't'});

        //version
        switch (version) {
            case VERSION_00: {
                write(new byte[]{'0', '0'});
                break;
            }
            case VERSION_10: {
                write(new byte[]{'1', '0'});
                break;
            }
            case VERSION_15: {
                write(new byte[]{'1', '5'});
                break;
            }
            case VERSION_20: {
                write(new byte[]{'2', '0'});
                break;
            }
        }

        // assign IDs to all the objects.
        root.assignIDs(this);

        idSizeInBytes = computeIdSizeInBytes(idMap.size());

        // offsets of each object, indexed by ID
        long[] offsets = new long[idMap.size()];

        // write each object, save offset
        for (Map.Entry<NSObject, Integer> entry : idMap.entrySet()) {
            NSObject obj = entry.getKey();
            int id = entry.getValue();
            offsets[id] = count;
            if (obj == null) {
                write(0x00);
            } else {
                obj.toBinary(this);
            }
        }

        // write offset table
        long offsetTableOffset = count;
        int offsetSizeInBytes = computeOffsetSizeInBytes(count);
        for (long offset : offsets) {
            writeBytes(offset, offsetSizeInBytes);
        }

        if (version != VERSION_15) {
            // write trailer
            // 6 null bytes
            write(new byte[6]);
            // size of an offset
            write(offsetSizeInBytes);
            // size of a ref
            write(idSizeInBytes);
            // number of objects
            writeLong(idMap.size());
            // top object
            writeLong(idMap.get(root));
            // offset table offset
            writeLong(offsetTableOffset);
        }

        out.flush();
    }

    void assignID(NSObject obj) {
        if (!idMap.containsKey(obj)) {
            idMap.put(obj, idMap.size());
        }
    }

    int getID(NSObject obj) {
        return idMap.get(obj);
    }

    private static int computeIdSizeInBytes(int numberOfIds) {
        if (numberOfIds < 256) return 1;
        if (numberOfIds < 65536) return 2;
        return 4;
    }

    private int computeOffsetSizeInBytes(long maxOffset) {
        if (maxOffset < 256) return 1;
        if (maxOffset < 65536) return 2;
        if (maxOffset < 4294967296L) return 4;
        return 8;
    }

    void writeIntHeader(int kind, int value) throws IOException {
        assert value >= 0;
        if (value < 15) {
            write((kind << 4) + value);
        } else if (value < 256) {
            write((kind << 4) + 15);
            write(0x10);
            writeBytes(value, 1);
        } else if (value < 65536) {
            write((kind << 4) + 15);
            write(0x11);
            writeBytes(value, 2);
        } else {
            write((kind << 4) + 15);
            write(0x12);
            writeBytes(value, 4);
        }
    }

    void write(int b) throws IOException {
        out.write(b);
        count++;
    }

    void write(byte[] bytes) throws IOException {
        out.write(bytes);
        count += bytes.length;
    }

    void writeBytes(long value, int bytes) throws IOException {
        // write low-order bytes big-endian style
        for (int i = bytes - 1; i >= 0; i--) {
            write((int) (value >> (8 * i)));
        }
    }

    void writeID(int id) throws IOException {
        writeBytes(id, idSizeInBytes);
    }

    void writeLong(long value) throws IOException {
        writeBytes(value, 8);
    }

    void writeDouble(double value) throws IOException {
        writeLong(Double.doubleToRawLongBits(value));
    }
}