-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathShardRange.java
More file actions
87 lines (75 loc) · 2.83 KB
/
ShardRange.java
File metadata and controls
87 lines (75 loc) · 2.83 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
83
84
85
86
87
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
package org.opensearch.cluster.metadata;
import org.opensearch.common.annotation.ExperimentalApi;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
/**
* Represents the hash range assigned to a shard.
*
* @opensearch.experimental
*/
@ExperimentalApi
public record ShardRange(int shardId, int start, int end) implements Comparable<ShardRange>, ToXContentFragment, Writeable {
/**
* Constructs a new shard range from a stream.
* @param in the stream to read from
* @throws IOException if an error occurs while reading from the stream
* @see #writeTo(StreamOutput)
*/
public ShardRange(StreamInput in) throws IOException {
this(in.readVInt(), in.readInt(), in.readInt());
}
public boolean contains(int hash) {
return hash >= start && hash <= end;
}
@Override
public int compareTo(ShardRange o) {
return Integer.compare(start, o.start);
}
@Override
public String toString() {
return "ShardRange{" + "shardId=" + shardId + ", start=" + start + ", end=" + end + '}';
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(shardId);
out.writeInt(start);
out.writeInt(end);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject().field("shard_id", shardId).field("start", start).field("end", end);
builder.endObject();
return builder;
}
public static ShardRange parse(XContentParser parser) throws IOException {
int shardId = -1, start = -1, end = -1;
XContentParser.Token token;
String fieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
fieldName = parser.currentName();
} else if (token == XContentParser.Token.VALUE_NUMBER) {
if ("shard_id".equals(fieldName)) {
shardId = parser.intValue();
} else if ("start".equals(fieldName)) {
start = parser.intValue();
} else if ("end".equals(fieldName)) {
end = parser.intValue();
}
}
}
return new ShardRange(shardId, start, end);
}
}