Skip to content

Commit

Permalink
feat: optimize convertInSyntax's performance (#450)
Browse files Browse the repository at this point in the history
Optimise convertInSyntax method by compiling Pattern only once and creating StringBuffer only when needed.
  • Loading branch information
kdebski85 authored Feb 21, 2025
1 parent 747234b commit 677c106
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions src/main/java/org/casbin/jcasbin/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public class Util {
public static boolean enableLog = true;
private static Pattern evalReg = Pattern.compile("\\beval\\(([^),]*)\\)");

private static final Pattern IN_SYNTAX_PATTERN = Pattern.compile("([a-zA-Z0-9_.()\"]*) +in +([a-zA-Z0-9_.()\"]*)");

private static Pattern escapeAssertionRegex = Pattern.compile("\\b(r|p)[0-9]*\\.");

private static Logger LOGGER = LoggerFactory.getLogger("org.casbin.jcasbin");
Expand Down Expand Up @@ -144,16 +146,17 @@ public static String escapeAssertion(String s) {
* @return the 'include' expression.
*/
public static String convertInSyntax(String expString) {
String reg = "([a-zA-Z0-9_.()\"]*) +in +([a-zA-Z0-9_.()\"]*)";
Matcher m1 = Pattern.compile(reg).matcher(expString);
StringBuffer sb = new StringBuffer();
boolean flag = false;
while (m1.find()) {
flag = true;
m1.appendReplacement(sb, "include($2, $1)");
Matcher matcher = IN_SYNTAX_PATTERN.matcher(expString);
if (matcher.find()) {
StringBuffer sb = new StringBuffer();
do {
matcher.appendReplacement(sb, "include($2, $1)");
} while (matcher.find());
matcher.appendTail(sb);
return sb.toString();
}
m1.appendTail(sb);
return flag ? sb.toString() : expString;

return expString;
}

/**
Expand Down

0 comments on commit 677c106

Please sign in to comment.