-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathXdrUnsignedInteger.erb
More file actions
82 lines (69 loc) · 2.55 KB
/
XdrUnsignedInteger.erb
File metadata and controls
82 lines (69 loc) · 2.55 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package <%= @namespace %>;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import lombok.Value;
import org.stellar.sdk.Base64Factory;
/**
* Represents XDR Unsigned Integer.
*
* @see <a href="https://datatracker.ietf.org/doc/html/rfc4506#section-4.2">XDR: External Data
* Representation Standard</a>
*/
@Value
public class XdrUnsignedInteger implements XdrElement {
public static final long MAX_VALUE = (1L << 32) - 1;
public static final long MIN_VALUE = 0;
Long number;
public XdrUnsignedInteger(Long number) {
if (number < MIN_VALUE || number > MAX_VALUE) {
throw new IllegalArgumentException("number must be between 0 and 2^32 - 1 inclusive");
}
this.number = number;
}
public XdrUnsignedInteger(Integer number) {
if (number < 0) {
throw new IllegalArgumentException(
"number must be greater than or equal to 0 if you want to construct it from Integer");
}
this.number = number.longValue();
}
public static XdrUnsignedInteger decode(XdrDataInputStream stream, int maxDepth) throws IOException {
// maxDepth is intentionally not checked - XdrUnsignedInteger is a leaf type with no recursive decoding
int intValue = stream.readInt();
long uint32Value = Integer.toUnsignedLong(intValue);
return new XdrUnsignedInteger(uint32Value);
}
public static XdrUnsignedInteger decode(XdrDataInputStream stream) throws IOException {
return decode(stream, XdrDataInputStream.DEFAULT_MAX_DEPTH);
}
@Override
public void encode(XdrDataOutputStream stream) throws IOException {
stream.writeInt(number.intValue());
}
@Override
public String toJson() {
return XdrElement.gson.toJson(toJsonObject());
}
Object toJsonObject() {
return this.number;
}
public static XdrUnsignedInteger fromJson(String json) {
return fromJsonObject(XdrElement.gson.fromJson(json, Object.class));
}
static XdrUnsignedInteger fromJsonObject(Object json) {
if (json == null) {
return null;
}
return new XdrUnsignedInteger(XdrElement.jsonToLong(json));
}
public static XdrUnsignedInteger fromXdrBase64(String xdr) throws IOException {
byte[] bytes = Base64Factory.getInstance().decode(xdr);
return fromXdrByteArray(bytes);
}
public static XdrUnsignedInteger fromXdrByteArray(byte[] xdr) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xdr);
XdrDataInputStream xdrDataInputStream = new XdrDataInputStream(byteArrayInputStream);
return decode(xdrDataInputStream);
}
}