DLSequence.java revision 5db505e1f6a68c8d5dfdb0fed0b8607dea7bed96
1package org.bouncycastle.asn1;
2
3import java.io.IOException;
4import java.util.Enumeration;
5
6/**
7 * The DLSequence encodes a SEQUENCE using definite length form.
8 */
9public class DLSequence
10    extends ASN1Sequence
11{
12    private int bodyLength = -1;
13
14    /**
15     * Create an empty sequence
16     */
17    public DLSequence()
18    {
19    }
20
21    /**
22     * Create a sequence containing one object
23     */
24    public DLSequence(
25        ASN1Encodable obj)
26    {
27        super(obj);
28    }
29
30    /**
31     * Create a sequence containing a vector of objects.
32     */
33    public DLSequence(
34        ASN1EncodableVector v)
35    {
36        super(v);
37    }
38
39    /**
40     * Create a sequence containing an array of objects.
41     */
42    public DLSequence(
43        ASN1Encodable[] array)
44    {
45        super(array);
46    }
47
48    private int getBodyLength()
49        throws IOException
50    {
51        if (bodyLength < 0)
52        {
53            int length = 0;
54
55            for (Enumeration e = this.getObjects(); e.hasMoreElements();)
56            {
57                Object obj = e.nextElement();
58
59                length += ((ASN1Encodable)obj).toASN1Primitive().toDLObject().encodedLength();
60            }
61
62            bodyLength = length;
63        }
64
65        return bodyLength;
66    }
67
68    int encodedLength()
69        throws IOException
70    {
71        int length = getBodyLength();
72
73        return 1 + StreamUtil.calculateBodyLength(length) + length;
74    }
75
76    /**
77     * A note on the implementation:
78     * <p>
79     * As DL requires the constructed, definite-length model to
80     * be used for structured types, this varies slightly from the
81     * ASN.1 descriptions given. Rather than just outputting SEQUENCE,
82     * we also have to specify CONSTRUCTED, and the objects length.
83     */
84    void encode(
85        ASN1OutputStream out)
86        throws IOException
87    {
88        ASN1OutputStream dOut = out.getDLSubStream();
89        int length = getBodyLength();
90
91        out.write(BERTags.SEQUENCE | BERTags.CONSTRUCTED);
92        out.writeLength(length);
93
94        for (Enumeration e = this.getObjects(); e.hasMoreElements();)
95        {
96            Object obj = e.nextElement();
97
98            dOut.writeObject((ASN1Encodable)obj);
99        }
100    }
101}