/*
 * Created on Jun 22, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 * Copyright BroadSoft, Inc.
 */
package com.broadsoft.clients.oci.util;

import java.nio.*;

/**
 * This class holds various static methods for serializing an object (and its encapsulated objects). 
 * @author imported from AS
 */
public class Serializer 
{
  /**
   * Serializes a String to a ByteBuffer *not* using the Serializable mechanism.
   * The string is put as is in the ByteBuffer, thus it should intrinsically
   * contain information on how to decode it (e.g. XML string)
   * The resulting stream can be unserialized using the unserializeString method.
   * @param string. Can be null.
   * @return ByteBuffer that is ready for relative gets
   * @throws Exception
   */
  public static ByteBuffer serializeString(String str) throws Exception
  {
    if (str == null) {
      return null;
    }
    byte[] bytes = str.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);
    buffer.flip();
    return buffer;
  }

  /** @see serializeString */
  public static String unserializeString(ByteBuffer buffer) throws Exception
  {
    int len = buffer.limit() - buffer.position();
    byte[] bytes = new byte[len];
    buffer.get(bytes);
    return new String(bytes);
  }
}
