Skip to content

Instantly share code, notes, and snippets.

@captswag
Forked from JakeWharton/Truss.java
Last active April 30, 2021 16:13
Show Gist options
  • Save captswag/7a6f077c2a0eea52e047fa275aeb67ec to your computer and use it in GitHub Desktop.
Save captswag/7a6f077c2a0eea52e047fa275aeb67ec to your computer and use it in GitHub Desktop.
Rewrote Jake Wharton's wrapper of SpannableStringBuilder in Kotlin
import android.text.SpannableStringBuilder
import android.text.Spanned.SPAN_INCLUSIVE_EXCLUSIVE
import java.util.ArrayDeque
import java.util.Deque
// https://gist.github.com/JakeWharton/11274467
public class Truss {
private val builder: SpannableStringBuilder = SpannableStringBuilder()
private val stack: Deque<Span> = ArrayDeque()
fun append(string: String): Truss {
builder.append(string)
return this
}
fun append(charSequence: CharSequence): Truss {
builder.append(charSequence)
return this
}
fun append(char: Char): Truss {
builder.append(char)
return this
}
fun append(number: Int): Truss {
builder.append("$number")
return this
}
/** Starts {@code span} at the current position in the builder. */
fun pushSpan(span: Any): Truss {
stack.addLast(Span(builder.length, span))
return this
}
/** End the most recently pushed span at the current position in the builder. */
fun popSpan(): Truss {
val span = stack.removeLast()
builder.setSpan(span.span, span.start, builder.length, SPAN_INCLUSIVE_EXCLUSIVE)
return this
}
/** Create the final {@link CharSequence}, popping any remaining spans. */
fun build(): CharSequence {
while (!stack.isEmpty()) {
popSpan()
}
return builder
}
}
private data class Span(val start: Int, val span: Any)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment