View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.internal;
17  
18  import java.io.IOException;
19  import java.util.ArrayList;
20  import java.util.Iterator;
21  import java.util.List;
22  
23  import static io.netty.util.internal.ObjectUtil.*;
24  
25  /**
26   * String utility class.
27   */
28  public final class StringUtil {
29  
30      public static final String EMPTY_STRING = "";
31      public static final String NEWLINE = SystemPropertyUtil.get("line.separator", "\n");
32  
33      public static final char DOUBLE_QUOTE = '\"';
34      public static final char COMMA = ',';
35      public static final char LINE_FEED = '\n';
36      public static final char CARRIAGE_RETURN = '\r';
37      public static final char TAB = '\t';
38      public static final char SPACE = 0x20;
39  
40      /**
41       * 2 - Quote character at beginning and end.
42       * 5 - Extra allowance for anticipated escape characters that may be added.
43       */
44      private static final int CSV_NUMBER_ESCAPE_CHARACTERS = 2 + 5;
45      private static final char PACKAGE_SEPARATOR_CHAR = '.';
46  
47      /**
48       * Lazily initialized byte to hexadecimal string tables. {@link StringUtil} is loaded very early by most Netty
49       * applications, through {@link #simpleClassName(Class)} and friends, while these tables are only needed for hex
50       * dumps, so they are kept in a holder to not pay for the 512 strings at startup.
51       */
52      private static final class Byte2Hex {
53          static final String[] PAD = new String[256];
54          static final String[] NOPAD = new String[256];
55  
56          static {
57              // Generate the lookup table that converts a byte into a 2-digit hexadecimal integer.
58              for (int i = 0; i < PAD.length; i++) {
59                  String str = Integer.toHexString(i);
60                  PAD[i] = i > 0xf ? str : ('0' + str);
61                  NOPAD[i] = str;
62              }
63          }
64      }
65  
66      /**
67       * Lazily initialized hexadecimal digit to value table, kept separate from {@link Byte2Hex} so that decoding
68       * (used for instance to parse the machine id) does not pay for the byte to string tables.
69       * <p>
70       * The table stores {@code value + 1}: a zero entry means "not a hex digit", so the zero-filled array needs no
71       * {@code Arrays.fill} pass over its 64 KiB, which is costly when run by the interpreter at startup.
72       */
73      private static final class Hex2B {
74          // the size of the table is such that the JVM is capable of save any bounds-check
75          // if a char type is used as an index.
76          static final byte[] TABLE = new byte[Character.MAX_VALUE + 1];
77  
78          static {
79              TABLE['0'] = 1;
80              TABLE['1'] = 2;
81              TABLE['2'] = 3;
82              TABLE['3'] = 4;
83              TABLE['4'] = 5;
84              TABLE['5'] = 6;
85              TABLE['6'] = 7;
86              TABLE['7'] = 8;
87              TABLE['8'] = 9;
88              TABLE['9'] = 10;
89              TABLE['A'] = 11;
90              TABLE['B'] = 12;
91              TABLE['C'] = 13;
92              TABLE['D'] = 14;
93              TABLE['E'] = 15;
94              TABLE['F'] = 16;
95              TABLE['a'] = 11;
96              TABLE['b'] = 12;
97              TABLE['c'] = 13;
98              TABLE['d'] = 14;
99              TABLE['e'] = 15;
100             TABLE['f'] = 16;
101         }
102     }
103 
104     private StringUtil() {
105         // Unused.
106     }
107 
108     /**
109      * Get the item after one char delim if the delim is found (else null).
110      * This operation is a simplified and optimized
111      * version of {@link String#split(String, int)}.
112      */
113     public static String substringAfter(String value, char delim) {
114         int pos = value.indexOf(delim);
115         if (pos >= 0) {
116             return value.substring(pos + 1);
117         }
118         return null;
119     }
120 
121     /**
122      * Get the item before one char delim if the delim is found (else null).
123      * This operation is a simplified and optimized
124      * version of {@link String#split(String, int)}.
125      */
126     public static String substringBefore(String value, char delim) {
127         int pos = value.indexOf(delim);
128         if (pos >= 0) {
129             return value.substring(0, pos);
130         }
131         return null;
132     }
133 
134     /**
135      * Checks if two strings have the same suffix of specified length
136      *
137      * @param s   string
138      * @param p   string
139      * @param len length of the common suffix
140      * @return true if both s and p are not null and both have the same suffix. Otherwise - false
141      */
142     public static boolean commonSuffixOfLength(String s, String p, int len) {
143         return s != null && p != null && len >= 0 && s.regionMatches(s.length() - len, p, p.length() - len, len);
144     }
145 
146     /**
147      * Converts the specified byte value into a 2-digit hexadecimal integer.
148      */
149     public static String byteToHexStringPadded(int value) {
150         return Byte2Hex.PAD[value & 0xff];
151     }
152 
153     /**
154      * Converts the specified byte value into a 2-digit hexadecimal integer and appends it to the specified buffer.
155      */
156     public static <T extends Appendable> T byteToHexStringPadded(T buf, int value) {
157         try {
158             buf.append(byteToHexStringPadded(value));
159         } catch (IOException e) {
160             PlatformDependent.throwException(e);
161         }
162         return buf;
163     }
164 
165     /**
166      * Converts the specified byte array into a hexadecimal value.
167      */
168     public static String toHexStringPadded(byte[] src) {
169         return toHexStringPadded(src, 0, src.length);
170     }
171 
172     /**
173      * Converts the specified byte array into a hexadecimal value.
174      */
175     public static String toHexStringPadded(byte[] src, int offset, int length) {
176         return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString();
177     }
178 
179     /**
180      * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
181      */
182     public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src) {
183         return toHexStringPadded(dst, src, 0, src.length);
184     }
185 
186     /**
187      * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
188      */
189     public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src, int offset, int length) {
190         final int end = offset + length;
191         for (int i = offset; i < end; i++) {
192             byteToHexStringPadded(dst, src[i]);
193         }
194         return dst;
195     }
196 
197     /**
198      * Converts the specified byte value into a hexadecimal integer.
199      */
200     public static String byteToHexString(int value) {
201         return Byte2Hex.NOPAD[value & 0xff];
202     }
203 
204     /**
205      * Converts the specified byte value into a hexadecimal integer and appends it to the specified buffer.
206      */
207     public static <T extends Appendable> T byteToHexString(T buf, int value) {
208         try {
209             buf.append(byteToHexString(value));
210         } catch (IOException e) {
211             PlatformDependent.throwException(e);
212         }
213         return buf;
214     }
215 
216     /**
217      * Converts the specified byte array into a hexadecimal value.
218      */
219     public static String toHexString(byte[] src) {
220         return toHexString(src, 0, src.length);
221     }
222 
223     /**
224      * Converts the specified byte array into a hexadecimal value.
225      */
226     public static String toHexString(byte[] src, int offset, int length) {
227         return toHexString(new StringBuilder(length << 1), src, offset, length).toString();
228     }
229 
230     /**
231      * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
232      */
233     public static <T extends Appendable> T toHexString(T dst, byte[] src) {
234         return toHexString(dst, src, 0, src.length);
235     }
236 
237     /**
238      * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
239      */
240     public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) {
241         assert length >= 0;
242         if (length == 0) {
243             return dst;
244         }
245 
246         final int end = offset + length;
247         final int endMinusOne = end - 1;
248         int i;
249 
250         // Skip preceding zeroes.
251         for (i = offset; i < endMinusOne; i++) {
252             if (src[i] != 0) {
253                 break;
254             }
255         }
256 
257         byteToHexString(dst, src[i++]);
258         int remaining = end - i;
259         toHexStringPadded(dst, src, i, remaining);
260 
261         return dst;
262     }
263 
264     /**
265      * Helper to decode half of a hexadecimal number from a string.
266      * @param c The ASCII character of the hexadecimal number to decode.
267      * Must be in the range {@code [0-9a-fA-F]}.
268      * @return The hexadecimal value represented in the ASCII character
269      * given, or {@code -1} if the character is invalid.
270      */
271     public static int decodeHexNibble(final char c) {
272         // Character.digit() is not used here, as it addresses a larger
273         // set of characters (both ASCII and full-width latin letters).
274         return Hex2B.TABLE[c] - 1;
275     }
276 
277     /**
278      * Helper to decode half of a hexadecimal number from a string.
279      * @param b The ASCII character of the hexadecimal number to decode.
280      * Must be in the range {@code [0-9a-fA-F]}.
281      * @return The hexadecimal value represented in the ASCII character
282      * given, or {@code -1} if the character is invalid.
283      */
284     public static int decodeHexNibble(final byte b) {
285         // Character.digit() is not used here, as it addresses a larger
286         // set of characters (both ASCII and full-width latin letters).
287         return Hex2B.TABLE[b & 0xFF] - 1;
288     }
289 
290     /**
291      * Decode a 2-digit hex byte from within a string.
292      */
293     public static byte decodeHexByte(CharSequence s, int pos) {
294         int hi = decodeHexNibble(s.charAt(pos));
295         int lo = decodeHexNibble(s.charAt(pos + 1));
296         if (hi == -1 || lo == -1) {
297             throw new IllegalArgumentException(String.format(
298                     "invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s));
299         }
300         return (byte) ((hi << 4) + lo);
301     }
302 
303     /**
304      * Decodes part of a string with <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
305      *
306      * @param hexDump a {@link CharSequence} which contains the hex dump
307      * @param fromIndex start of hex dump in {@code hexDump}
308      * @param length hex string length
309      */
310     public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) {
311         if (length < 0 || (length & 1) != 0) {
312             throw new IllegalArgumentException("length: " + length);
313         }
314         if (length == 0) {
315             return EmptyArrays.EMPTY_BYTES;
316         }
317         byte[] bytes = new byte[length >>> 1];
318         for (int i = 0; i < length; i += 2) {
319             bytes[i >>> 1] = decodeHexByte(hexDump, fromIndex + i);
320         }
321         return bytes;
322     }
323 
324     /**
325      * Decodes a <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
326      */
327     public static byte[] decodeHexDump(CharSequence hexDump) {
328         return decodeHexDump(hexDump, 0, hexDump.length());
329     }
330 
331     /**
332      * The shortcut to {@link #simpleClassName(Class) simpleClassName(o.getClass())}.
333      */
334     public static String simpleClassName(Object o) {
335         if (o == null) {
336             return "null_object";
337         } else {
338             return simpleClassName(o.getClass());
339         }
340     }
341 
342     /**
343      * Generates a simplified name from a {@link Class}.  Similar to {@link Class#getSimpleName()}, but it works fine
344      * with anonymous classes.
345      */
346     public static String simpleClassName(Class<?> clazz) {
347         String className = checkNotNull(clazz, "clazz").getName();
348         final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
349         if (lastDotIdx > -1) {
350             return className.substring(lastDotIdx + 1);
351         }
352         return className;
353     }
354 
355     /**
356      * Escapes the specified value, if necessary according to
357      * <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
358      *
359      * @param value The value which will be escaped according to
360      *              <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
361      * @return {@link CharSequence} the escaped value if necessary, or the value unchanged
362      */
363     public static CharSequence escapeCsv(CharSequence value) {
364         return escapeCsv(value, false);
365     }
366 
367     /**
368      * Escapes the specified value, if necessary according to
369      * <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
370      *
371      * @param value          The value which will be escaped according to
372      *                       <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
373      * @param trimWhiteSpace The value will first be trimmed of its optional white-space characters,
374      *                       according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a>
375      * @return {@link CharSequence} the escaped value if necessary, or the value unchanged
376      */
377     public static CharSequence escapeCsv(CharSequence value, boolean trimWhiteSpace) {
378         int length = checkNotNull(value, "value").length();
379         int start;
380         int last;
381         if (trimWhiteSpace) {
382             start = indexOfFirstNonOwsChar(value, length);
383             last = indexOfLastNonOwsChar(value, start, length);
384         } else {
385             start = 0;
386             last = length - 1;
387         }
388         if (start > last) {
389             return EMPTY_STRING;
390         }
391 
392         int firstUnescapedSpecial = -1;
393         boolean quoted = false;
394         if (isDoubleQuote(value.charAt(start))) {
395             quoted = isDoubleQuote(value.charAt(last)) && last > start;
396             if (quoted) {
397                 start++;
398                 last--;
399             } else {
400                 firstUnescapedSpecial = start;
401             }
402         }
403 
404         if (firstUnescapedSpecial < 0) {
405             if (quoted) {
406                 for (int i = start; i <= last; i++) {
407                     if (isDoubleQuote(value.charAt(i))) {
408                         if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
409                             firstUnescapedSpecial = i;
410                             break;
411                         }
412                         i++;
413                     }
414                 }
415             } else {
416                 for (int i = start; i <= last; i++) {
417                     char c = value.charAt(i);
418                     if (c == LINE_FEED || c == CARRIAGE_RETURN || c == COMMA) {
419                         firstUnescapedSpecial = i;
420                         break;
421                     }
422                     if (isDoubleQuote(c)) {
423                         if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
424                             firstUnescapedSpecial = i;
425                             break;
426                         }
427                         i++;
428                     }
429                 }
430             }
431 
432             if (firstUnescapedSpecial < 0) {
433                 // Special characters is not found or all of them already escaped.
434                 // In the most cases returns a same string. New string will be instantiated (via StringBuilder)
435                 // only if it really needed. It's important to prevent GC extra load.
436                 return quoted? value.subSequence(start - 1, last + 2) : value.subSequence(start, last + 1);
437             }
438         }
439 
440         StringBuilder result = new StringBuilder(last - start + 1 + CSV_NUMBER_ESCAPE_CHARACTERS);
441         result.append(DOUBLE_QUOTE).append(value, start, firstUnescapedSpecial);
442         for (int i = firstUnescapedSpecial; i <= last; i++) {
443             char c = value.charAt(i);
444             if (isDoubleQuote(c)) {
445                 result.append(DOUBLE_QUOTE);
446                 if (i < last && isDoubleQuote(value.charAt(i + 1))) {
447                     i++;
448                 }
449             }
450             result.append(c);
451         }
452         return result.append(DOUBLE_QUOTE);
453     }
454 
455     /**
456      * Unescapes the specified escaped CSV field, if necessary according to
457      * <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
458      *
459      * @param value The escaped CSV field which will be unescaped according to
460      *              <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
461      * @return {@link CharSequence} the unescaped value if necessary, or the value unchanged
462      */
463     public static CharSequence unescapeCsv(CharSequence value) {
464         int length = checkNotNull(value, "value").length();
465         if (length == 0) {
466             return value;
467         }
468         int last = length - 1;
469         boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length != 1;
470         if (!quoted) {
471             validateCsvFormat(value);
472             return value;
473         }
474         StringBuilder unescaped = InternalThreadLocalMap.get().stringBuilder();
475         for (int i = 1; i < last; i++) {
476             char current = value.charAt(i);
477             if (current == DOUBLE_QUOTE) {
478                 if (isDoubleQuote(value.charAt(i + 1)) && (i + 1) != last) {
479                     // Followed by a double-quote but not the last character
480                     // Just skip the next double-quote
481                     i++;
482                 } else {
483                     // Not followed by a double-quote or the following double-quote is the last character
484                     throw newInvalidEscapedCsvFieldException(value, i);
485                 }
486             }
487             unescaped.append(current);
488         }
489         return unescaped.toString();
490     }
491 
492     /**
493      * Unescapes the specified escaped CSV fields according to
494      * <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
495      *
496      * @param value A string with multiple CSV escaped fields which will be unescaped according to
497      *              <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
498      * @return {@link List} the list of unescaped fields
499      */
500     public static List<CharSequence> unescapeCsvFields(CharSequence value) {
501         List<CharSequence> unescaped = new ArrayList<CharSequence>(2);
502         StringBuilder current = InternalThreadLocalMap.get().stringBuilder();
503         boolean quoted = false;
504         int last = value.length() - 1;
505         for (int i = 0; i <= last; i++) {
506             char c = value.charAt(i);
507             if (quoted) {
508                 switch (c) {
509                     case DOUBLE_QUOTE:
510                         if (i == last) {
511                             // Add the last field and return
512                             unescaped.add(current.toString());
513                             return unescaped;
514                         }
515                         char next = value.charAt(++i);
516                         if (next == DOUBLE_QUOTE) {
517                             // 2 double-quotes should be unescaped to one
518                             current.append(DOUBLE_QUOTE);
519                             break;
520                         }
521                         if (next == COMMA) {
522                             // This is the end of a field. Let's start to parse the next field.
523                             quoted = false;
524                             unescaped.add(current.toString());
525                             current.setLength(0);
526                             break;
527                         }
528                         // double-quote followed by other character is invalid
529                         throw newInvalidEscapedCsvFieldException(value, i - 1);
530                     default:
531                         current.append(c);
532                 }
533             } else {
534                 switch (c) {
535                     case COMMA:
536                         // Start to parse the next field
537                         unescaped.add(current.toString());
538                         current.setLength(0);
539                         break;
540                     case DOUBLE_QUOTE:
541                         if (current.length() == 0) {
542                             quoted = true;
543                             break;
544                         }
545                         // double-quote appears without being enclosed with double-quotes
546                         // fall through
547                     case LINE_FEED:
548                         // fall through
549                     case CARRIAGE_RETURN:
550                         // special characters appears without being enclosed with double-quotes
551                         throw newInvalidEscapedCsvFieldException(value, i);
552                     default:
553                         current.append(c);
554                 }
555             }
556         }
557         if (quoted) {
558             throw newInvalidEscapedCsvFieldException(value, last);
559         }
560         unescaped.add(current.toString());
561         return unescaped;
562     }
563 
564     /**
565      * Validate if {@code value} is a valid csv field without double-quotes.
566      *
567      * @throws IllegalArgumentException if {@code value} needs to be encoded with double-quotes.
568      */
569     private static void validateCsvFormat(CharSequence value) {
570         int length = value.length();
571         for (int i = 0; i < length; i++) {
572             switch (value.charAt(i)) {
573                 case DOUBLE_QUOTE:
574                 case LINE_FEED:
575                 case CARRIAGE_RETURN:
576                 case COMMA:
577                     // If value contains any special character, it should be enclosed with double-quotes
578                     throw newInvalidEscapedCsvFieldException(value, i);
579                 default:
580             }
581         }
582     }
583 
584     private static IllegalArgumentException newInvalidEscapedCsvFieldException(CharSequence value, int index) {
585         return new IllegalArgumentException("invalid escaped CSV field: " + value + " index: " + index);
586     }
587 
588     /**
589      * Get the length of a string, {@code null} input is considered {@code 0} length.
590      */
591     public static int length(String s) {
592         return s == null ? 0 : s.length();
593     }
594 
595     /**
596      * Determine if a string is {@code null} or {@link String#isEmpty()} returns {@code true}.
597      */
598     public static boolean isNullOrEmpty(String s) {
599         return s == null || s.isEmpty();
600     }
601 
602     /**
603      * Find the index of the first non-white space character in {@code s} starting at {@code offset}.
604      *
605      * @param seq    The string to search.
606      * @param offset The offset to start searching at.
607      * @return the index of the first non-white space character or &lt;{@code -1} if none was found.
608      */
609     public static int indexOfNonWhiteSpace(CharSequence seq, int offset) {
610         for (; offset < seq.length(); ++offset) {
611             if (!Character.isWhitespace(seq.charAt(offset))) {
612                 return offset;
613             }
614         }
615         return -1;
616     }
617 
618     /**
619      * Find the index of the first white space character in {@code s} starting at {@code offset}.
620      *
621      * @param seq    The string to search.
622      * @param offset The offset to start searching at.
623      * @return the index of the first white space character or &lt;{@code -1} if none was found.
624      */
625     public static int indexOfWhiteSpace(CharSequence seq, int offset) {
626         for (; offset < seq.length(); ++offset) {
627             if (Character.isWhitespace(seq.charAt(offset))) {
628                 return offset;
629             }
630         }
631         return -1;
632     }
633 
634     /**
635      * Determine if {@code c} lies within the range of values defined for
636      * <a href="https://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>.
637      *
638      * @param c the character to check.
639      * @return {@code true} if {@code c} lies within the range of values defined for
640      * <a href="https://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>. {@code false} otherwise.
641      */
642     public static boolean isSurrogate(char c) {
643         return c >= '\uD800' && c <= '\uDFFF';
644     }
645 
646     private static boolean isDoubleQuote(char c) {
647         return c == DOUBLE_QUOTE;
648     }
649 
650     /**
651      * Determine if the string {@code s} ends with the char {@code c}.
652      *
653      * @param s the string to test
654      * @param c the tested char
655      * @return true if {@code s} ends with the char {@code c}
656      */
657     public static boolean endsWith(CharSequence s, char c) {
658         int len = s.length();
659         return len > 0 && s.charAt(len - 1) == c;
660     }
661 
662     /**
663      * Trim optional white-space characters from the specified value,
664      * according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a>.
665      *
666      * @param value the value to trim
667      * @return {@link CharSequence} the trimmed value if necessary, or the value unchanged
668      */
669     public static CharSequence trimOws(CharSequence value) {
670         final int length = value.length();
671         if (length == 0) {
672             return value;
673         }
674         int start = indexOfFirstNonOwsChar(value, length);
675         int end = indexOfLastNonOwsChar(value, start, length);
676         return start == 0 && end == length - 1 ? value : value.subSequence(start, end + 1);
677     }
678 
679     /**
680      * Returns a char sequence that contains all {@code elements} joined by a given separator.
681      *
682      * @param separator for each element
683      * @param elements to join together
684      *
685      * @return a char sequence joined by a given separator.
686      */
687     public static CharSequence join(CharSequence separator, Iterable<? extends CharSequence> elements) {
688         ObjectUtil.checkNotNull(separator, "separator");
689         ObjectUtil.checkNotNull(elements, "elements");
690 
691         Iterator<? extends CharSequence> iterator = elements.iterator();
692         if (!iterator.hasNext()) {
693             return EMPTY_STRING;
694         }
695 
696         CharSequence firstElement = iterator.next();
697         if (!iterator.hasNext()) {
698             return firstElement;
699         }
700 
701         StringBuilder builder = new StringBuilder(firstElement);
702         do {
703             builder.append(separator).append(iterator.next());
704         } while (iterator.hasNext());
705 
706         return builder;
707     }
708 
709     /**
710      * @return {@code length} if no OWS is found.
711      */
712     private static int indexOfFirstNonOwsChar(CharSequence value, int length) {
713         int i = 0;
714         while (i < length && isOws(value.charAt(i))) {
715             i++;
716         }
717         return i;
718     }
719 
720     /**
721      * @return {@code start} if no OWS is found.
722      */
723     private static int indexOfLastNonOwsChar(CharSequence value, int start, int length) {
724         int i = length - 1;
725         while (i > start && isOws(value.charAt(i))) {
726             i--;
727         }
728         return i;
729     }
730 
731     private static boolean isOws(char c) {
732         return c == SPACE || c == TAB;
733     }
734 
735 }