1/*
2 * Copyright (C) 2011 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package benchmarks.regression;
18
19import com.google.caliper.Param;
20import java.util.Locale;
21import java.util.regex.Matcher;
22import java.util.regex.Pattern;
23
24public final class SchemePrefixBenchmark {
25
26    enum Strategy {
27        JAVA() {
28            @Override String execute(String spec) {
29                int colon = spec.indexOf(':');
30
31                if (colon < 1) {
32                    return null;
33                }
34
35                for (int i = 0; i < colon; i++) {
36                    char c = spec.charAt(i);
37                    if (!isValidSchemeChar(i, c)) {
38                        return null;
39                    }
40                }
41
42                return spec.substring(0, colon).toLowerCase(Locale.US);
43            }
44
45            private boolean isValidSchemeChar(int index, char c) {
46                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
47                    return true;
48                }
49                if (index > 0 && ((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')) {
50                    return true;
51                }
52                return false;
53            }
54        },
55
56        REGEX() {
57            private final Pattern pattern = Pattern.compile("^([a-zA-Z][a-zA-Z0-9+\\-.]*):");
58
59            @Override String execute(String spec) {
60                Matcher matcher = pattern.matcher(spec);
61                if (matcher.find()) {
62                    return matcher.group(1).toLowerCase(Locale.US);
63                } else {
64                    return null;
65                }
66            }
67        };
68
69
70        abstract String execute(String spec);
71    }
72
73    @Param Strategy strategy;
74
75    public void timeSchemePrefix(int reps) {
76        for (int i = 0; i < reps; i++) {
77            strategy.execute("http://android.com");
78        }
79    }
80}
81