2 * Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may
6 * not use this file except in compliance with the License. You may obtain
7 * a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 * License for the specific language governing permissions and limitations
18 package org.openflow.util;
20 import java.io.UnsupportedEncodingException;
21 import java.nio.charset.Charset;
22 import java.util.Arrays;
24 import org.jboss.netty.buffer.ChannelBuffer;
26 public class StringByteSerializer {
27 public static String readFrom(ChannelBuffer data, int length) {
28 byte[] stringBytes = new byte[length];
29 data.readBytes(stringBytes);
30 // find the first index of 0
32 for (byte b : stringBytes) {
37 return new String(Arrays.copyOf(stringBytes, index),
38 Charset.forName("ascii"));
41 public static void writeTo(ChannelBuffer data, int length, String value) {
43 byte[] name = value.getBytes("ASCII");
44 if (name.length < length) {
45 data.writeBytes(name);
46 for (int i = name.length; i < length; ++i) {
47 data.writeByte((byte) 0);
50 data.writeBytes(name, 0, length-1);
51 data.writeByte((byte) 0);
53 } catch (UnsupportedEncodingException e) {
54 throw new RuntimeException(e);