View Javadoc
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       * Slice a data byte array based on a single position record
18       * 
19       * @param data the data to pull from
20       * @param r the position record indicating offsets
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       * Slice a data byte array based on a list of position record
30       * 
31       * @param data the data to pull from
32       * @param list the list of position records indicating offsets
33       */
34      @Nullable
35      public static byte[] makeDataSlice(byte[] data, @Nullable List<PositionRecord> list) {
36  
37          // Nothing to do
38          if (CollectionUtils.isEmpty(list)) {
39              return null;
40          }
41  
42          // Use higher performing impl when only one record
43          if (list.size() == 1) {
44              return makeDataSlice(data, list.get(0));
45          }
46  
47  
48          // Aggregate all the pieces using the baos
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      /** This class is not meant to be instantiated. */
77      private DataByteArraySlicer() {}
78  }