| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.value; |
| 7 |
|
| 8 |
import java.nio.charset.StandardCharsets; |
| 9 |
|
| 10 |
import org.h2.engine.SysProperties; |
| 11 |
import org.h2.util.Utils; |
| 12 |
|
| 13 |
/** |
| 14 |
* Implementation of the BINARY VARYING data type. |
| 15 |
*/ |
| 16 |
public final class ValueVarbinary extends ValueBytesBase { |
| 17 |
|
| 18 |
/** |
| 19 |
* Empty value. |
| 20 |
*/ |
| 21 |
public static final ValueVarbinary EMPTY = new ValueVarbinary(Utils.EMPTY_BYTES); |
| 22 |
|
| 23 |
/** |
| 24 |
* Associated TypeInfo. |
| 25 |
*/ |
| 26 |
private TypeInfo type; |
| 27 |
|
| 28 |
private ValueVarbinary(byte[] value) { |
| 29 |
super(value); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Get or create a VARBINARY value for the given byte array. |
| 34 |
* Clone the data. |
| 35 |
* |
| 36 |
* @param b the byte array |
| 37 |
* @return the value |
| 38 |
*/ |
| 39 |
public static ValueVarbinary get(byte[] b) { |
| 40 |
if (b.length == 0) { |
| 41 |
return EMPTY; |
| 42 |
} |
| 43 |
b = Utils.cloneByteArray(b); |
| 44 |
return getNoCopy(b); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Get or create a VARBINARY value for the given byte array. |
| 49 |
* Do not clone the date. |
| 50 |
* |
| 51 |
* @param b the byte array |
| 52 |
* @return the value |
| 53 |
*/ |
| 54 |
public static ValueVarbinary getNoCopy(byte[] b) { |
| 55 |
if (b.length == 0) { |
| 56 |
return EMPTY; |
| 57 |
} |
| 58 |
ValueVarbinary obj = new ValueVarbinary(b); |
| 59 |
if (b.length > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) { |
| 60 |
return obj; |
| 61 |
} |
| 62 |
return (ValueVarbinary) Value.cache(obj); |
| 63 |
} |
| 64 |
|
| 65 |
@Override |
| 66 |
public TypeInfo getType() { |
| 67 |
TypeInfo type = this.type; |
| 68 |
if (type == null) { |
| 69 |
long precision = value.length; |
| 70 |
this.type = type = new TypeInfo(VARBINARY, precision, 0, null); |
| 71 |
} |
| 72 |
return type; |
| 73 |
} |
| 74 |
|
| 75 |
@Override |
| 76 |
public int getValueType() { |
| 77 |
return VARBINARY; |
| 78 |
} |
| 79 |
|
| 80 |
@Override |
| 81 |
public String getString() { |
| 82 |
return new String(value, StandardCharsets.UTF_8); |
| 83 |
} |
| 84 |
|
| 85 |
} |