001/* 002 * Copyright (C) 2009-2011 Mathias Doenitz 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.parboiled.matchers; 018 019import org.parboiled.MatcherContext; 020import org.parboiled.Rule; 021 022import static org.parboiled.common.Preconditions.checkArgNotNull; 023 024/** 025 * A {@link SequenceMatcher} specialization for sequences of CharMatchers. Performs fast string matching if the 026 * current context has it enabled. 027 */ 028public class StringMatcher extends SequenceMatcher { 029 public final char[] characters; 030 031 public StringMatcher(Rule[] charMatchers, char[] characters) { 032 super(checkArgNotNull(charMatchers, "charMatchers")); 033 this.characters = characters; 034 } 035 036 @Override 037 public String getLabel() { 038 return super.getLabel() != null ? super.getLabel() : '"' + String.valueOf(characters) + '"'; 039 } 040 041 @Override 042 public boolean hasCustomLabel() { 043 return true; 044 } 045 046 @Override 047 public boolean match(MatcherContext context) { 048 if (!context.fastStringMatching()) { 049 return super.match(context); 050 } 051 052 if (!context.getInputBuffer().test(context.getCurrentIndex(), characters)) return false; 053 context.advanceIndex(characters.length); 054 context.createNode(); 055 return true; 056 } 057}