diff options
| author | Benjamin J. Culkin <bjculkin@mix.wvu.edu> | 2017-10-08 22:39:59 -0300 |
|---|---|---|
| committer | Benjamin J. Culkin <bjculkin@mix.wvu.edu> | 2017-10-08 22:39:59 -0300 |
| commit | c82e3b3b2de0633317ec8fc85925e91422820597 (patch) | |
| tree | 96567416ce23c5ce85601f9cedc3a94bb1c55cba /base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java | |
| parent | b3ac1c8690c3e14c879913e5dcc03a5f5e14876e (diff) | |
Start splitting into maven modules
Diffstat (limited to 'base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java')
| -rw-r--r-- | base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java new file mode 100644 index 0000000..f4d8439 --- /dev/null +++ b/base/src/main/java/bjc/utils/ioutils/blocks/FlatMappedBlockReader.java @@ -0,0 +1,86 @@ +package bjc.utils.ioutils.blocks; + +import java.io.IOException; + +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * A block reader that supports applying a flatmap operation to blocks. + * + * The use-case in mind for this was tokenizing blocks. + * + * @author Benjamin Culkin + */ +public class FlatMappedBlockReader implements BlockReader { + /* + * The source reader. + */ + private BlockReader reader; + + /* + * The current block, and any blocks pending from the last source block. + */ + private Iterator<Block> pending; + private Block current; + + /* + * The operator to open blocks with. + */ + private Function<Block, List<Block>> transform; + + /* + * The current block number. + */ + private int blockNo; + + public FlatMappedBlockReader(BlockReader source, Function<Block, List<Block>> trans) { + reader = source; + transform = trans; + + blockNo = 0; + } + + @Override + public boolean hasNextBlock() { + return pending.hasNext() || reader.hasNextBlock(); + } + + @Override + public Block getBlock() { + return current; + } + + @Override + public boolean nextBlock() { + /* + * Attempt to get a new pending list if the one we have isn't + * valid. + */ + while(pending == null || !pending.hasNext()) { + if(!reader.hasNext()) return false; + + pending = transform.apply(reader.next()).iterator(); + } + + /* + * Advance the iterator. + */ + current = pending.next(); + blockNo += 1; + + return true; + } + + @Override + public int getBlockCount() { + return blockNo; + } + + @Override + public void close() throws IOException { + reader.close(); + } +} |
