Umesh Krishnaswamy | 345ee99 | 2012-12-13 20:29:48 -0800 | [diff] [blame] | 1 | /** |
| 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 | |
| 18 | package org.openflow.util; |
| 19 | |
| 20 | import java.io.UnsupportedEncodingException; |
| 21 | import java.nio.charset.Charset; |
| 22 | import java.util.Arrays; |
| 23 | |
| 24 | import org.jboss.netty.buffer.ChannelBuffer; |
| 25 | |
| 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 |
| 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), |
| 38 | Charset.forName("ascii")); |
| 39 | } |
| 40 | |
| 41 | public static void writeTo(ChannelBuffer data, int length, 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 | } |