1/*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2000,2008 Oracle.  All rights reserved.
5 *
6 * $Id: CharacterBinding.java,v 12.7 2008/01/08 20:58:36 bostic Exp $
7 */
8
9package com.sleepycat.bind.tuple;
10
11import com.sleepycat.db.DatabaseEntry;
12
13/**
14 * A concrete <code>TupleBinding</code> for a <code>Character</code> primitive
15 * wrapper or a <code>char</code> primitive.
16 *
17 * <p>There are two ways to use this class:</p>
18 * <ol>
19 * <li>When using the {@link com.sleepycat.db} 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 */
28public class CharacterBinding extends TupleBinding {
29
30    private static final int CHAR_SIZE = 2;
31
32    // javadoc is inherited
33    public Object entryToObject(TupleInput input) {
34
35        return new Character(input.readChar());
36    }
37
38    // javadoc is inherited
39    public void objectToEntry(Object object, TupleOutput output) {
40
41        output.writeChar(((Character) object).charValue());
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>char</code> value.
52     *
53     * @param entry is the source entry buffer.
54     *
55     * @return the resulting value.
56     */
57    public static char entryToChar(DatabaseEntry entry) {
58
59        return entryToInput(entry).readChar();
60    }
61
62    /**
63     * Converts a simple <code>char</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 charToEntry(char val, DatabaseEntry entry) {
70
71        outputToEntry(sizedOutput().writeChar(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[CHAR_SIZE]);
81    }
82}
83