Yotam Harchol | f3f1115 | 2013-09-05 16:47:16 -0700 | [diff] [blame] | 1 | package org.projectfloodlight.openflow.util; |
| 2 | |
| 3 | import java.util.List; |
| 4 | |
| 5 | import org.jboss.netty.buffer.ChannelBuffer; |
| 6 | import org.projectfloodlight.openflow.exceptions.OFParseError; |
| 7 | import org.projectfloodlight.openflow.protocol.OFMessageReader; |
| 8 | import org.projectfloodlight.openflow.protocol.Writeable; |
| 9 | |
| 10 | import com.google.common.base.Charsets; |
| 11 | import com.google.common.collect.ImmutableList; |
| 12 | import 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 | |
| 20 | public class ChannelUtils { |
| 21 | public static String readFixedLengthString(ChannelBuffer bb, int length) { |
| 22 | byte[] dst = new byte[length]; |
| 23 | bb.readBytes(dst, 0, length); |
| 24 | return new String(dst, Charsets.US_ASCII); |
| 25 | } |
| 26 | |
| 27 | public static void writeFixedLengthString(ChannelBuffer bb, String string, |
| 28 | int length) { |
| 29 | int l = string.length(); |
| 30 | if (l > length) { |
| 31 | throw new IllegalArgumentException("Error writing string: length=" |
| 32 | + l + " > max Length=" + length); |
| 33 | } |
| 34 | bb.writeBytes(string.getBytes(Charsets.US_ASCII)); |
| 35 | if (l < length) { |
| 36 | bb.writeZero(length - l); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | static public byte[] readBytes(final ChannelBuffer bb, final int length) { |
| 41 | byte byteArray[] = new byte[length]; |
| 42 | bb.readBytes(byteArray); |
| 43 | return byteArray; |
| 44 | } |
| 45 | |
| 46 | static public void writeBytes(final ChannelBuffer bb, |
| 47 | final byte byteArray[]) { |
| 48 | bb.writeBytes(byteArray); |
| 49 | } |
| 50 | |
| 51 | public static <T> List<T> readList(ChannelBuffer bb, int length, OFMessageReader<T> reader) throws OFParseError { |
| 52 | int end = bb.readerIndex() + length; |
| 53 | Builder<T> builder = ImmutableList.<T>builder(); |
| 54 | while(bb.readerIndex() < end) { |
| 55 | builder.add(reader.readFrom(bb)); |
| 56 | } |
| 57 | if(bb.readerIndex() != end) { |
| 58 | throw new IllegalStateException("Overread length: length="+length + " overread by "+ (bb.readerIndex() - end) + " reader: "+reader); |
| 59 | } |
| 60 | return builder.build(); |
| 61 | } |
| 62 | |
| 63 | public static void writeList(ChannelBuffer bb, List<? extends Writeable> writeables) { |
| 64 | for(Writeable w: writeables) |
| 65 | w.writeTo(bb); |
| 66 | } |
| 67 | } |