[go: nahoru, domu]

Skip to content

Commit

Permalink
Add Regexp.hashCode and tests. (#79)
Browse files Browse the repository at this point in the history
Fixes warning about equals() being implemented without hashCode().
  • Loading branch information
sjamesr committed Oct 23, 2018
1 parent a7ce289 commit 205f0d2
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
30 changes: 30 additions & 0 deletions java/com/google/re2j/Regexp.java
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,36 @@ int maxCap() {
return m;
}

@Override
public int hashCode() {
int hashcode = op.hashCode();
switch (op) {
case END_TEXT:
hashcode += 31 * (flags & RE2.WAS_DOLLAR);
break;
case LITERAL:
case CHAR_CLASS:
hashcode += 31 * Arrays.hashCode(runes);
break;
case ALTERNATE:
case CONCAT:
hashcode += 31 * Arrays.deepHashCode(subs);
break;
case STAR:
case PLUS:
case QUEST:
hashcode += 31 * (flags & RE2.NON_GREEDY) + 31 * subs[0].hashCode();
break;
case REPEAT:
hashcode += 31 * min + 31 * max + 31 * subs[0].hashCode();
break;
case CAPTURE:
hashcode += 31 * cap + 31 * (name != null ? name.hashCode() : 0) + 31 * subs[0].hashCode();
break;
}
return hashcode;
}

// equals() returns true if this and that have identical structure.
@Override
public boolean equals(Object that) {
Expand Down
52 changes: 52 additions & 0 deletions javatests/com/google/re2j/RegexpHashcodeEqualsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.google.re2j;

import com.google.common.truth.Truth;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;

@RunWith(Parameterized.class)
public class RegexpHashcodeEqualsTest {
@Parameterized.Parameters
public static Iterable<Object[]> testCases() {
return Arrays.asList(
new Object[][] {
{"abc", "abc", true, RE2.POSIX},
{"abc", "def", false, RE2.POSIX},
{"(abc)", "(a)(b)(c)", false, RE2.POSIX},
{"a|$", "a|$", true, RE2.POSIX},
{"abc|def", "def|abc", false, RE2.POSIX},
{"a?", "b?", false, RE2.POSIX},
{"a?", "a?", true, RE2.POSIX},
{"a{1,3}", "a{1,3}", true, RE2.POSIX},
{"a{2,3}", "a{1,3}", false, RE2.POSIX},
{"^((?P<foo>what)a)$", "^((?P<foo>what)a)$", true, RE2.PERL},
{"^((?P<foo>what)a)$", "^((?P<bar>what)a)$", false, RE2.PERL},
});
}

@Parameterized.Parameter public String a;

@Parameterized.Parameter(1)
public String b;

@Parameterized.Parameter(2)
public boolean areEqual;

@Parameterized.Parameter(3)
public int mode;

@Test
public void testEquals() {
Regexp ra = Parser.parse(a, mode);
Regexp rb = Parser.parse(b, mode);
if (areEqual) {
Truth.assertThat(ra).isEqualTo(rb);
Truth.assertThat(ra.hashCode()).isEqualTo(rb.hashCode());
} else {
Truth.assertThat(ra).isNotEqualTo(rb);
}
}
}

0 comments on commit 205f0d2

Please sign in to comment.