Path: blob/master/test/hotspot/jtreg/vmTestbase/vm/share/StringUtils.java
41153 views
/*1* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/22package vm.share;2324import java.io.ByteArrayOutputStream;25import java.util.Random;26import java.util.function.Predicate;2728public class StringUtils {2930public static byte[] binaryReplace(final byte[] src, String search,31String replacement) {32if (search.length() == 0)33return src;3435int nReplaced = 0;3637try {38final byte[] bSrch = search.getBytes("ASCII");39final byte[] bRepl = replacement.getBytes("ASCII");4041ByteArrayOutputStream out = new ByteArrayOutputStream();42try {43searching: for (int i = 0; i < src.length; i++) {44if (src[i] == bSrch[0]) {45replacing: do {46for (int ii = 1; ii < Math.min(bSrch.length,47src.length - i); ii++)48if (src[i + ii] != bSrch[ii])49break replacing;5051out.write(bRepl);52i += bSrch.length - 1;53nReplaced++;54continue searching;55} while (false);56}5758out.write(src[i]);59}6061return out.toByteArray();6263} finally {64out.close();65}66} catch (Exception e) {67RuntimeException t = new RuntimeException("Test internal error");68t.initCause(e);69throw t;70}71}7273public static String generateString(Random rng, int length,74Predicate<Character> predicate) {75if (length <= 0) {76throw new IllegalArgumentException("length <= 0");77}78StringBuilder builder = new StringBuilder(length);79for (int i = 0; i < length; ++i) {80char tmp;81do {82tmp = (char) rng.nextInt(Character.MAX_VALUE);83} while (!predicate.test(tmp));84builder.append(tmp);85}86return builder.toString();87}88}899091