1 package emissary.parser;
2
3 import org.apache.commons.collections4.CollectionUtils;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6
7 import java.io.ByteArrayOutputStream;
8 import java.io.IOException;
9 import java.util.List;
10 import javax.annotation.Nullable;
11
12 public class DataByteArraySlicer {
13
14 private static final Logger logger = LoggerFactory.getLogger(DataByteArraySlicer.class);
15
16
17
18
19
20
21
22 public static byte[] makeDataSlice(byte[] data, PositionRecord r) {
23 byte[] n = new byte[(int) r.getLength()];
24 System.arraycopy(data, (int) r.getPosition(), n, 0, (int) r.getLength());
25 return n;
26 }
27
28
29
30
31
32
33
34 @Nullable
35 public static byte[] makeDataSlice(byte[] data, @Nullable List<PositionRecord> list) {
36
37
38 if (CollectionUtils.isEmpty(list)) {
39 return null;
40 }
41
42
43 if (list.size() == 1) {
44 return makeDataSlice(data, list.get(0));
45 }
46
47
48
49 byte[] ret = null;
50
51 try {
52 ByteArrayOutputStream out = new ByteArrayOutputStream();
53
54 for (PositionRecord r : list) {
55 int start = (int) r.getPosition();
56 int len = (int) r.getLength();
57
58 if (len == 0) {
59 continue;
60 }
61
62 if (len > 0 && start > -1 && (len + start) <= data.length) {
63 out.write(data, start, len);
64 }
65 }
66
67 ret = out.toByteArray();
68 out.close();
69 } catch (IOException iox) {
70 logger.warn("io error on bytearray stream cant happen", iox);
71 }
72
73 return ret;
74 }
75
76
77 private DataByteArraySlicer() {}
78 }