001package org.unix4j.unix.xargs;
002
003import org.unix4j.line.Line;
004import org.unix4j.util.StringUtil;
005
006class WhitespaceItemizer implements Itemizer {
007        
008        private boolean lastLineWithTrailingWhitespace;
009        
010        public WhitespaceItemizer() {
011                super();
012        }
013
014        @Override
015        public void itemizeLine(Line line, ItemStorage itemStorage) {
016                final int len = line.length();
017                int start = StringUtil.findStartTrimWhitespace(line);
018                int end = Integer.MAX_VALUE;
019                while (start < len) {
020                        end = start + 1;
021                        while (end < len && !Character.isWhitespace(line.charAt(end))) {
022                                end++;
023                        }
024                        final String item = line.subSequence(start, end).toString();
025                        itemStorage.storeItem(item);
026                        start = StringUtil.findStartTrimWhitespace(line, end);
027                }
028                lastLineWithTrailingWhitespace = end < line.getContentLength();
029                if (!lastLineWithTrailingWhitespace) {
030                        itemStorage.incrementLineCount();
031                }
032        }
033
034        @Override
035        public void finish(ItemStorage itemStorage) {
036                if (lastLineWithTrailingWhitespace) {
037                        itemStorage.incrementLineCount();
038                        lastLineWithTrailingWhitespace = false;
039                }
040        }
041
042}