1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 package org.apache.giraph.utils; 19 20 import java.io.IOException; 21 import java.util.Iterator; 22 import org.apache.hadoop.io.Writable; 23 24 /** 25 * This iterator is designed to deserialize a byte array on the fly to 26 * provide new copies of writable objects when desired. It does not reuse 27 * objects, and instead creates a new one for every next(). 28 * 29 * @param <T> Type that extends Writable that will be iterated 30 */ 31 public abstract class ByteStructIterator<T extends Writable> implements 32 Iterator<T> { 33 /** Data input */ 34 protected final ExtendedDataInput extendedDataInput; 35 36 /** 37 * Wrap ExtendedDataInput in ByteArrayIterator 38 * 39 * @param extendedDataInput ExtendedDataInput 40 */ 41 public ByteStructIterator(ExtendedDataInput extendedDataInput) { 42 this.extendedDataInput = extendedDataInput; 43 } 44 45 @Override 46 public boolean hasNext() { 47 return !extendedDataInput.endOfInput(); 48 } 49 50 @Override 51 public T next() { 52 T writable = createWritable(); 53 try { 54 writable.readFields(extendedDataInput); 55 } catch (IOException e) { 56 throw new IllegalStateException("next: readFields got IOException", e); 57 } 58 return writable; 59 } 60 61 @Override 62 public void remove() { 63 throw new UnsupportedOperationException("remove: Not supported"); 64 } 65 66 /** 67 * Must be able to create the writable object 68 * 69 * @return New writable 70 */ 71 protected abstract T createWritable(); 72 }