-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
99 lines (74 loc) · 2.79 KB
/
Copy pathQueue.java
File metadata and controls
99 lines (74 loc) · 2.79 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
88
89
90
91
92
93
94
95
96
97
98
99
import common.Constants;
public class Queue {
// Fixed-size slot ring buffer
private final int TOTAL_SIZE = Constants.MAX_MESSAGE_SIZE * Constants.QUEUE_CAPACITY;
private final byte[] buffer = new byte[TOTAL_SIZE];
private final byte[] sizes = new byte[Constants.QUEUE_CAPACITY];
// pointing to first byte of a slot
private int head;
private int tail;
/*
e.g. MAX_MESSAGE_SIZE = 5
head(pop) .... tail(push)
|s l o t _ |s l o t _|....
*/
public Queue() {
this.head = 0;
this.tail = 0;
}
public void push(byte[] data){
if(data.length > Constants.MAX_MESSAGE_SIZE){
throw new IllegalArgumentException("Message to large");
}
if(isFull()){
throw new IllegalArgumentException("Queue is full");
}
int slotIndex = tail / Constants.MAX_MESSAGE_SIZE;
sizes[slotIndex] = (byte) data.length; // actual size of the data in slot
// Copy data to slot
System.arraycopy(data, 0, buffer, tail, data.length);
// If tail reaches the end, reset it to the beginning
tail = (tail + Constants.MAX_MESSAGE_SIZE) % TOTAL_SIZE;
}
public byte[] pop(){
if (isEmpty()) {
return null;
}
int slotIndex = head / Constants.MAX_MESSAGE_SIZE;
int size = sizes[slotIndex];
byte[] data = new byte[Constants.MAX_MESSAGE_SIZE];
System.arraycopy(buffer, head, data, 0, size);
head = (head + Constants.MAX_MESSAGE_SIZE) % TOTAL_SIZE;
return data;
}
public byte[] peekAt(int offset){
if (isEmpty()) {
return null;
}
int position = (head + offset * Constants.MAX_MESSAGE_SIZE) % TOTAL_SIZE;
int slotIndex = position / Constants.MAX_MESSAGE_SIZE;
int size = sizes[slotIndex];
byte[] data = new byte[Constants.MAX_MESSAGE_SIZE];
System.arraycopy(buffer, position, data, 0, size);
return data;
}
protected boolean isEmpty() {
return head == tail;
}
protected boolean isFull() {
return ((tail + Constants.MAX_MESSAGE_SIZE) % TOTAL_SIZE) == head;
}
public void debug(){
System.out.print("DEBUG QUEUE: ");
int cur = head;
while(cur != tail){
int slotIndex = cur / Constants.MAX_MESSAGE_SIZE;
int size = sizes[slotIndex];
byte[] data = new byte[size];
System.arraycopy(buffer, cur, data, 0, size);
System.out.print(new String(data) + " | ");
cur = (cur + Constants.MAX_MESSAGE_SIZE) % TOTAL_SIZE;
}
System.out.println("");
}
}