blob: 6949fb251d53cb836441020df6783eefe2450c79 [file] [log] [blame]
tom0eb04ca2014-08-25 14:34:51 -07001/**
2 * Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
3 * University
4 *
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
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
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
15 * under the License.
16 **/
17
18package org.projectfloodlight.openflow.util;
19
20import java.io.UnsupportedEncodingException;
21import java.nio.charset.Charset;
22import java.util.Arrays;
23
24import org.jboss.netty.buffer.ChannelBuffer;
25
26public class StringByteSerializer {
27 public static String readFrom(final ChannelBuffer data, final int length) {
28 byte[] stringBytes = new byte[length];
29 data.readBytes(stringBytes);
30 // find the first index of 0
31 int index = 0;
32 for (byte b : stringBytes) {
33 if (0 == b)
34 break;
35 ++index;
36 }
37 return new String(Arrays.copyOf(stringBytes, index), Charset.forName("ascii"));
38 }
39
40 public static void writeTo(final ChannelBuffer data, final int length,
41 final String value) {
42 try {
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);
48 }
49 } else {
50 data.writeBytes(name, 0, length - 1);
51 data.writeByte((byte) 0);
52 }
53 } catch (UnsupportedEncodingException e) {
54 throw new RuntimeException(e);
55 }
56
57 }
58}