blob: 13cfdc71de298ace8912dc562c35d5a60a4dc7ba [file] [log] [blame]
Yotam Harcholf3f11152013-09-05 16:47:16 -07001package org.projectfloodlight.openflow.util;
2
3import java.util.List;
4
5import org.jboss.netty.buffer.ChannelBuffer;
6import org.projectfloodlight.openflow.exceptions.OFParseError;
7import org.projectfloodlight.openflow.protocol.OFMessageReader;
8import org.projectfloodlight.openflow.protocol.Writeable;
9
10import com.google.common.base.Charsets;
11import com.google.common.collect.ImmutableList;
12import com.google.common.collect.ImmutableList.Builder;
13
14/**
15 * Collection of helper functions for reading and writing into ChannelBuffers
16 *
17 * @author capveg
18 */
19
20public class ChannelUtils {
21 public static String readFixedLengthString(ChannelBuffer bb, int length) {
22 byte[] dst = new byte[length];
23 bb.readBytes(dst, 0, length);
Rob Vaterlaus64d06df2013-10-11 19:54:26 -070024 int validLength = 0;
25 for (validLength = 0; validLength < length; validLength++) {
26 if (dst[validLength] == 0)
27 break;
28 }
29 return new String(dst, 0, validLength, Charsets.US_ASCII);
Yotam Harcholf3f11152013-09-05 16:47:16 -070030 }
31
32 public static void writeFixedLengthString(ChannelBuffer bb, String string,
33 int length) {
34 int l = string.length();
35 if (l > length) {
36 throw new IllegalArgumentException("Error writing string: length="
37 + l + " > max Length=" + length);
38 }
39 bb.writeBytes(string.getBytes(Charsets.US_ASCII));
40 if (l < length) {
41 bb.writeZero(length - l);
42 }
43 }
44
45 static public byte[] readBytes(final ChannelBuffer bb, final int length) {
46 byte byteArray[] = new byte[length];
47 bb.readBytes(byteArray);
48 return byteArray;
49 }
50
51 static public void writeBytes(final ChannelBuffer bb,
52 final byte byteArray[]) {
53 bb.writeBytes(byteArray);
54 }
55
56 public static <T> List<T> readList(ChannelBuffer bb, int length, OFMessageReader<T> reader) throws OFParseError {
57 int end = bb.readerIndex() + length;
58 Builder<T> builder = ImmutableList.<T>builder();
59 while(bb.readerIndex() < end) {
60 builder.add(reader.readFrom(bb));
61 }
62 if(bb.readerIndex() != end) {
63 throw new IllegalStateException("Overread length: length="+length + " overread by "+ (bb.readerIndex() - end) + " reader: "+reader);
64 }
65 return builder.build();
66 }
67
68 public static void writeList(ChannelBuffer bb, List<? extends Writeable> writeables) {
69 for(Writeable w: writeables)
70 w.writeTo(bb);
71 }
72}