1package org.bouncycastle.asn1;
2
3import java.io.IOException;
4import java.math.BigInteger;
5
6import org.bouncycastle.util.Arrays;
7
8public class DEREnumerated
9    extends ASN1Object
10{
11    byte[]      bytes;
12
13    /**
14     * return an integer from the passed in object
15     *
16     * @exception IllegalArgumentException if the object cannot be converted.
17     */
18    public static DEREnumerated getInstance(
19        Object  obj)
20    {
21        if (obj == null || obj instanceof DEREnumerated)
22        {
23            return (DEREnumerated)obj;
24        }
25
26        throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
27    }
28
29    /**
30     * return an Enumerated from a tagged object.
31     *
32     * @param obj the tagged object holding the object we want
33     * @param explicit true if the object is meant to be explicitly
34     *              tagged false otherwise.
35     * @exception IllegalArgumentException if the tagged object cannot
36     *               be converted.
37     */
38    public static DEREnumerated getInstance(
39        ASN1TaggedObject obj,
40        boolean          explicit)
41    {
42        DERObject o = obj.getObject();
43
44        if (explicit || o instanceof DEREnumerated)
45        {
46            return getInstance(o);
47        }
48        else
49        {
50            return new DEREnumerated(((ASN1OctetString)o).getOctets());
51        }
52    }
53
54    public DEREnumerated(
55        int         value)
56    {
57        bytes = BigInteger.valueOf(value).toByteArray();
58    }
59
60    public DEREnumerated(
61        BigInteger   value)
62    {
63        bytes = value.toByteArray();
64    }
65
66    public DEREnumerated(
67        byte[]   bytes)
68    {
69        this.bytes = bytes;
70    }
71
72    public BigInteger getValue()
73    {
74        return new BigInteger(bytes);
75    }
76
77    void encode(
78        DEROutputStream out)
79        throws IOException
80    {
81        out.writeEncoded(ENUMERATED, bytes);
82    }
83
84    boolean asn1Equals(
85        DERObject  o)
86    {
87        if (!(o instanceof DEREnumerated))
88        {
89            return false;
90        }
91
92        DEREnumerated other = (DEREnumerated)o;
93
94        return Arrays.areEqual(this.bytes, other.bytes);
95    }
96
97    public int hashCode()
98    {
99        return Arrays.hashCode(bytes);
100    }
101}
102