-
Notifications
You must be signed in to change notification settings - Fork 298
/
BigDecimalSerializer.java
65 lines (53 loc) · 1.84 KB
/
BigDecimalSerializer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package me.prettyprint.cassandra.serializers;
import static me.prettyprint.hector.api.ddl.ComparatorType.DECIMALTYPE;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import me.prettyprint.hector.api.ddl.ComparatorType;
/**
* Serializer implementation for BigDecimal
*
* @author peter lin
*/
public final class BigDecimalSerializer extends AbstractSerializer<BigDecimal> {
private static final BigDecimalSerializer INSTANCE = new BigDecimalSerializer();
public static BigDecimalSerializer get() {
return INSTANCE;
}
@Override
public byte[] toBytes(BigDecimal obj) {
return this.toByteArray(obj);
}
@Override
public BigDecimal fromByteBuffer(ByteBuffer byteBuffer) {
if (byteBuffer == null) {
return null;
}
int scale = byteBuffer.getInt();
byte[] bibytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bibytes, 0, byteBuffer.remaining());
BigInteger bi = new BigInteger(bibytes);
// now we create an instance of BigDecimal with BigInteger and scale
BigDecimal value = new BigDecimal(bi, scale);
return value;
}
@Override
public ByteBuffer toByteBuffer(BigDecimal obj) {
if (obj == null) {
return null;
}
return ByteBuffer.wrap(toByteArray(obj));
}
public byte[] toByteArray(BigDecimal bigDecimal) {
byte[] bigIntBytes = bigDecimal.unscaledValue().toByteArray();
byte[] scaleBytes = IntegerSerializer.get().toBytes(bigDecimal.scale());
byte[] bytes = new byte[scaleBytes.length + bigIntBytes.length];
System.arraycopy(scaleBytes, 0, bytes, 0, scaleBytes.length);
System.arraycopy(bigIntBytes, 0, bytes, scaleBytes.length, bigIntBytes.length);
return bytes;
}
@Override
public ComparatorType getComparatorType() {
return DECIMALTYPE;
}
}