Initial opendaylight infrastructure commit!!
[controller.git] / third-party / openflowj / src / main / java / org / openflow / util / StringByteSerializer.java
1 package org.openflow.util;
2
3 import java.io.UnsupportedEncodingException;
4 import java.nio.ByteBuffer;
5 import java.nio.charset.Charset;
6 import java.util.Arrays;
7
8 public class StringByteSerializer {
9     public static String readFrom(ByteBuffer data, int length) {
10         byte[] stringBytes = new byte[length];
11         data.get(stringBytes);
12         // find the first index of 0
13         int index = 0;
14         for (byte b : stringBytes) {
15             if (0 == b)
16                 break;
17             ++index;
18         }
19         return new String(Arrays.copyOf(stringBytes, index),
20                 Charset.forName("ascii"));
21     }
22
23     public static void writeTo(ByteBuffer data, int length, String value) {
24         try {
25             byte[] name = value.getBytes("ASCII");
26             if (name.length < length) {
27                 data.put(name);
28                 for (int i = name.length; i < length; ++i) {
29                     data.put((byte) 0);
30                 }
31             } else {
32                 data.put(name, 0, length-1);
33                 data.put((byte) 0);
34             }
35         } catch (UnsupportedEncodingException e) {
36             throw new RuntimeException(e);
37         }
38
39     }
40 }