• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.mojo.system;
6 
7 /**
8  * Base class for bit field used as flags.
9  *
10  * @param <F> the type of the flags.
11  */
12 public abstract class Flags<F extends Flags<F>> {
13     private int mFlags;
14     private boolean mImmutable;
15 
16     /**
17      * Dedicated constructor.
18      *
19      * @param flags initial value of the flag.
20      */
Flags(int flags)21     protected Flags(int flags) {
22         mImmutable = false;
23         mFlags = flags;
24     }
25 
26     /**
27      * @return the computed flag.
28      */
getFlags()29     public int getFlags() {
30         return mFlags;
31     }
32 
33     /**
34      * Change the given bit of this flag.
35      *
36      * @param value the new value of given bit.
37      * @return this.
38      */
setFlag(int flag, boolean value)39     protected F setFlag(int flag, boolean value) {
40         if (mImmutable) {
41             throw new UnsupportedOperationException("Flags is immutable.");
42         }
43         if (value) {
44             mFlags |= flag;
45         } else {
46             mFlags &= ~flag;
47         }
48         @SuppressWarnings("unchecked")
49         F f = (F) this;
50         return f;
51     }
52 
53     /**
54      * Makes this flag immutable. This is a non-reversable operation.
55      */
immutable()56     protected F immutable() {
57         mImmutable = true;
58         @SuppressWarnings("unchecked")
59         F f = (F) this;
60         return f;
61     }
62 
63     /**
64      * @see Object#hashCode()
65      */
66     @Override
hashCode()67     public int hashCode() {
68         return mFlags;
69     }
70 
71     /**
72      * @see Object#equals(Object)
73      */
74     @Override
equals(Object obj)75     public boolean equals(Object obj) {
76         if (this == obj) return true;
77         if (obj == null) return false;
78         if (getClass() != obj.getClass()) return false;
79         Flags<?> other = (Flags<?>) obj;
80         if (mFlags != other.mFlags) return false;
81         return true;
82     }
83 }
84