001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.mapred.nativetask.serde;
020
021import java.io.ByteArrayOutputStream;
022import java.io.DataInput;
023import java.io.DataOutput;
024import java.io.DataOutputStream;
025import java.io.IOException;
026
027import org.apache.hadoop.classification.InterfaceAudience;
028import org.apache.hadoop.classification.InterfaceStability;
029import org.apache.hadoop.io.Writable;
030
031@InterfaceAudience.Public
032@InterfaceStability.Evolving
033public class DefaultSerializer implements INativeSerializer<Writable> {
034
035  static class ModifiedByteArrayOutputStream extends ByteArrayOutputStream {
036
037    public byte[] getBuffer() {
038      return this.buf;
039    }
040  }
041
042  private final ModifiedByteArrayOutputStream outBuffer = new ModifiedByteArrayOutputStream();
043  private final DataOutputStream outData = new DataOutputStream(outBuffer);
044  private Writable buffered = null;
045  private int bufferedLength = -1;
046
047  @Override
048  public int getLength(Writable w) throws IOException {
049    // if (w == buffered) {
050    // return bufferedLength;
051    // }
052    buffered = null;
053    bufferedLength = -1;
054
055    outBuffer.reset();
056    w.write(outData);
057    bufferedLength = outBuffer.size();
058    buffered = w;
059    return bufferedLength;
060  }
061
062  @Override
063  public void serialize(Writable w, DataOutput out) throws IOException {
064    w.write(out);
065  }
066
067  @Override
068  public void deserialize(DataInput in, int length, Writable w) throws IOException {
069    w.readFields(in);
070  }
071}