

package org.apache.giraph.utils;

import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration;
import org.apache.giraph.edge.Edge;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

import java.io.IOException;

/**
 * Stores vertex id and edge pairs in a single byte array.
 *
 * @param <I> Vertex id
 * @param <E> Edge value
 */
@SuppressWarnings("unchecked")
public class ByteArrayVertexIdEdges<I extends WritableComparable,
    E extends Writable> extends ByteArrayVertexIdData<I, Edge<I, E>> {
  /**
   * Cast the {@link ImmutableClassesGiraphConfiguration} so it can be used
   * to generate edge objects.
   *
   * @return Casted configuration
   */
  @Override
  public ImmutableClassesGiraphConfiguration<I, ?, E> getConf() {
    return (ImmutableClassesGiraphConfiguration<I, ?, E>) super.getConf();
  }

  @Override
  public Edge<I, E> createData() {
    return getConf().createReusableEdge();
  }

  @Override
  public void writeData(ExtendedDataOutput out, Edge<I, E> edge)
    throws IOException {
    WritableUtils.writeEdge(out, edge);
  }

  @Override
  public void readData(ExtendedDataInput in, Edge<I, E> edge)
    throws IOException {
    WritableUtils.readEdge(in, edge);
  }

  /**
   * Get an iterator over the pairs.
   *
   * @return Iterator
   */
  public VertexIdEdgeIterator getVertexIdEdgeIterator() {
    return new VertexIdEdgeIterator();
  }

  /**
   * Special iterator that reuses vertex ids and edge objects so that the
   * lifetime of the object is only until next() is called.
   */
  public class VertexIdEdgeIterator extends VertexIdDataIterator {
    /**
     * Get the current edge.
     *
     * @return Current edge
     */
    public Edge<I, E> getCurrentEdge() {
      return getCurrentData();
    }

    /**
     * Release the current edge.
     *
     * @return Released edge
     */
    public Edge<I, E> releaseCurrentEdge() {
      return releaseCurrentData();
    }
  }
}

