001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.fusesource.hawtbuf.codec;
018    
019    import java.io.DataInput;
020    import java.io.DataOutput;
021    import java.io.IOException;
022    
023    import org.fusesource.hawtbuf.Buffer;
024    
025    /**
026     * Implementation of a Codec for Buffer objects
027     * 
028     * @author <a href="http://hiramchirino.com">Hiram Chirino</a>
029     */
030    abstract public class AbstractBufferCodec<T extends Buffer> extends VariableCodec<T> {
031    
032        public void encode(T value, DataOutput dataOut) throws IOException {
033            dataOut.writeInt(value.length);
034            dataOut.write(value.data, value.offset, value.length);
035        }
036    
037        public T decode(DataInput dataIn) throws IOException {
038            int size = dataIn.readInt();
039            byte[] data = new byte[size];
040            dataIn.readFully(data);
041            return createBuffer(data);
042        }
043    
044        abstract protected T createBuffer(byte [] data);
045        
046        public T deepCopy(T source) {
047            return createBuffer(source.deepCopy().data);
048        }
049    
050        public boolean isDeepCopySupported() {
051            return true;
052        }
053    
054        @Override
055        public boolean isEstimatedSizeSupported() {
056            return true;
057        }
058    
059        public int estimatedSize(T object) {
060            return object.length+4;
061        }
062    
063    }