01: /*-
02: * See the file LICENSE for redistribution information.
03: *
04: * Copyright (c) 2000,2008 Oracle. All rights reserved.
05: *
06: * $Id: IntegerBinding.java,v 1.10.2.2 2008/01/07 15:14:06 cwl Exp $
07: */
08:
09: package com.sleepycat.bind.tuple;
10:
11: import com.sleepycat.je.DatabaseEntry;
12:
13: /**
14: * A concrete <code>TupleBinding</code> for a <code>Integer</code> primitive
15: * wrapper or an <code>int</code> primitive.
16: *
17: * <p>There are two ways to use this class:</p>
18: * <ol>
19: * <li>When using the {@link com.sleepycat.je} package directly, the static
20: * methods in this class can be used to convert between primitive values and
21: * {@link DatabaseEntry} objects.</li>
22: * <li>When using the {@link com.sleepycat.collections} package, an instance of
23: * this class can be used with any stored collection. The easiest way to
24: * obtain a binding instance is with the {@link
25: * TupleBinding#getPrimitiveBinding} method.</li>
26: * </ol>
27: */
28: public class IntegerBinding extends TupleBinding {
29:
30: private static final int INT_SIZE = 4;
31:
32: // javadoc is inherited
33: public Object entryToObject(TupleInput input) {
34:
35: return new Integer(input.readInt());
36: }
37:
38: // javadoc is inherited
39: public void objectToEntry(Object object, TupleOutput output) {
40:
41: output.writeInt(((Number) object).intValue());
42: }
43:
44: // javadoc is inherited
45: protected TupleOutput getTupleOutput(Object object) {
46:
47: return sizedOutput();
48: }
49:
50: /**
51: * Converts an entry buffer into a simple <code>int</code> value.
52: *
53: * @param entry is the source entry buffer.
54: *
55: * @return the resulting value.
56: */
57: public static int entryToInt(DatabaseEntry entry) {
58:
59: return entryToInput(entry).readInt();
60: }
61:
62: /**
63: * Converts a simple <code>int</code> value into an entry buffer.
64: *
65: * @param val is the source value.
66: *
67: * @param entry is the destination entry buffer.
68: */
69: public static void intToEntry(int val, DatabaseEntry entry) {
70:
71: outputToEntry(sizedOutput().writeInt(val), entry);
72: }
73:
74: /**
75: * Returns a tuple output object of the exact size needed, to avoid
76: * wasting space when a single primitive is output.
77: */
78: private static TupleOutput sizedOutput() {
79:
80: return new TupleOutput(new byte[INT_SIZE]);
81: }
82: }
|