001package org.unix4j.unix.xargs; 002 003import org.unix4j.line.Line; 004 005class CharDelimitedItemizer implements Itemizer { 006 007 private final char delimiter; 008 009 private StringBuilder multiLine = new StringBuilder(); 010 011 public CharDelimitedItemizer(char delimiter) { 012 this.delimiter = delimiter; 013 } 014 015 @Override 016 public void itemizeLine(Line line, ItemStorage itemStorage) { 017 final int len = line.length(); 018 019 if (line.getLineEndingLength() == 1 && line.getLineEnding().charAt(0) == delimiter) { 020 //the delim is the line ending (e.g. for \0 terminated lines) 021 //it is a constraint for the Line that no other such character 022 //exists in the content part of the line 023 itemStorage.storeItem(line.getContent()); 024 } else { 025 int start = 0; 026 int end = 0; 027 while (end < len) { 028 if (delimiter != line.charAt(end)) { 029 end++; 030 } else { 031 if (multiLine.length() > 0) { 032 multiLine.append(line, start, end); 033 itemStorage.storeItem(multiLine.toString()); 034 multiLine.setLength(0); 035 } else { 036 final CharSequence item = line.subSequence(start, end); 037 itemStorage.storeItem(item.toString()); 038 } 039 start = end + 1; 040 end = start; 041 } 042 } 043 if (start < len) { 044 multiLine.append(line, start, len); 045 } 046 } 047 itemStorage.incrementLineCount(); 048 } 049 050 @Override 051 public void finish(ItemStorage itemStorage) { 052 if (multiLine.length() > 0) { 053 itemStorage.storeItem(multiLine.toString()); 054 multiLine.setLength(0); 055 } 056 } 057}