Class LengthLimitedStringBuilder


  • @NotThreadSafe
    public class LengthLimitedStringBuilder
    extends Object
    A length limited string builder which dynamically or statically limits the capacity of the underlying StringBuilder implementation. Useful for preventing OOMs.

    Easy misconception is that it will always limit the number of chars to the length provided, which is not always true if increasing the capacity of the StringBuilder will cause it to become greater than the provided limit.

    e.g Limit is 20, current StringBuilder capacity is 16, current number of chars is 16. Appending 1 more char would not go over the limit. However, depending on StringBuilder implementation, it's capacity could be increased past the limit. Appending would stop here.

    Since:
    7.20
    • Constructor Detail

      • LengthLimitedStringBuilder

        public LengthLimitedStringBuilder​(LengthLimitedStringBuilder.LengthLimitProvider lengthLimitProvider)
        Creates a length limited string builder, which will silently stop appending if the limit is reached.
        Parameters:
        lengthLimitProvider - the provider of the length limit
    • Method Detail

      • setLength

        public void setLength​(int l)
      • length

        public int length()
      • limitReached

        protected boolean limitReached​(int length)
        Checks if appending length characters to the string builder will reach the limit.
        Parameters:
        length - of the characters to be appended
        Returns:
        true if the limit is reached, false otherwise
      • capacity

        public int capacity()
      • isLimitReached

        public boolean isLimitReached()