04a925d2b220942de912a203230807dffd31b098
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / string / tokenizer / Terminator.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2020, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.commons.string.tokenizer;
11
12 public class Terminator {
13
14     public final String startSequence;
15     public final String endSequence;
16     public final TerminationStrategy termination;
17
18     public Terminator(final String startSequence, TerminationStrategy termination) {
19         this.startSequence = startSequence;
20         this.endSequence = null;
21         this.termination = termination;
22     }
23
24     public Terminator(final String startSequence, final String endSequence, TerminationStrategy termination) {
25         this.startSequence = startSequence;
26         this.endSequence = endSequence;
27         this.termination = termination;
28     }
29
30     public boolean matches(String source, int index) {
31         // boundary check
32         if (source.length() < (index + startSequence.length()))
33             return false;
34
35         // match check
36         for (int i = 0; i < startSequence.length(); i++)
37             if (startSequence.charAt(i) != source.charAt(index + i))
38                 return false;
39
40         return true;
41     }
42
43     public boolean hasEndSequence() {
44         return endSequence != null;
45     }
46
47     @Override
48     public String toString() {
49         return "Terminator{" +
50                 "startSequence='" + startSequence + '\'' +
51                 ", endSequence='" + endSequence + '\'' +
52                 ", termination=" + termination +
53                 '}';
54     }
55
56     public enum TerminationStrategy {
57         PRESERVE,
58         DROP
59     }
60 }