Advertisement
LynxPlay

StringArray

May 3rd, 2019
2,553
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. public static class StringArrayItemTagType implements PersistentDataType<byte[], String[]> {
  2.  
  3.     private Charset charset;
  4.  
  5.     public StringArrayItemTagType(Charset charset) {
  6.         this.charset = charset;
  7.     }
  8.  
  9.     @Override
  10.     public Class<byte[]> getPrimitiveType() {
  11.         return byte[].class;
  12.     }
  13.  
  14.     @Override
  15.     public Class<String[]> getComplexType() {
  16.         return String[].class;
  17.     }
  18.  
  19.     @Override
  20.     public byte[] toPrimitive(String[] strings, PersistentDataAdapterContext itemTagAdapterContext) {
  21.         byte[][] allStringBytes = new byte[strings.length][];
  22.         int total = 0;
  23.         for (int i = 0; i < allStringBytes.length; i++) {
  24.             byte[] bytes = strings[i].getBytes(charset);
  25.             allStringBytes[i] = bytes;
  26.             total += bytes.length;
  27.         }
  28.  
  29.         ByteBuffer buffer = ByteBuffer.allocate(total + allStringBytes.length * 4); //stores integers
  30.         for (byte[] bytes : allStringBytes) {
  31.             buffer.putInt(bytes.length);
  32.             buffer.put(bytes);
  33.         }
  34.  
  35.         return buffer.array();
  36.     }
  37.  
  38.     @Override
  39.     public String[] fromPrimitive(byte[] bytes, PersistentDataAdapterContext itemTagAdapterContext) {
  40.         ByteBuffer buffer = ByteBuffer.wrap(bytes);
  41.         ArrayList<String> list = new ArrayList<>();
  42.  
  43.         while (buffer.remaining() > 0) {
  44.             if (buffer.remaining() < 4) break;
  45.             int stringLength = buffer.getInt();
  46.             if (buffer.remaining() < stringLength) break;
  47.  
  48.             byte[] stringBytes = new byte[stringLength];
  49.             buffer.get(stringBytes);
  50.  
  51.             list.add(new String(stringBytes, charset));
  52.         }
  53.  
  54.         return list.toArray(new String[list.size()]);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement