Class IdGenerator

java.lang.Object
org.commonmark.ext.heading.anchor.IdGenerator

public class IdGenerator extends Object
Generates strings to be used as identifiers.

Use builder() to create an instance.

  • Field Details

    • allowedCharacters

      private final Pattern allowedCharacters
    • identityMap

      private final Map<String,Integer> identityMap
    • prefix

      private final String prefix
    • suffix

      private final String suffix
    • defaultIdentifier

      private String defaultIdentifier
  • Constructor Details

  • Method Details

    • builder

      public static IdGenerator.Builder builder()
      Returns:
      a new builder with default arguments
    • generateId

      public String generateId(String text)

      Generate an ID based on the provided text and previously generated IDs.

      This method is not thread safe, concurrent calls can end up with non-unique identifiers.

      Note that collision can occur in the case that

      • Method called with 'X'
      • Method called with 'X' again
      • Method called with 'X-1'

      In that case, the three generated IDs will be:

      • X
      • X-1
      • X-1

      Therefore if collisions are unacceptable you should ensure that numbers are stripped from end of text.

      Parameters:
      text - Text that the identifier should be based on. Will be normalised, then used to generate the identifier.
      Returns:
      text if this is the first instance that the text has been passed to the method. Otherwise, text + "-" + X will be returned, where X is the number of times that text has previously been passed in. If text is empty, the default identifier given in the constructor will be used.
    • compileAllowedCharactersPattern

      private static Pattern compileAllowedCharactersPattern()
    • normalizeText

      private String normalizeText(String text)
      Assume we've been given a space separated text.
      Parameters:
      text - Text to normalize to an ID