1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.giraph.aggregators.matrix.dense;
20
21 import it.unimi.dsi.fastutil.longs.LongArrayList;
22
23 import java.io.DataInput;
24 import java.io.DataOutput;
25 import java.io.IOException;
26
27 import org.apache.hadoop.io.Writable;
28
29
30
31
32
33 public class LongDenseVector implements Writable {
34
35 private final LongArrayList entries = new LongArrayList();
36
37 private boolean isSingleton = false;
38
39 private int singletonIndex;
40
41 private long singletonValue;
42
43
44 public LongDenseVector() { }
45
46
47
48
49
50
51 public LongDenseVector(int size) {
52 ensureCapacity(size);
53 }
54
55
56
57
58
59
60
61 public void setSingleton(int index, long value) {
62 isSingleton = true;
63 this.singletonIndex = index;
64 this.singletonValue = value;
65 }
66
67
68
69
70
71
72 public int getSingletonIndex() {
73 return singletonIndex;
74 }
75
76
77
78
79
80
81 public long getSingletonValue() {
82 return singletonValue;
83 }
84
85
86
87
88
89
90
91 public long get(int i) {
92
93 if (i >= entries.size()) {
94 return 0L;
95 }
96 return entries.getLong(i);
97 }
98
99
100
101
102
103
104
105 public void set(int i, long value) {
106 entries.set(i, value);
107 }
108
109
110
111
112
113
114
115 public void add(LongDenseVector other) {
116 if (isSingleton) {
117 throw new RuntimeException("Cannot add to singleton vector");
118 }
119 if (other.isSingleton) {
120 ensureCapacity(other.singletonIndex + 1);
121 entries.set(other.singletonIndex, entries.getLong(other.singletonIndex) +
122 other.singletonValue);
123 } else {
124 ensureCapacity(other.entries.size());
125 for (int i = 0; i < other.entries.size(); ++i) {
126 entries.set(i, entries.getLong(i) + other.entries.getLong(i));
127 }
128 }
129 }
130
131
132
133
134
135
136 private void ensureCapacity(int size) {
137 if (entries.size() < size) {
138 entries.size(size);
139 }
140 }
141
142 @Override
143 public void write(DataOutput out) throws IOException {
144 out.writeBoolean(isSingleton);
145 if (isSingleton) {
146 out.writeInt(singletonIndex);
147 out.writeLong(singletonValue);
148 } else {
149 out.writeInt(entries.size());
150 for (int i = 0; i < entries.size(); ++i) {
151 out.writeLong(entries.getLong(i));
152 }
153 }
154 }
155
156 @Override
157 public void readFields(DataInput in) throws IOException {
158 isSingleton = in.readBoolean();
159 if (isSingleton) {
160 singletonIndex = in.readInt();
161 singletonValue = in.readLong();
162 } else {
163 int size = in.readInt();
164 for (int i = 0; i < size; ++i) {
165 entries.add(in.readLong());
166 }
167 }
168 }
169 }