001package org.unix4j.unix.tail;
002
003import org.unix4j.context.ExecutionContext;
004import org.unix4j.line.Line;
005import org.unix4j.line.SimpleLine;
006import org.unix4j.processor.LineProcessor;
007import org.unix4j.util.Counter;
008
009class TailCharsFromStartProcessor extends AbstractTailProcessor {
010
011        private final Counter counter = new Counter();
012
013    @Override
014    public void resetCountersAndFlush() {
015        counter.reset();
016    }
017
018    public TailCharsFromStartProcessor(TailCommand command, ExecutionContext context, LineProcessor output) {
019                super(command, context, output);
020        }
021
022        @Override
023        public boolean processLine(Line line) {
024                final long before = counter.getCount();
025                if (before >= count) {
026                        return getOutput().processLine(line);
027                } else {
028                        final long after = counter.increment(line.length());
029                        if (after >= count) {
030                                final int lineLen = line.length();
031                                final int charsFromEnd = (int)(after - count + 1);
032                                final Line cutLine = SimpleLine.subLine(line, lineLen - charsFromEnd, lineLen, false);
033                                return getOutput().processLine(cutLine);
034                        } else {
035                                return true;//we want more lines
036                        }
037                }
038        }
039
040        @Override
041        public void finish() {
042        resetCountersAndFlush();
043                getOutput().finish();
044        }
045}