aboutsummaryrefslogtreecommitdiff
path: root/mojo/public/java/system/src/org/chromium/mojo/system/Flags.java
blob: 30ff07f7100e37f4c5ad867dbc861ee0daf4cf43 (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
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.mojo.system;

/**
 * Base class for bit field used as flags.
 *
 * @param <F> the type of the flags.
 */
public abstract class Flags<F extends Flags<F>> {
    private int mFlags;
    private boolean mImmutable;

    /**
     * Dedicated constructor.
     *
     * @param flags initial value of the flag.
     */
    protected Flags(int flags) {
        mImmutable = false;
        mFlags = flags;
    }

    /**
     * @return the computed flag.
     */
    public int getFlags() {
        return mFlags;
    }

    /**
     * Change the given bit of this flag.
     *
     * @param value the new value of given bit.
     * @return this.
     */
    protected F setFlag(int flag, boolean value) {
        if (mImmutable) {
            throw new UnsupportedOperationException("Flags is immutable.");
        }
        if (value) {
            mFlags |= flag;
        } else {
            mFlags &= ~flag;
        }
        @SuppressWarnings("unchecked")
        F f = (F) this;
        return f;
    }

    /**
     * Makes this flag immutable. This is a non-reversable operation.
     */
    protected F immutable() {
        mImmutable = true;
        @SuppressWarnings("unchecked")
        F f = (F) this;
        return f;
    }

    /**
     * @see Object#hashCode()
     */
    @Override
    public int hashCode() {
        return mFlags;
    }

    /**
     * @see Object#equals(Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        Flags<?> other = (Flags<?>) obj;
        if (mFlags != other.mFlags) return false;
        return true;
    }
}