001package org.unix4j.unix.uniq; 002 003import org.unix4j.line.Line; 004import org.unix4j.line.SimpleLine; 005import org.unix4j.processor.LineProcessor; 006import org.unix4j.util.StringUtil; 007 008/** 009 * Helper class to format count output of the uniq command. 010 */ 011class CountUtil { 012 013 /** 014 * Formats the given {@code count} value to the fixed string length 015 * {@code maxDigitsForCount} padding it with spaces from the left if 016 * necessary. Note that the returned string can be longer than 017 * {@code maxDigitsForCount} as values are never truncated. 018 * 019 * @param count 020 * the count value to format 021 * @param countDigits 022 * the number of digits to use, padding the given value with 023 * spaces from left if necessary 024 * @return the formatted count string, the right-aligned {@code value} 025 * padded with spaces from the left if necessary 026 */ 027 public static String formatCount(long count, int countDigits) { 028 final String scount = String.valueOf(count); 029 return scount.length() <= countDigits ? StringUtil.fixSizeString(countDigits, false, ' ', count) : scount; 030 } 031 032 /** 033 * Writes the given line prefixed with the count using the format <br> 034 * {@code ' ' + <count> + ' ' + <line>} <br> 035 * and using {@link #formatCount(long, int)} to format {@code <count>}. 036 * 037 * @param line 038 * the line to write to the output 039 * @param count 040 * the count written before the line 041 * @param countDigits 042 * the number of digits to use for {@code <count>}, padding the 043 * given value with spaces from left if necessary 044 * @param output 045 * the output device to write to 046 * @return the length of the formatted count string as returned by 047 * {@code #formatCount(long, int)} 048 */ 049 public static int writeCountLine(Line line, long count, int countDigits, LineProcessor output) { 050 final String countString = formatCount(count, countDigits); 051 final Line outputLine = new SimpleLine(" " + countString + " " + line.getContent(), line.getLineEnding()); 052 output.processLine(outputLine); 053 return countString.length(); 054 } 055 056 // no instances 057 private CountUtil() { 058 super(); 059 } 060}