From bad57a329f05c8ba7e6ea3d0893bc760ec2434eb Mon Sep 17 00:00:00 2001 From: matthew16550 Date: Sun, 31 Oct 2021 16:27:39 +1100 Subject: [PATCH] Change StringUtils.isEmpty() & isNotEmpty() to avoid creating new strings --- src/net/sourceforge/plantuml/StringUtils.java | 20 ++++++++----- .../sourceforge/plantuml/StringUtilsTest.java | 29 +++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 test/net/sourceforge/plantuml/StringUtilsTest.java diff --git a/src/net/sourceforge/plantuml/StringUtils.java b/src/net/sourceforge/plantuml/StringUtils.java index 4db4f0331..50dafe0aa 100644 --- a/src/net/sourceforge/plantuml/StringUtils.java +++ b/src/net/sourceforge/plantuml/StringUtils.java @@ -5,12 +5,12 @@ * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: http://plantuml.com - * + * * If you like this project or if you find it useful, you can support us at: - * + * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal - * + * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it @@ -119,16 +119,22 @@ public class StringUtils { return result; } - public static boolean isNotEmpty(String input) { - return input != null && trin(input).length() > 0; + public static boolean isNotEmpty(CharSequence s) { + return !isEmpty(s); } public static boolean isNotEmpty(List input) { return input != null && input.size() > 0; } - public static boolean isEmpty(String input) { - return input == null || trin(input).length() == 0; + public static boolean isEmpty(CharSequence s) { + if (s == null) return true; + final int length = s.length(); + if (length == 0) return true; + for (int i = 0; i < length; i++) { + if (!isSpaceOrTabOrNull(s.charAt(i))) return false; + } + return true; } public static String manageHtml(String s) { diff --git a/test/net/sourceforge/plantuml/StringUtilsTest.java b/test/net/sourceforge/plantuml/StringUtilsTest.java new file mode 100644 index 000000000..39c9f3600 --- /dev/null +++ b/test/net/sourceforge/plantuml/StringUtilsTest.java @@ -0,0 +1,29 @@ +package net.sourceforge.plantuml; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class StringUtilsTest { + + @ParameterizedTest + @CsvSource(nullValues = "null", value = { + " null , true ", + " '' , true ", + " ' ' , true ", + " '\0' , true ", + " '\n' , true ", + " '\r' , true ", + " '\t' , true ", + " 'x' , false ", + " ' x ' , false ", + }) + void test_isEmpty_isNotEmpty(String s, boolean empty) { + assertThat(StringUtils.isEmpty(s)) + .isEqualTo(empty); + + assertThat(StringUtils.isNotEmpty(s)) + .isNotEqualTo(empty); + } +}