ReplaceStreams: allow multiple replacements strings
[nikiroo-utils.git] / src / be / nikiroo / utils / streams / StreamUtils.java
1 package be.nikiroo.utils.streams;
2
3 import java.io.UnsupportedEncodingException;
4
5 /**
6 * Some non-public utilities used in the stream classes.
7 *
8 * @author niki
9 */
10 class StreamUtils {
11 /**
12 * Check if the buffer starts with the given search term (given as an array,
13 * a start position and an end position).
14 * <p>
15 * Note: the parameter <tt>stop</tt> is the <b>index</b> of the last
16 * position, <b>not</b> the length.
17 * <p>
18 * Note: the search term size <b>must</b> be smaller or equal the internal
19 * buffer size.
20 *
21 * @param search
22 * the term to search for
23 * @param buffer
24 * the buffer to look into
25 * @param start
26 * the offset at which to start the search
27 * @param stop
28 * the maximum index of the data to check (this is <b>not</b> a
29 * length, but an index)
30 *
31 * @return TRUE if the search content is present at the given location and
32 * does not exceed the <tt>len</tt> index
33 */
34 static public boolean startsWith(byte[] search, byte[] buffer, int start,
35 int stop) {
36
37 // Check if there even is enough space for it
38 if (search.length > (stop - start)) {
39 return false;
40 }
41
42 boolean same = true;
43 for (int i = 0; i < search.length; i++) {
44 if (search[i] != buffer[start + i]) {
45 same = false;
46 break;
47 }
48 }
49
50 return same;
51 }
52
53 /**
54 * Return the bytes array representation of the given {@link String} in
55 * UTF-8.
56 *
57 * @param str
58 * the {@link String} to transform into bytes
59 * @return the content in bytes
60 */
61 static public byte[] bytes(String str) {
62 try {
63 return str.getBytes("UTF-8");
64 } catch (UnsupportedEncodingException e) {
65 // All conforming JVM must support UTF-8
66 e.printStackTrace();
67 return null;
68 }
69 }
70
71 /**
72 * Return the bytes array representation of the given {@link String} in
73 * UTF-8.
74 *
75 * @param strs
76 * the {@link String}s to transform into bytes
77 * @return the content in bytes
78 */
79 static public byte[][] bytes(String[] strs) {
80 try {
81 byte[][] bytes = new byte[strs.length][];
82 for (int i = 0; i < strs.length; i++) {
83 bytes[i] = strs[i].getBytes("UTF-8");
84 }
85 return bytes;
86 } catch (UnsupportedEncodingException e) {
87 // All conforming JVM must support UTF-8
88 e.printStackTrace();
89 return null;
90 }
91 }
92 }