From ad433ecc1684683e3eba11dc198cc0d853299410 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Wed, 1 Jul 2020 17:21:55 -0400 Subject: [PATCH] Make internal API null-safe and Javadoc. --- .../commons/lang3/CharSequenceUtils.java | 23 +++++++++++-------- .../commons/lang3/CharSequenceUtilsTest.java | 1 + 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index fc5350f52..ad12d9938 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -299,20 +299,23 @@ public class CharSequenceUtils { } /** - * Green implementation of toCharArray. + * Converts the given CharSequence to a char[]. * - * @param cs the {@code CharSequence} to be processed - * @return the resulting char array + * @param source the {@code CharSequence} to be processed. + * @return the resulting char array, never null. * @since 3.11 */ - public static char[] toCharArray(final CharSequence cs) { - if (cs instanceof String) { - return ((String) cs).toCharArray(); + public static char[] toCharArray(final CharSequence source) { + final int len = StringUtils.length(source); + if (len == 0) { + return ArrayUtils.EMPTY_CHAR_ARRAY; } - final int sz = cs.length(); - final char[] array = new char[cs.length()]; - for (int i = 0; i < sz; i++) { - array[i] = cs.charAt(i); + if (source instanceof String) { + return ((String) source).toCharArray(); + } + final char[] array = new char[len]; + for (int i = 0; i < len; i++) { + array[i] = source.charAt(i); } return array; } diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java index b21144c1c..7e2f4d164 100644 --- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java @@ -186,6 +186,7 @@ public class CharSequenceUtilsTest { final char[] expected = builder.toString().toCharArray(); assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder)); assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder.toString())); + assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, CharSequenceUtils.toCharArray(null)); } static class WrapperString implements CharSequence {