1/*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2000,2008 Oracle.  All rights reserved.
5 *
6 * $Id: StringBinding.java,v 12.7 2008/01/08 20:58:36 bostic Exp $
7 */
8
9package com.sleepycat.bind.tuple;
10
11import com.sleepycat.util.UtfOps;
12import com.sleepycat.db.DatabaseEntry;
13
14/**
15 * A concrete <code>TupleBinding</code> for a simple <code>String</code> value.
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 StringBinding extends TupleBinding {
29
30    // javadoc is inherited
31    public Object entryToObject(TupleInput input) {
32
33        return input.readString();
34    }
35
36    // javadoc is inherited
37    public void objectToEntry(Object object, TupleOutput output) {
38
39        output.writeString((String) object);
40    }
41
42    // javadoc is inherited
43    protected TupleOutput getTupleOutput(Object object) {
44
45        return sizedOutput((String) object);
46    }
47
48    /**
49     * Converts an entry buffer into a simple <code>String</code> value.
50     *
51     * @param entry is the source entry buffer.
52     *
53     * @return the resulting value.
54     */
55    public static String entryToString(DatabaseEntry entry) {
56
57        return entryToInput(entry).readString();
58    }
59
60    /**
61     * Converts a simple <code>String</code> value into an entry buffer.
62     *
63     * @param val is the source value.
64     *
65     * @param entry is the destination entry buffer.
66     */
67    public static void stringToEntry(String val, DatabaseEntry entry) {
68
69        outputToEntry(sizedOutput(val).writeString(val), entry);
70    }
71
72    /**
73     * Returns a tuple output object of the exact size needed, to avoid
74     * wasting space when a single primitive is output.
75     */
76    private static TupleOutput sizedOutput(String val) {
77
78	int stringLength =
79	    (val == null) ? 1 : UtfOps.getByteLength(val.toCharArray());
80	stringLength++;           // null terminator
81        return new TupleOutput(new byte[stringLength]);
82    }
83}
84