//
// MessagePack for Java
//
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
package org.msgpack.template;

import java.nio.ByteBuffer;
import java.io.IOException;
import org.msgpack.*;

public class ByteBufferTemplate implements Template {
	private ByteBufferTemplate() { }

	public void pack(Packer pk, Object target) throws IOException {
		byte[] bytes = byteBufferToByteArray((ByteBuffer)target);
		pk.packByteArray(bytes);
	}

	private static byte[] byteBufferToByteArray(ByteBuffer b) {
		if (b.hasArray() && b.position() == 0 && b.arrayOffset() == 0
				&& b.remaining() == b.capacity()) {
			return b.array();
		} else {
			int size = b.remaining();
			byte[] bytes = new byte[size];
			System.arraycopy(b.array(), b.arrayOffset() + b.position(), bytes, 0, size);
			return bytes;
		}
	}

	public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
		byte[] bytes = pac.unpackByteArray();
		return ByteBuffer.wrap(bytes);
	}

	public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
		byte[] bytes = from.asByteArray();
		return ByteBuffer.wrap(bytes);
	}

	static public ByteBufferTemplate getInstance() {
		return instance;
	}

	static final ByteBufferTemplate instance = new ByteBufferTemplate();

	static {
		TemplateRegistry.register(ByteBuffer.class, instance);
	}
}


@@ -927,45 +927,25 @@
 %7B%0A%09%09
-byte%5B%5D bytes = byteBufferToByteArray(
+ByteBuffer buf = 
 (Byt
@@ -952,23 +952,23 @@
 eBuffer)
+ 
 target
-)
 ;%0A%09%09pk.p
@@ -974,311 +974,50 @@
 pack
-ByteArray(bytes);%0A%09%7D%0A%0A%09private static byte%5B%5D byteBufferToByteArray(ByteBuffer b) %7B%0A%09%09if (b.hasArray() && b.position() == 0 && b.arrayOffset() == 0%0A%09%09%09%09&& b.remaining() == b.capacity()) %7B%0A%09%09%09return b.array();%0A%09%09%7D else %7B%0A%09%09%09int size = b.remaining();%0A%09%09%09byte%5B%5D bytes = new byte%5Bsize%5D;%0A%09%09%09System.arraycop
+Raw(buf.remaining());%0A%09%09pk.packRawBod
 y(b
+uf
 .arr
@@ -1023,16 +1023,18 @@
 ray(), b
+uf
 .arrayOf
@@ -1043,16 +1043,18 @@
 et() + b
+uf
 .positio
@@ -1063,44 +1063,24 @@
 ), b
-ytes, 0, size);%0A%09%09%09return bytes;%0A%09%09%7D
+uf.remaining());
 %0A%09%7D%0A

refactor ByteBufferTemplate.java