1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ehcache.pool.sizeof;
18
19 /***
20 * Primitive types in the VM type system and their sizes
21 * @author Alex Snaps
22 */
23 enum PrimitiveType {
24
25 /***
26 * boolean.class
27 */
28 BOOLEAN(boolean.class, 1),
29 /***
30 * byte.class
31 */
32 BYTE(byte.class, 1),
33 /***
34 * char.class
35 */
36 CHAR(char.class, 2),
37 /***
38 * short.class
39 */
40 SHORT(short.class, 2),
41 /***
42 * int.class
43 */
44 INT(int.class, 4),
45 /***
46 * float.class
47 */
48 FLOAT(float.class, 4),
49 /***
50 * double.class
51 */
52 DOUBLE(double.class, 8),
53 /***
54 * long.class
55 */
56 LONG(long.class, 8),
57 /***
58 * java.lang.Class
59 */
60 CLASS(Class.class, 8) {
61 @Override
62 public int getSize() {
63 return JvmInformation.POINTER_SIZE + JvmInformation.JAVA_POINTER_SIZE;
64 }
65 };
66
67 private Class<?> type;
68 private int size;
69
70
71 private PrimitiveType(Class<?> type, int size) {
72 this.type = type;
73 this.size = size;
74 }
75
76 /***
77 * Returns the size in memory this type occupies
78 * @return size in bytes
79 */
80 public int getSize() {
81 return size;
82 }
83
84 /***
85 * The representing type
86 * @return the type
87 */
88 public Class<?> getType() {
89 return type;
90 }
91
92 /***
93 * The size of a pointer
94 * @return size in bytes
95 */
96 public static int getReferenceSize() {
97 return JvmInformation.JAVA_POINTER_SIZE;
98 }
99
100 /***
101 * The size on an array
102 * @return size in bytes
103 */
104 public static long getArraySize() {
105 return CLASS.getSize() + INT.getSize();
106 }
107
108 /***
109 * Finds the matching PrimitiveType for a type
110 * @param type the type to find the PrimitiveType for
111 * @return the PrimitiveType instance or null if none found
112 */
113 public static PrimitiveType forType(final Class<?> type) {
114 for (PrimitiveType primitiveType : values()) {
115 if (primitiveType.getType() == type) {
116 return primitiveType;
117 }
118 }
119 return null;
120 }
121 }