Skip to content

Commit df2ae4b

Browse files
committed
add toUsAsciiBytes to IString for best performance when converting into
byte array
1 parent 0c63e9c commit df2ae4b

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

net.lecousin.core/src/main/java/net/lecousin/framework/util/IString.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,19 @@ public interface IString extends CharSequence {
4444
/** Fill the given character array with the content of this string. */
4545
public default int fill(char[] chars) { return fill(chars, 0); }
4646

47+
/** Same as with char but with bytes, all characters are directly converted into bytes without CharsetEncoder. */
48+
public int fillUsAsciiBytes(byte[] bytes, int start);
49+
50+
/** Same as with char but with bytes, all characters are directly converted into bytes without CharsetEncoder. */
51+
public default int fillUsAsciiBytes(byte[] bytes) { return fillUsAsciiBytes(bytes, 0); }
52+
53+
/** Same as with char but with bytes, all characters are directly converted into bytes without CharsetEncoder. */
54+
public default byte[] toUsAsciiBytes() {
55+
byte[] bytes = new byte[length()];
56+
fillUsAsciiBytes(bytes, 0);
57+
return bytes;
58+
}
59+
4760
/** Remove spaces characters at the beginning of this string. */
4861
public IString trimBeginning();
4962

net.lecousin.core/src/main/java/net/lecousin/framework/util/UnprotectedString.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,14 @@ public int fill(char[] chars, int start) {
279279
return pos;
280280
}
281281

282+
@Override
283+
public int fillUsAsciiBytes(byte[] bytes, int start) {
284+
int pos = 0;
285+
for (int i = this.start; i <= this.end; ++i)
286+
bytes[start + (pos++)] = (byte)this.chars[i];
287+
return pos;
288+
}
289+
282290
@Override
283291
public List<UnprotectedString> split(char sep) {
284292
LinkedList<UnprotectedString> list = new LinkedList<>();

net.lecousin.core/src/main/java/net/lecousin/framework/util/UnprotectedStringBuffer.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,15 @@ public int fill(char[] chars, int start) {
373373
return pos;
374374
}
375375

376+
@Override
377+
public int fillUsAsciiBytes(byte[] bytes, int start) {
378+
if (strings == null) return 0;
379+
int pos = 0;
380+
for (int i = 0; i <= lastUsed; ++i)
381+
pos += strings[i].fillUsAsciiBytes(bytes, start + pos);
382+
return pos;
383+
}
384+
376385
@Override
377386
public UnprotectedStringBuffer trimBeginning() {
378387
if (strings != null)

0 commit comments

Comments
 (0)