Skip to content

Commit

Permalink
Added ANSI#length() and trim(len)
Browse files Browse the repository at this point in the history
  • Loading branch information
LatvianModder committed Oct 16, 2024
1 parent ac4a42d commit 8e26e39
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/main/java/dev/latvian/apps/ansi/ANSI.java
Original file line number Diff line number Diff line change
Expand Up @@ -524,4 +524,52 @@ public ANSI flatten() {

return new ANSI(result.toString(), style, false);
}

public int length() {
int len = content.length();

if (!children.isEmpty()) {
for (var child : children) {
len += child.length();
}
}

return len;
}

public ANSI trim(int toLength) {
return trim0(toLength).copy();
}

private ANSI trim0(int toLength) {
if (toLength <= 0) {
return EMPTY;
} else if (children.isEmpty()) {
if (toLength >= content.length()) {
return this;
} else {
return new ANSI(content.substring(0, toLength), style, false);
}
} else if (content.length() == toLength) {
return new ANSI(content, style, false);
} else if (content.length() > toLength) {
return new ANSI(content.substring(0, toLength), style, false);
} else {
var result = new ANSI(content, style, false);

for (var c : children) {
int len = c.length();

if (toLength - len >= 0) {
result.append(c);
toLength -= len;
} else {
result.append(c.trim0(toLength));
break;
}
}

return result;
}
}
}
16 changes: 16 additions & 0 deletions src/test/java/dev/latvian/apps/ansi/test/ANSITests.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,20 @@ public void object() {
Log.info(ansi.toUnformattedString());
Log.info(ansi.toDebugString());
}

@Test
public void trim() {
var ansi = ANSI.empty()
.foreground(218)
.background(0xFF3F2B45)
.append(" Text 1 ")
.append(ANSI.of(" Text 2 ").reverse())
.append(" Text 3 ");

ansi = ANSI.empty().append("<START>").append(ansi.trim(12)).append("<END>");

Log.info(ansi);
Log.info(ansi.toUnformattedString());
Log.info(ansi.toDebugString());
}
}

0 comments on commit 8e26e39

Please sign in to comment.