id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
21,800
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/Util.java
Util.makeConcreteClassAbstract
static SuggestedFix.Builder makeConcreteClassAbstract(ClassTree classTree, VisitorState state) { Set<Modifier> flags = EnumSet.noneOf(Modifier.class); flags.addAll(classTree.getModifiers().getFlags()); boolean wasFinal = flags.remove(FINAL); boolean wasAbstract = !flags.add(ABSTRACT); if (classTree.getKind().equals(INTERFACE) || (!wasFinal && wasAbstract)) { return SuggestedFix.builder(); // no-op } ImmutableList.Builder<Object> modifiers = ImmutableList.builder(); for (AnnotationTree annotation : classTree.getModifiers().getAnnotations()) { modifiers.add(state.getSourceForNode(annotation)); } modifiers.addAll(flags); SuggestedFix.Builder makeAbstract = SuggestedFix.builder(); if (((JCModifiers) classTree.getModifiers()).pos == -1) { makeAbstract.prefixWith(classTree, Joiner.on(' ').join(modifiers.build())); } else { makeAbstract.replace(classTree.getModifiers(), Joiner.on(' ').join(modifiers.build())); } if (wasFinal && HAS_GENERATED_CONSTRUCTOR.matches(classTree, state)) { makeAbstract.merge(addPrivateConstructor(classTree)); } return makeAbstract; }
java
static SuggestedFix.Builder makeConcreteClassAbstract(ClassTree classTree, VisitorState state) { Set<Modifier> flags = EnumSet.noneOf(Modifier.class); flags.addAll(classTree.getModifiers().getFlags()); boolean wasFinal = flags.remove(FINAL); boolean wasAbstract = !flags.add(ABSTRACT); if (classTree.getKind().equals(INTERFACE) || (!wasFinal && wasAbstract)) { return SuggestedFix.builder(); // no-op } ImmutableList.Builder<Object> modifiers = ImmutableList.builder(); for (AnnotationTree annotation : classTree.getModifiers().getAnnotations()) { modifiers.add(state.getSourceForNode(annotation)); } modifiers.addAll(flags); SuggestedFix.Builder makeAbstract = SuggestedFix.builder(); if (((JCModifiers) classTree.getModifiers()).pos == -1) { makeAbstract.prefixWith(classTree, Joiner.on(' ').join(modifiers.build())); } else { makeAbstract.replace(classTree.getModifiers(), Joiner.on(' ').join(modifiers.build())); } if (wasFinal && HAS_GENERATED_CONSTRUCTOR.matches(classTree, state)) { makeAbstract.merge(addPrivateConstructor(classTree)); } return makeAbstract; }
[ "static", "SuggestedFix", ".", "Builder", "makeConcreteClassAbstract", "(", "ClassTree", "classTree", ",", "VisitorState", "state", ")", "{", "Set", "<", "Modifier", ">", "flags", "=", "EnumSet", ".", "noneOf", "(", "Modifier", ".", "class", ")", ";", "flags", ".", "addAll", "(", "classTree", ".", "getModifiers", "(", ")", ".", "getFlags", "(", ")", ")", ";", "boolean", "wasFinal", "=", "flags", ".", "remove", "(", "FINAL", ")", ";", "boolean", "wasAbstract", "=", "!", "flags", ".", "add", "(", "ABSTRACT", ")", ";", "if", "(", "classTree", ".", "getKind", "(", ")", ".", "equals", "(", "INTERFACE", ")", "||", "(", "!", "wasFinal", "&&", "wasAbstract", ")", ")", "{", "return", "SuggestedFix", ".", "builder", "(", ")", ";", "// no-op", "}", "ImmutableList", ".", "Builder", "<", "Object", ">", "modifiers", "=", "ImmutableList", ".", "builder", "(", ")", ";", "for", "(", "AnnotationTree", "annotation", ":", "classTree", ".", "getModifiers", "(", ")", ".", "getAnnotations", "(", ")", ")", "{", "modifiers", ".", "add", "(", "state", ".", "getSourceForNode", "(", "annotation", ")", ")", ";", "}", "modifiers", ".", "addAll", "(", "flags", ")", ";", "SuggestedFix", ".", "Builder", "makeAbstract", "=", "SuggestedFix", ".", "builder", "(", ")", ";", "if", "(", "(", "(", "JCModifiers", ")", "classTree", ".", "getModifiers", "(", ")", ")", ".", "pos", "==", "-", "1", ")", "{", "makeAbstract", ".", "prefixWith", "(", "classTree", ",", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "modifiers", ".", "build", "(", ")", ")", ")", ";", "}", "else", "{", "makeAbstract", ".", "replace", "(", "classTree", ".", "getModifiers", "(", ")", ",", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "modifiers", ".", "build", "(", ")", ")", ")", ";", "}", "if", "(", "wasFinal", "&&", "HAS_GENERATED_CONSTRUCTOR", ".", "matches", "(", "classTree", ",", "state", ")", ")", "{", "makeAbstract", ".", "merge", "(", "addPrivateConstructor", "(", "classTree", ")", ")", ";", "}", "return", "makeAbstract", ";", "}" ]
Returns a fix that changes a concrete class to an abstract class. <ul> <li>Removes {@code final} if it was there. <li>Adds {@code abstract} if it wasn't there. <li>Adds a private empty constructor if the class was {@code final} and had only a default constructor. </ul>
[ "Returns", "a", "fix", "that", "changes", "a", "concrete", "class", "to", "an", "abstract", "class", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/Util.java#L164-L190
21,801
google/error-prone
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
SuggestedFixes.addModifiers
public static Optional<SuggestedFix> addModifiers( Tree tree, VisitorState state, Modifier... modifiers) { ModifiersTree originalModifiers = getModifiers(tree); if (originalModifiers == null) { return Optional.empty(); } return addModifiers(tree, originalModifiers, state, new TreeSet<>(Arrays.asList(modifiers))); }
java
public static Optional<SuggestedFix> addModifiers( Tree tree, VisitorState state, Modifier... modifiers) { ModifiersTree originalModifiers = getModifiers(tree); if (originalModifiers == null) { return Optional.empty(); } return addModifiers(tree, originalModifiers, state, new TreeSet<>(Arrays.asList(modifiers))); }
[ "public", "static", "Optional", "<", "SuggestedFix", ">", "addModifiers", "(", "Tree", "tree", ",", "VisitorState", "state", ",", "Modifier", "...", "modifiers", ")", "{", "ModifiersTree", "originalModifiers", "=", "getModifiers", "(", "tree", ")", ";", "if", "(", "originalModifiers", "==", "null", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "return", "addModifiers", "(", "tree", ",", "originalModifiers", ",", "state", ",", "new", "TreeSet", "<>", "(", "Arrays", ".", "asList", "(", "modifiers", ")", ")", ")", ";", "}" ]
Adds modifiers to the given class, method, or field declaration.
[ "Adds", "modifiers", "to", "the", "given", "class", "method", "or", "field", "declaration", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L157-L164
21,802
google/error-prone
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
SuggestedFixes.removeModifiers
public static Optional<SuggestedFix> removeModifiers( Tree tree, VisitorState state, Modifier... modifiers) { Set<Modifier> toRemove = ImmutableSet.copyOf(modifiers); ModifiersTree originalModifiers = getModifiers(tree); if (originalModifiers == null) { return Optional.empty(); } return removeModifiers(originalModifiers, state, toRemove); }
java
public static Optional<SuggestedFix> removeModifiers( Tree tree, VisitorState state, Modifier... modifiers) { Set<Modifier> toRemove = ImmutableSet.copyOf(modifiers); ModifiersTree originalModifiers = getModifiers(tree); if (originalModifiers == null) { return Optional.empty(); } return removeModifiers(originalModifiers, state, toRemove); }
[ "public", "static", "Optional", "<", "SuggestedFix", ">", "removeModifiers", "(", "Tree", "tree", ",", "VisitorState", "state", ",", "Modifier", "...", "modifiers", ")", "{", "Set", "<", "Modifier", ">", "toRemove", "=", "ImmutableSet", ".", "copyOf", "(", "modifiers", ")", ";", "ModifiersTree", "originalModifiers", "=", "getModifiers", "(", "tree", ")", ";", "if", "(", "originalModifiers", "==", "null", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "return", "removeModifiers", "(", "originalModifiers", ",", "state", ",", "toRemove", ")", ";", "}" ]
Remove modifiers from the given class, method, or field declaration.
[ "Remove", "modifiers", "from", "the", "given", "class", "method", "or", "field", "declaration", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L229-L237
21,803
google/error-prone
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
SuggestedFixes.qualifyType
public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, TypeMirror type) { return type.accept( new SimpleTypeVisitor8<String, SuggestedFix.Builder>() { @Override protected String defaultAction(TypeMirror e, Builder builder) { return e.toString(); } @Override public String visitArray(ArrayType t, Builder builder) { return t.getComponentType().accept(this, builder) + "[]"; } @Override public String visitDeclared(DeclaredType t, Builder builder) { String baseType = qualifyType(state, builder, ((Type) t).tsym); if (t.getTypeArguments().isEmpty()) { return baseType; } StringBuilder b = new StringBuilder(baseType); b.append('<'); boolean started = false; for (TypeMirror arg : t.getTypeArguments()) { if (started) { b.append(','); } b.append(arg.accept(this, builder)); started = true; } b.append('>'); return b.toString(); } }, fix); }
java
public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, TypeMirror type) { return type.accept( new SimpleTypeVisitor8<String, SuggestedFix.Builder>() { @Override protected String defaultAction(TypeMirror e, Builder builder) { return e.toString(); } @Override public String visitArray(ArrayType t, Builder builder) { return t.getComponentType().accept(this, builder) + "[]"; } @Override public String visitDeclared(DeclaredType t, Builder builder) { String baseType = qualifyType(state, builder, ((Type) t).tsym); if (t.getTypeArguments().isEmpty()) { return baseType; } StringBuilder b = new StringBuilder(baseType); b.append('<'); boolean started = false; for (TypeMirror arg : t.getTypeArguments()) { if (started) { b.append(','); } b.append(arg.accept(this, builder)); started = true; } b.append('>'); return b.toString(); } }, fix); }
[ "public", "static", "String", "qualifyType", "(", "VisitorState", "state", ",", "SuggestedFix", ".", "Builder", "fix", ",", "TypeMirror", "type", ")", "{", "return", "type", ".", "accept", "(", "new", "SimpleTypeVisitor8", "<", "String", ",", "SuggestedFix", ".", "Builder", ">", "(", ")", "{", "@", "Override", "protected", "String", "defaultAction", "(", "TypeMirror", "e", ",", "Builder", "builder", ")", "{", "return", "e", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "String", "visitArray", "(", "ArrayType", "t", ",", "Builder", "builder", ")", "{", "return", "t", ".", "getComponentType", "(", ")", ".", "accept", "(", "this", ",", "builder", ")", "+", "\"[]\"", ";", "}", "@", "Override", "public", "String", "visitDeclared", "(", "DeclaredType", "t", ",", "Builder", "builder", ")", "{", "String", "baseType", "=", "qualifyType", "(", "state", ",", "builder", ",", "(", "(", "Type", ")", "t", ")", ".", "tsym", ")", ";", "if", "(", "t", ".", "getTypeArguments", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "baseType", ";", "}", "StringBuilder", "b", "=", "new", "StringBuilder", "(", "baseType", ")", ";", "b", ".", "append", "(", "'", "'", ")", ";", "boolean", "started", "=", "false", ";", "for", "(", "TypeMirror", "arg", ":", "t", ".", "getTypeArguments", "(", ")", ")", "{", "if", "(", "started", ")", "{", "b", ".", "append", "(", "'", "'", ")", ";", "}", "b", ".", "append", "(", "arg", ".", "accept", "(", "this", ",", "builder", ")", ")", ";", "started", "=", "true", ";", "}", "b", ".", "append", "(", "'", "'", ")", ";", "return", "b", ".", "toString", "(", ")", ";", "}", "}", ",", "fix", ")", ";", "}" ]
Returns a human-friendly name of the given type for use in fixes.
[ "Returns", "a", "human", "-", "friendly", "name", "of", "the", "given", "type", "for", "use", "in", "fixes", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L295-L329
21,804
google/error-prone
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
SuggestedFixes.renameMethod
public static SuggestedFix renameMethod( MethodTree tree, final String replacement, VisitorState state) { // Search tokens from beginning of method tree to beginning of method body. int basePos = ((JCTree) tree).getStartPosition(); int endPos = tree.getBody() != null ? ((JCTree) tree.getBody()).getStartPosition() : state.getEndPosition(tree); List<ErrorProneToken> methodTokens = ErrorProneTokens.getTokens( state.getSourceCode().subSequence(basePos, endPos).toString(), state.context); for (ErrorProneToken token : methodTokens) { if (token.kind() == TokenKind.IDENTIFIER && token.name().equals(tree.getName())) { int nameStartPosition = basePos + token.pos(); int nameEndPosition = basePos + token.endPos(); return SuggestedFix.builder() .replace(nameStartPosition, nameEndPosition, replacement) .build(); } } // Method name not found. throw new AssertionError(); }
java
public static SuggestedFix renameMethod( MethodTree tree, final String replacement, VisitorState state) { // Search tokens from beginning of method tree to beginning of method body. int basePos = ((JCTree) tree).getStartPosition(); int endPos = tree.getBody() != null ? ((JCTree) tree.getBody()).getStartPosition() : state.getEndPosition(tree); List<ErrorProneToken> methodTokens = ErrorProneTokens.getTokens( state.getSourceCode().subSequence(basePos, endPos).toString(), state.context); for (ErrorProneToken token : methodTokens) { if (token.kind() == TokenKind.IDENTIFIER && token.name().equals(tree.getName())) { int nameStartPosition = basePos + token.pos(); int nameEndPosition = basePos + token.endPos(); return SuggestedFix.builder() .replace(nameStartPosition, nameEndPosition, replacement) .build(); } } // Method name not found. throw new AssertionError(); }
[ "public", "static", "SuggestedFix", "renameMethod", "(", "MethodTree", "tree", ",", "final", "String", "replacement", ",", "VisitorState", "state", ")", "{", "// Search tokens from beginning of method tree to beginning of method body.", "int", "basePos", "=", "(", "(", "JCTree", ")", "tree", ")", ".", "getStartPosition", "(", ")", ";", "int", "endPos", "=", "tree", ".", "getBody", "(", ")", "!=", "null", "?", "(", "(", "JCTree", ")", "tree", ".", "getBody", "(", ")", ")", ".", "getStartPosition", "(", ")", ":", "state", ".", "getEndPosition", "(", "tree", ")", ";", "List", "<", "ErrorProneToken", ">", "methodTokens", "=", "ErrorProneTokens", ".", "getTokens", "(", "state", ".", "getSourceCode", "(", ")", ".", "subSequence", "(", "basePos", ",", "endPos", ")", ".", "toString", "(", ")", ",", "state", ".", "context", ")", ";", "for", "(", "ErrorProneToken", "token", ":", "methodTokens", ")", "{", "if", "(", "token", ".", "kind", "(", ")", "==", "TokenKind", ".", "IDENTIFIER", "&&", "token", ".", "name", "(", ")", ".", "equals", "(", "tree", ".", "getName", "(", ")", ")", ")", "{", "int", "nameStartPosition", "=", "basePos", "+", "token", ".", "pos", "(", ")", ";", "int", "nameEndPosition", "=", "basePos", "+", "token", ".", "endPos", "(", ")", ";", "return", "SuggestedFix", ".", "builder", "(", ")", ".", "replace", "(", "nameStartPosition", ",", "nameEndPosition", ",", "replacement", ")", ".", "build", "(", ")", ";", "}", "}", "// Method name not found.", "throw", "new", "AssertionError", "(", ")", ";", "}" ]
Be warned, only changes method name at the declaration.
[ "Be", "warned", "only", "changes", "method", "name", "at", "the", "declaration", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L466-L488
21,805
google/error-prone
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
SuggestedFixes.deleteExceptions
public static Fix deleteExceptions( MethodTree tree, final VisitorState state, List<ExpressionTree> toDelete) { List<? extends ExpressionTree> trees = tree.getThrows(); if (toDelete.size() == trees.size()) { return SuggestedFix.replace( getThrowsPosition(tree, state) - 1, state.getEndPosition(getLast(trees)), ""); } String replacement = FluentIterable.from(tree.getThrows()) .filter(Predicates.not(Predicates.in(toDelete))) .transform( new Function<ExpressionTree, String>() { @Override @Nullable public String apply(ExpressionTree input) { return state.getSourceForNode(input); } }) .join(Joiner.on(", ")); return SuggestedFix.replace( ((JCTree) tree.getThrows().get(0)).getStartPosition(), state.getEndPosition(getLast(tree.getThrows())), replacement); }
java
public static Fix deleteExceptions( MethodTree tree, final VisitorState state, List<ExpressionTree> toDelete) { List<? extends ExpressionTree> trees = tree.getThrows(); if (toDelete.size() == trees.size()) { return SuggestedFix.replace( getThrowsPosition(tree, state) - 1, state.getEndPosition(getLast(trees)), ""); } String replacement = FluentIterable.from(tree.getThrows()) .filter(Predicates.not(Predicates.in(toDelete))) .transform( new Function<ExpressionTree, String>() { @Override @Nullable public String apply(ExpressionTree input) { return state.getSourceForNode(input); } }) .join(Joiner.on(", ")); return SuggestedFix.replace( ((JCTree) tree.getThrows().get(0)).getStartPosition(), state.getEndPosition(getLast(tree.getThrows())), replacement); }
[ "public", "static", "Fix", "deleteExceptions", "(", "MethodTree", "tree", ",", "final", "VisitorState", "state", ",", "List", "<", "ExpressionTree", ">", "toDelete", ")", "{", "List", "<", "?", "extends", "ExpressionTree", ">", "trees", "=", "tree", ".", "getThrows", "(", ")", ";", "if", "(", "toDelete", ".", "size", "(", ")", "==", "trees", ".", "size", "(", ")", ")", "{", "return", "SuggestedFix", ".", "replace", "(", "getThrowsPosition", "(", "tree", ",", "state", ")", "-", "1", ",", "state", ".", "getEndPosition", "(", "getLast", "(", "trees", ")", ")", ",", "\"\"", ")", ";", "}", "String", "replacement", "=", "FluentIterable", ".", "from", "(", "tree", ".", "getThrows", "(", ")", ")", ".", "filter", "(", "Predicates", ".", "not", "(", "Predicates", ".", "in", "(", "toDelete", ")", ")", ")", ".", "transform", "(", "new", "Function", "<", "ExpressionTree", ",", "String", ">", "(", ")", "{", "@", "Override", "@", "Nullable", "public", "String", "apply", "(", "ExpressionTree", "input", ")", "{", "return", "state", ".", "getSourceForNode", "(", "input", ")", ";", "}", "}", ")", ".", "join", "(", "Joiner", ".", "on", "(", "\", \"", ")", ")", ";", "return", "SuggestedFix", ".", "replace", "(", "(", "(", "JCTree", ")", "tree", ".", "getThrows", "(", ")", ".", "get", "(", "0", ")", ")", ".", "getStartPosition", "(", ")", ",", "state", ".", "getEndPosition", "(", "getLast", "(", "tree", ".", "getThrows", "(", ")", ")", ")", ",", "replacement", ")", ";", "}" ]
Deletes the given exceptions from a method's throws clause.
[ "Deletes", "the", "given", "exceptions", "from", "a", "method", "s", "throws", "clause", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L509-L532
21,806
google/error-prone
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
SuggestedFixes.compilesWithFix
public static boolean compilesWithFix(Fix fix, VisitorState state) { if (fix.isEmpty()) { return true; } JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); JavaFileObject modifiedFile = compilationUnit.getSourceFile(); BasicJavacTask javacTask = (BasicJavacTask) state.context.get(JavacTask.class); if (javacTask == null) { throw new IllegalArgumentException("No JavacTask in context."); } Arguments arguments = Arguments.instance(javacTask.getContext()); List<JavaFileObject> fileObjects = new ArrayList<>(arguments.getFileObjects()); for (int i = 0; i < fileObjects.size(); i++) { final JavaFileObject oldFile = fileObjects.get(i); if (modifiedFile.toUri().equals(oldFile.toUri())) { DescriptionBasedDiff diff = DescriptionBasedDiff.create(compilationUnit, ImportOrganizer.STATIC_FIRST_ORGANIZER); diff.handleFix(fix); SourceFile fixSource; try { fixSource = new SourceFile( modifiedFile.getName(), modifiedFile.getCharContent(false /*ignoreEncodingErrors*/)); } catch (IOException e) { return false; } diff.applyDifferences(fixSource); fileObjects.set( i, new SimpleJavaFileObject(sourceURI(modifiedFile.toUri()), Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return fixSource.getAsSequence(); } }); break; } } DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<>(); Context context = new Context(); Options options = Options.instance(context); Options originalOptions = Options.instance(javacTask.getContext()); for (String key : originalOptions.keySet()) { String value = originalOptions.get(key); if (key.equals("-Xplugin:") && value.startsWith("ErrorProne")) { // When using the -Xplugin Error Prone integration, disable Error Prone for speculative // recompiles to avoid infinite recurison. continue; } options.put(key, value); } JavacTask newTask = JavacTool.create() .getTask( CharStreams.nullWriter(), state.context.get(JavaFileManager.class), diagnosticListener, ImmutableList.of(), arguments.getClassNames(), fileObjects, context); try { newTask.analyze(); } catch (IOException e) { throw new UncheckedIOException(e); } return countErrors(diagnosticListener) == 0; }
java
public static boolean compilesWithFix(Fix fix, VisitorState state) { if (fix.isEmpty()) { return true; } JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); JavaFileObject modifiedFile = compilationUnit.getSourceFile(); BasicJavacTask javacTask = (BasicJavacTask) state.context.get(JavacTask.class); if (javacTask == null) { throw new IllegalArgumentException("No JavacTask in context."); } Arguments arguments = Arguments.instance(javacTask.getContext()); List<JavaFileObject> fileObjects = new ArrayList<>(arguments.getFileObjects()); for (int i = 0; i < fileObjects.size(); i++) { final JavaFileObject oldFile = fileObjects.get(i); if (modifiedFile.toUri().equals(oldFile.toUri())) { DescriptionBasedDiff diff = DescriptionBasedDiff.create(compilationUnit, ImportOrganizer.STATIC_FIRST_ORGANIZER); diff.handleFix(fix); SourceFile fixSource; try { fixSource = new SourceFile( modifiedFile.getName(), modifiedFile.getCharContent(false /*ignoreEncodingErrors*/)); } catch (IOException e) { return false; } diff.applyDifferences(fixSource); fileObjects.set( i, new SimpleJavaFileObject(sourceURI(modifiedFile.toUri()), Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return fixSource.getAsSequence(); } }); break; } } DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<>(); Context context = new Context(); Options options = Options.instance(context); Options originalOptions = Options.instance(javacTask.getContext()); for (String key : originalOptions.keySet()) { String value = originalOptions.get(key); if (key.equals("-Xplugin:") && value.startsWith("ErrorProne")) { // When using the -Xplugin Error Prone integration, disable Error Prone for speculative // recompiles to avoid infinite recurison. continue; } options.put(key, value); } JavacTask newTask = JavacTool.create() .getTask( CharStreams.nullWriter(), state.context.get(JavaFileManager.class), diagnosticListener, ImmutableList.of(), arguments.getClassNames(), fileObjects, context); try { newTask.analyze(); } catch (IOException e) { throw new UncheckedIOException(e); } return countErrors(diagnosticListener) == 0; }
[ "public", "static", "boolean", "compilesWithFix", "(", "Fix", "fix", ",", "VisitorState", "state", ")", "{", "if", "(", "fix", ".", "isEmpty", "(", ")", ")", "{", "return", "true", ";", "}", "JCCompilationUnit", "compilationUnit", "=", "(", "JCCompilationUnit", ")", "state", ".", "getPath", "(", ")", ".", "getCompilationUnit", "(", ")", ";", "JavaFileObject", "modifiedFile", "=", "compilationUnit", ".", "getSourceFile", "(", ")", ";", "BasicJavacTask", "javacTask", "=", "(", "BasicJavacTask", ")", "state", ".", "context", ".", "get", "(", "JavacTask", ".", "class", ")", ";", "if", "(", "javacTask", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No JavacTask in context.\"", ")", ";", "}", "Arguments", "arguments", "=", "Arguments", ".", "instance", "(", "javacTask", ".", "getContext", "(", ")", ")", ";", "List", "<", "JavaFileObject", ">", "fileObjects", "=", "new", "ArrayList", "<>", "(", "arguments", ".", "getFileObjects", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fileObjects", ".", "size", "(", ")", ";", "i", "++", ")", "{", "final", "JavaFileObject", "oldFile", "=", "fileObjects", ".", "get", "(", "i", ")", ";", "if", "(", "modifiedFile", ".", "toUri", "(", ")", ".", "equals", "(", "oldFile", ".", "toUri", "(", ")", ")", ")", "{", "DescriptionBasedDiff", "diff", "=", "DescriptionBasedDiff", ".", "create", "(", "compilationUnit", ",", "ImportOrganizer", ".", "STATIC_FIRST_ORGANIZER", ")", ";", "diff", ".", "handleFix", "(", "fix", ")", ";", "SourceFile", "fixSource", ";", "try", "{", "fixSource", "=", "new", "SourceFile", "(", "modifiedFile", ".", "getName", "(", ")", ",", "modifiedFile", ".", "getCharContent", "(", "false", "/*ignoreEncodingErrors*/", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "false", ";", "}", "diff", ".", "applyDifferences", "(", "fixSource", ")", ";", "fileObjects", ".", "set", "(", "i", ",", "new", "SimpleJavaFileObject", "(", "sourceURI", "(", "modifiedFile", ".", "toUri", "(", ")", ")", ",", "Kind", ".", "SOURCE", ")", "{", "@", "Override", "public", "CharSequence", "getCharContent", "(", "boolean", "ignoreEncodingErrors", ")", "throws", "IOException", "{", "return", "fixSource", ".", "getAsSequence", "(", ")", ";", "}", "}", ")", ";", "break", ";", "}", "}", "DiagnosticCollector", "<", "JavaFileObject", ">", "diagnosticListener", "=", "new", "DiagnosticCollector", "<>", "(", ")", ";", "Context", "context", "=", "new", "Context", "(", ")", ";", "Options", "options", "=", "Options", ".", "instance", "(", "context", ")", ";", "Options", "originalOptions", "=", "Options", ".", "instance", "(", "javacTask", ".", "getContext", "(", ")", ")", ";", "for", "(", "String", "key", ":", "originalOptions", ".", "keySet", "(", ")", ")", "{", "String", "value", "=", "originalOptions", ".", "get", "(", "key", ")", ";", "if", "(", "key", ".", "equals", "(", "\"-Xplugin:\"", ")", "&&", "value", ".", "startsWith", "(", "\"ErrorProne\"", ")", ")", "{", "// When using the -Xplugin Error Prone integration, disable Error Prone for speculative", "// recompiles to avoid infinite recurison.", "continue", ";", "}", "options", ".", "put", "(", "key", ",", "value", ")", ";", "}", "JavacTask", "newTask", "=", "JavacTool", ".", "create", "(", ")", ".", "getTask", "(", "CharStreams", ".", "nullWriter", "(", ")", ",", "state", ".", "context", ".", "get", "(", "JavaFileManager", ".", "class", ")", ",", "diagnosticListener", ",", "ImmutableList", ".", "of", "(", ")", ",", "arguments", ".", "getClassNames", "(", ")", ",", "fileObjects", ",", "context", ")", ";", "try", "{", "newTask", ".", "analyze", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "UncheckedIOException", "(", "e", ")", ";", "}", "return", "countErrors", "(", "diagnosticListener", ")", "==", "0", ";", "}" ]
Returns true if the current compilation would succeed with the given fix applied. Note that calling this method is very expensive as it requires rerunning the entire compile, so it should be used with restraint.
[ "Returns", "true", "if", "the", "current", "compilation", "would", "succeed", "with", "the", "given", "fix", "applied", ".", "Note", "that", "calling", "this", "method", "is", "very", "expensive", "as", "it", "requires", "rerunning", "the", "entire", "compile", "so", "it", "should", "be", "used", "with", "restraint", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L773-L841
21,807
google/error-prone
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
SuggestedFixes.suggestWhitelistAnnotation
public static Optional<SuggestedFix> suggestWhitelistAnnotation( String whitelistAnnotation, TreePath where, VisitorState state) { // TODO(bangert): Support annotations that do not have @Target(CLASS). if (whitelistAnnotation.equals("com.google.errorprone.annotations.DontSuggestFixes")) { return Optional.empty(); } SuggestedFix.Builder builder = SuggestedFix.builder(); Type whitelistAnnotationType = state.getTypeFromString(whitelistAnnotation); ImmutableSet<Tree.Kind> supportedWhitelistLocationKinds; String annotationName; if (whitelistAnnotationType != null) { supportedWhitelistLocationKinds = supportedTreeTypes(whitelistAnnotationType.asElement()); annotationName = qualifyType(state, builder, whitelistAnnotationType); } else { // If we can't resolve the type, fall back to an approximation. int idx = whitelistAnnotation.lastIndexOf('.'); Verify.verify(idx > 0 && idx + 1 < whitelistAnnotation.length()); supportedWhitelistLocationKinds = TREE_TYPE_UNKNOWN_ANNOTATION; annotationName = whitelistAnnotation.substring(idx + 1); builder.addImport(whitelistAnnotation); } Optional<Tree> whitelistLocation = StreamSupport.stream(where.spliterator(), false) .filter(tree -> supportedWhitelistLocationKinds.contains(tree.getKind())) .filter(Predicates.not(SuggestedFixes::isAnonymousClassTree)) .findFirst(); return whitelistLocation.map( location -> builder.prefixWith(location, "@" + annotationName + " ").build()); }
java
public static Optional<SuggestedFix> suggestWhitelistAnnotation( String whitelistAnnotation, TreePath where, VisitorState state) { // TODO(bangert): Support annotations that do not have @Target(CLASS). if (whitelistAnnotation.equals("com.google.errorprone.annotations.DontSuggestFixes")) { return Optional.empty(); } SuggestedFix.Builder builder = SuggestedFix.builder(); Type whitelistAnnotationType = state.getTypeFromString(whitelistAnnotation); ImmutableSet<Tree.Kind> supportedWhitelistLocationKinds; String annotationName; if (whitelistAnnotationType != null) { supportedWhitelistLocationKinds = supportedTreeTypes(whitelistAnnotationType.asElement()); annotationName = qualifyType(state, builder, whitelistAnnotationType); } else { // If we can't resolve the type, fall back to an approximation. int idx = whitelistAnnotation.lastIndexOf('.'); Verify.verify(idx > 0 && idx + 1 < whitelistAnnotation.length()); supportedWhitelistLocationKinds = TREE_TYPE_UNKNOWN_ANNOTATION; annotationName = whitelistAnnotation.substring(idx + 1); builder.addImport(whitelistAnnotation); } Optional<Tree> whitelistLocation = StreamSupport.stream(where.spliterator(), false) .filter(tree -> supportedWhitelistLocationKinds.contains(tree.getKind())) .filter(Predicates.not(SuggestedFixes::isAnonymousClassTree)) .findFirst(); return whitelistLocation.map( location -> builder.prefixWith(location, "@" + annotationName + " ").build()); }
[ "public", "static", "Optional", "<", "SuggestedFix", ">", "suggestWhitelistAnnotation", "(", "String", "whitelistAnnotation", ",", "TreePath", "where", ",", "VisitorState", "state", ")", "{", "// TODO(bangert): Support annotations that do not have @Target(CLASS).", "if", "(", "whitelistAnnotation", ".", "equals", "(", "\"com.google.errorprone.annotations.DontSuggestFixes\"", ")", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "SuggestedFix", ".", "Builder", "builder", "=", "SuggestedFix", ".", "builder", "(", ")", ";", "Type", "whitelistAnnotationType", "=", "state", ".", "getTypeFromString", "(", "whitelistAnnotation", ")", ";", "ImmutableSet", "<", "Tree", ".", "Kind", ">", "supportedWhitelistLocationKinds", ";", "String", "annotationName", ";", "if", "(", "whitelistAnnotationType", "!=", "null", ")", "{", "supportedWhitelistLocationKinds", "=", "supportedTreeTypes", "(", "whitelistAnnotationType", ".", "asElement", "(", ")", ")", ";", "annotationName", "=", "qualifyType", "(", "state", ",", "builder", ",", "whitelistAnnotationType", ")", ";", "}", "else", "{", "// If we can't resolve the type, fall back to an approximation.", "int", "idx", "=", "whitelistAnnotation", ".", "lastIndexOf", "(", "'", "'", ")", ";", "Verify", ".", "verify", "(", "idx", ">", "0", "&&", "idx", "+", "1", "<", "whitelistAnnotation", ".", "length", "(", ")", ")", ";", "supportedWhitelistLocationKinds", "=", "TREE_TYPE_UNKNOWN_ANNOTATION", ";", "annotationName", "=", "whitelistAnnotation", ".", "substring", "(", "idx", "+", "1", ")", ";", "builder", ".", "addImport", "(", "whitelistAnnotation", ")", ";", "}", "Optional", "<", "Tree", ">", "whitelistLocation", "=", "StreamSupport", ".", "stream", "(", "where", ".", "spliterator", "(", ")", ",", "false", ")", ".", "filter", "(", "tree", "->", "supportedWhitelistLocationKinds", ".", "contains", "(", "tree", ".", "getKind", "(", ")", ")", ")", ".", "filter", "(", "Predicates", ".", "not", "(", "SuggestedFixes", "::", "isAnonymousClassTree", ")", ")", ".", "findFirst", "(", ")", ";", "return", "whitelistLocation", ".", "map", "(", "location", "->", "builder", ".", "prefixWith", "(", "location", ",", "\"@\"", "+", "annotationName", "+", "\" \"", ")", ".", "build", "(", ")", ")", ";", "}" ]
Create a fix to add a suppression annotation on the surrounding class. <p>No suggested fix is produced if the suppression annotation cannot be used on classes, i.e. the annotation has a {@code @Target} but does not include {@code @Target(TYPE)}. <p>If the suggested annotation is {@code DontSuggestFixes}, return empty.
[ "Create", "a", "fix", "to", "add", "a", "suppression", "annotation", "on", "the", "surrounding", "class", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L926-L956
21,808
google/error-prone
check_api/src/main/java/com/google/errorprone/SuppressionInfo.java
SuppressionInfo.suppressedState
public SuppressedState suppressedState( Suppressible suppressible, boolean suppressedInGeneratedCode) { if (inGeneratedCode && suppressedInGeneratedCode) { return SuppressedState.SUPPRESSED; } if (suppressible.supportsSuppressWarnings() && !Collections.disjoint(suppressible.allNames(), suppressWarningsStrings)) { return SuppressedState.SUPPRESSED; } if (!Collections.disjoint(suppressible.customSuppressionAnnotations(), customSuppressions)) { return SuppressedState.SUPPRESSED; } return SuppressedState.UNSUPPRESSED; }
java
public SuppressedState suppressedState( Suppressible suppressible, boolean suppressedInGeneratedCode) { if (inGeneratedCode && suppressedInGeneratedCode) { return SuppressedState.SUPPRESSED; } if (suppressible.supportsSuppressWarnings() && !Collections.disjoint(suppressible.allNames(), suppressWarningsStrings)) { return SuppressedState.SUPPRESSED; } if (!Collections.disjoint(suppressible.customSuppressionAnnotations(), customSuppressions)) { return SuppressedState.SUPPRESSED; } return SuppressedState.UNSUPPRESSED; }
[ "public", "SuppressedState", "suppressedState", "(", "Suppressible", "suppressible", ",", "boolean", "suppressedInGeneratedCode", ")", "{", "if", "(", "inGeneratedCode", "&&", "suppressedInGeneratedCode", ")", "{", "return", "SuppressedState", ".", "SUPPRESSED", ";", "}", "if", "(", "suppressible", ".", "supportsSuppressWarnings", "(", ")", "&&", "!", "Collections", ".", "disjoint", "(", "suppressible", ".", "allNames", "(", ")", ",", "suppressWarningsStrings", ")", ")", "{", "return", "SuppressedState", ".", "SUPPRESSED", ";", "}", "if", "(", "!", "Collections", ".", "disjoint", "(", "suppressible", ".", "customSuppressionAnnotations", "(", ")", ",", "customSuppressions", ")", ")", "{", "return", "SuppressedState", ".", "SUPPRESSED", ";", "}", "return", "SuppressedState", ".", "UNSUPPRESSED", ";", "}" ]
Returns true if this checker should be considered suppressed given the signals present in this object. @param suppressible Holds information about the suppressibilty of a checker @param suppressedInGeneratedCode true if this checker instance should be considered suppressed if the signals in this object say we're in generated code.
[ "Returns", "true", "if", "this", "checker", "should", "be", "considered", "suppressed", "given", "the", "signals", "present", "in", "this", "object", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/SuppressionInfo.java#L86-L100
21,809
google/error-prone
check_api/src/main/java/com/google/errorprone/predicates/TypePredicates.java
TypePredicates.isExactTypeAny
public static TypePredicate isExactTypeAny(Iterable<String> types) { return new ExactAny(Iterables.transform(types, GET_TYPE)); }
java
public static TypePredicate isExactTypeAny(Iterable<String> types) { return new ExactAny(Iterables.transform(types, GET_TYPE)); }
[ "public", "static", "TypePredicate", "isExactTypeAny", "(", "Iterable", "<", "String", ">", "types", ")", "{", "return", "new", "ExactAny", "(", "Iterables", ".", "transform", "(", "types", ",", "GET_TYPE", ")", ")", ";", "}" ]
Match types that are exactly equal to any of the given types.
[ "Match", "types", "that", "are", "exactly", "equal", "to", "any", "of", "the", "given", "types", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/predicates/TypePredicates.java#L63-L65
21,810
google/error-prone
check_api/src/main/java/com/google/errorprone/predicates/TypePredicates.java
TypePredicates.isDescendantOfAny
public static TypePredicate isDescendantOfAny(Iterable<String> types) { return new DescendantOfAny(Iterables.transform(types, GET_TYPE)); }
java
public static TypePredicate isDescendantOfAny(Iterable<String> types) { return new DescendantOfAny(Iterables.transform(types, GET_TYPE)); }
[ "public", "static", "TypePredicate", "isDescendantOfAny", "(", "Iterable", "<", "String", ">", "types", ")", "{", "return", "new", "DescendantOfAny", "(", "Iterables", ".", "transform", "(", "types", ",", "GET_TYPE", ")", ")", ";", "}" ]
Match types that are a sub-type of one of the given types.
[ "Match", "types", "that", "are", "a", "sub", "-", "type", "of", "one", "of", "the", "given", "types", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/predicates/TypePredicates.java#L73-L75
21,811
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/SelfAssignment.java
SelfAssignment.stripNullCheck
private static ExpressionTree stripNullCheck(ExpressionTree expression, VisitorState state) { if (expression != null && expression.getKind() == METHOD_INVOCATION) { MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; if (NON_NULL_MATCHER.matches(methodInvocation, state)) { return methodInvocation.getArguments().get(0); } } return expression; }
java
private static ExpressionTree stripNullCheck(ExpressionTree expression, VisitorState state) { if (expression != null && expression.getKind() == METHOD_INVOCATION) { MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; if (NON_NULL_MATCHER.matches(methodInvocation, state)) { return methodInvocation.getArguments().get(0); } } return expression; }
[ "private", "static", "ExpressionTree", "stripNullCheck", "(", "ExpressionTree", "expression", ",", "VisitorState", "state", ")", "{", "if", "(", "expression", "!=", "null", "&&", "expression", ".", "getKind", "(", ")", "==", "METHOD_INVOCATION", ")", "{", "MethodInvocationTree", "methodInvocation", "=", "(", "MethodInvocationTree", ")", "expression", ";", "if", "(", "NON_NULL_MATCHER", ".", "matches", "(", "methodInvocation", ",", "state", ")", ")", "{", "return", "methodInvocation", ".", "getArguments", "(", ")", ".", "get", "(", "0", ")", ";", "}", "}", "return", "expression", ";", "}" ]
If the given expression is a call to a method checking the nullity of its first parameter, and otherwise returns that parameter.
[ "If", "the", "given", "expression", "is", "a", "call", "to", "a", "method", "checking", "the", "nullity", "of", "its", "first", "parameter", "and", "otherwise", "returns", "that", "parameter", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/SelfAssignment.java#L130-L138
21,812
google/error-prone
check_api/src/main/java/com/google/errorprone/apply/SourceFile.java
SourceFile.getLines
public List<String> getLines() { try { return CharSource.wrap(sourceBuilder).readLines(); } catch (IOException e) { throw new AssertionError("IOException not possible, as the string is in-memory"); } }
java
public List<String> getLines() { try { return CharSource.wrap(sourceBuilder).readLines(); } catch (IOException e) { throw new AssertionError("IOException not possible, as the string is in-memory"); } }
[ "public", "List", "<", "String", ">", "getLines", "(", ")", "{", "try", "{", "return", "CharSource", ".", "wrap", "(", "sourceBuilder", ")", ".", "readLines", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "AssertionError", "(", "\"IOException not possible, as the string is in-memory\"", ")", ";", "}", "}" ]
Returns a copy of code as a list of lines.
[ "Returns", "a", "copy", "of", "code", "as", "a", "list", "of", "lines", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/apply/SourceFile.java#L58-L64
21,813
google/error-prone
check_api/src/main/java/com/google/errorprone/apply/SourceFile.java
SourceFile.replaceLines
public void replaceLines(List<String> lines) { sourceBuilder.replace(0, sourceBuilder.length(), Joiner.on("\n").join(lines) + "\n"); }
java
public void replaceLines(List<String> lines) { sourceBuilder.replace(0, sourceBuilder.length(), Joiner.on("\n").join(lines) + "\n"); }
[ "public", "void", "replaceLines", "(", "List", "<", "String", ">", "lines", ")", "{", "sourceBuilder", ".", "replace", "(", "0", ",", "sourceBuilder", ".", "length", "(", ")", ",", "Joiner", ".", "on", "(", "\"\\n\"", ")", ".", "join", "(", "lines", ")", "+", "\"\\n\"", ")", ";", "}" ]
Replace the source code with the new lines of code.
[ "Replace", "the", "source", "code", "with", "the", "new", "lines", "of", "code", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/apply/SourceFile.java#L122-L124
21,814
google/error-prone
check_api/src/main/java/com/google/errorprone/apply/SourceFile.java
SourceFile.replaceLines
public void replaceLines(int startLine, int endLine, List<String> replacementLines) { Preconditions.checkArgument(startLine <= endLine); List<String> originalLines = getLines(); List<String> newLines = new ArrayList<>(); for (int i = 0; i < originalLines.size(); i++) { int lineNum = i + 1; if (lineNum == startLine) { newLines.addAll(replacementLines); } else if (lineNum > startLine && lineNum <= endLine) { // Skip } else { newLines.add(originalLines.get(i)); } } replaceLines(newLines); }
java
public void replaceLines(int startLine, int endLine, List<String> replacementLines) { Preconditions.checkArgument(startLine <= endLine); List<String> originalLines = getLines(); List<String> newLines = new ArrayList<>(); for (int i = 0; i < originalLines.size(); i++) { int lineNum = i + 1; if (lineNum == startLine) { newLines.addAll(replacementLines); } else if (lineNum > startLine && lineNum <= endLine) { // Skip } else { newLines.add(originalLines.get(i)); } } replaceLines(newLines); }
[ "public", "void", "replaceLines", "(", "int", "startLine", ",", "int", "endLine", ",", "List", "<", "String", ">", "replacementLines", ")", "{", "Preconditions", ".", "checkArgument", "(", "startLine", "<=", "endLine", ")", ";", "List", "<", "String", ">", "originalLines", "=", "getLines", "(", ")", ";", "List", "<", "String", ">", "newLines", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "originalLines", ".", "size", "(", ")", ";", "i", "++", ")", "{", "int", "lineNum", "=", "i", "+", "1", ";", "if", "(", "lineNum", "==", "startLine", ")", "{", "newLines", ".", "addAll", "(", "replacementLines", ")", ";", "}", "else", "if", "(", "lineNum", ">", "startLine", "&&", "lineNum", "<=", "endLine", ")", "{", "// Skip", "}", "else", "{", "newLines", ".", "add", "(", "originalLines", ".", "get", "(", "i", ")", ")", ";", "}", "}", "replaceLines", "(", "newLines", ")", ";", "}" ]
Replace the source code between the start and end lines with some new lines of code.
[ "Replace", "the", "source", "code", "between", "the", "start", "and", "end", "lines", "with", "some", "new", "lines", "of", "code", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/apply/SourceFile.java#L127-L142
21,815
google/error-prone
check_api/src/main/java/com/google/errorprone/apply/SourceFile.java
SourceFile.replaceChars
public void replaceChars(int startPosition, int endPosition, String replacement) { try { sourceBuilder.replace(startPosition, endPosition, replacement); } catch (StringIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException( String.format( "Replacement cannot be made. Source file %s has length %d, requested start " + "position %d, requested end position %d, replacement %s", path, sourceBuilder.length(), startPosition, endPosition, replacement)); } }
java
public void replaceChars(int startPosition, int endPosition, String replacement) { try { sourceBuilder.replace(startPosition, endPosition, replacement); } catch (StringIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException( String.format( "Replacement cannot be made. Source file %s has length %d, requested start " + "position %d, requested end position %d, replacement %s", path, sourceBuilder.length(), startPosition, endPosition, replacement)); } }
[ "public", "void", "replaceChars", "(", "int", "startPosition", ",", "int", "endPosition", ",", "String", "replacement", ")", "{", "try", "{", "sourceBuilder", ".", "replace", "(", "startPosition", ",", "endPosition", ",", "replacement", ")", ";", "}", "catch", "(", "StringIndexOutOfBoundsException", "e", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "String", ".", "format", "(", "\"Replacement cannot be made. Source file %s has length %d, requested start \"", "+", "\"position %d, requested end position %d, replacement %s\"", ",", "path", ",", "sourceBuilder", ".", "length", "(", ")", ",", "startPosition", ",", "endPosition", ",", "replacement", ")", ")", ";", "}", "}" ]
Replace the source code between the start and end character positions with a new string. <p>This method uses the same conventions as {@link String#substring(int, int)} for its start and end parameters.
[ "Replace", "the", "source", "code", "between", "the", "start", "and", "end", "character", "positions", "with", "a", "new", "string", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/apply/SourceFile.java#L150-L160
21,816
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Parameter.java
Parameter.isAssignableTo
boolean isAssignableTo(Parameter target, VisitorState state) { if (state.getTypes().isSameType(type(), Type.noType) || state.getTypes().isSameType(target.type(), Type.noType)) { return false; } try { return state.getTypes().isAssignable(type(), target.type()); } catch (CompletionFailure e) { // Report completion errors to avoid e.g. https://github.com/bazelbuild/bazel/issues/4105 Check.instance(state.context) .completionError((DiagnosticPosition) state.getPath().getLeaf(), e); return false; } }
java
boolean isAssignableTo(Parameter target, VisitorState state) { if (state.getTypes().isSameType(type(), Type.noType) || state.getTypes().isSameType(target.type(), Type.noType)) { return false; } try { return state.getTypes().isAssignable(type(), target.type()); } catch (CompletionFailure e) { // Report completion errors to avoid e.g. https://github.com/bazelbuild/bazel/issues/4105 Check.instance(state.context) .completionError((DiagnosticPosition) state.getPath().getLeaf(), e); return false; } }
[ "boolean", "isAssignableTo", "(", "Parameter", "target", ",", "VisitorState", "state", ")", "{", "if", "(", "state", ".", "getTypes", "(", ")", ".", "isSameType", "(", "type", "(", ")", ",", "Type", ".", "noType", ")", "||", "state", ".", "getTypes", "(", ")", ".", "isSameType", "(", "target", ".", "type", "(", ")", ",", "Type", ".", "noType", ")", ")", "{", "return", "false", ";", "}", "try", "{", "return", "state", ".", "getTypes", "(", ")", ".", "isAssignable", "(", "type", "(", ")", ",", "target", ".", "type", "(", ")", ")", ";", "}", "catch", "(", "CompletionFailure", "e", ")", "{", "// Report completion errors to avoid e.g. https://github.com/bazelbuild/bazel/issues/4105", "Check", ".", "instance", "(", "state", ".", "context", ")", ".", "completionError", "(", "(", "DiagnosticPosition", ")", "state", ".", "getPath", "(", ")", ".", "getLeaf", "(", ")", ",", "e", ")", ";", "return", "false", ";", "}", "}" ]
Return true if this parameter is assignable to the target parameter. This will consider subclassing, autoboxing and null.
[ "Return", "true", "if", "this", "parameter", "is", "assignable", "to", "the", "target", "parameter", ".", "This", "will", "consider", "subclassing", "autoboxing", "and", "null", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Parameter.java#L115-L128
21,817
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Parameter.java
Parameter.getArgumentName
@VisibleForTesting static String getArgumentName(ExpressionTree expressionTree) { switch (expressionTree.getKind()) { case MEMBER_SELECT: return ((MemberSelectTree) expressionTree).getIdentifier().toString(); case NULL_LITERAL: // null could match anything pretty well return NAME_NULL; case IDENTIFIER: IdentifierTree idTree = (IdentifierTree) expressionTree; if (idTree.getName().contentEquals("this")) { // for the 'this' keyword the argument name is the name of the object's class Symbol sym = ASTHelpers.getSymbol(idTree); return sym != null ? getClassName(ASTHelpers.enclosingClass(sym)) : NAME_NOT_PRESENT; } else { // if we have a variable, just extract its name return idTree.getName().toString(); } case METHOD_INVOCATION: MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expressionTree; MethodSymbol methodSym = ASTHelpers.getSymbol(methodInvocationTree); if (methodSym != null) { String name = methodSym.getSimpleName().toString(); List<String> terms = NamingConventions.splitToLowercaseTerms(name); String firstTerm = Iterables.getFirst(terms, null); if (METHODNAME_PREFIXES_TO_REMOVE.contains(firstTerm)) { if (terms.size() == 1) { ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree); if (receiver == null) { return getClassName(ASTHelpers.enclosingClass(methodSym)); } // recursively try to get a name from the receiver return getArgumentName(receiver); } else { return name.substring(firstTerm.length()); } } else { return name; } } else { return NAME_NOT_PRESENT; } case NEW_CLASS: MethodSymbol constructorSym = ASTHelpers.getSymbol((NewClassTree) expressionTree); return constructorSym != null && constructorSym.owner != null ? getClassName((ClassSymbol) constructorSym.owner) : NAME_NOT_PRESENT; default: return NAME_NOT_PRESENT; } }
java
@VisibleForTesting static String getArgumentName(ExpressionTree expressionTree) { switch (expressionTree.getKind()) { case MEMBER_SELECT: return ((MemberSelectTree) expressionTree).getIdentifier().toString(); case NULL_LITERAL: // null could match anything pretty well return NAME_NULL; case IDENTIFIER: IdentifierTree idTree = (IdentifierTree) expressionTree; if (idTree.getName().contentEquals("this")) { // for the 'this' keyword the argument name is the name of the object's class Symbol sym = ASTHelpers.getSymbol(idTree); return sym != null ? getClassName(ASTHelpers.enclosingClass(sym)) : NAME_NOT_PRESENT; } else { // if we have a variable, just extract its name return idTree.getName().toString(); } case METHOD_INVOCATION: MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expressionTree; MethodSymbol methodSym = ASTHelpers.getSymbol(methodInvocationTree); if (methodSym != null) { String name = methodSym.getSimpleName().toString(); List<String> terms = NamingConventions.splitToLowercaseTerms(name); String firstTerm = Iterables.getFirst(terms, null); if (METHODNAME_PREFIXES_TO_REMOVE.contains(firstTerm)) { if (terms.size() == 1) { ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree); if (receiver == null) { return getClassName(ASTHelpers.enclosingClass(methodSym)); } // recursively try to get a name from the receiver return getArgumentName(receiver); } else { return name.substring(firstTerm.length()); } } else { return name; } } else { return NAME_NOT_PRESENT; } case NEW_CLASS: MethodSymbol constructorSym = ASTHelpers.getSymbol((NewClassTree) expressionTree); return constructorSym != null && constructorSym.owner != null ? getClassName((ClassSymbol) constructorSym.owner) : NAME_NOT_PRESENT; default: return NAME_NOT_PRESENT; } }
[ "@", "VisibleForTesting", "static", "String", "getArgumentName", "(", "ExpressionTree", "expressionTree", ")", "{", "switch", "(", "expressionTree", ".", "getKind", "(", ")", ")", "{", "case", "MEMBER_SELECT", ":", "return", "(", "(", "MemberSelectTree", ")", "expressionTree", ")", ".", "getIdentifier", "(", ")", ".", "toString", "(", ")", ";", "case", "NULL_LITERAL", ":", "// null could match anything pretty well", "return", "NAME_NULL", ";", "case", "IDENTIFIER", ":", "IdentifierTree", "idTree", "=", "(", "IdentifierTree", ")", "expressionTree", ";", "if", "(", "idTree", ".", "getName", "(", ")", ".", "contentEquals", "(", "\"this\"", ")", ")", "{", "// for the 'this' keyword the argument name is the name of the object's class", "Symbol", "sym", "=", "ASTHelpers", ".", "getSymbol", "(", "idTree", ")", ";", "return", "sym", "!=", "null", "?", "getClassName", "(", "ASTHelpers", ".", "enclosingClass", "(", "sym", ")", ")", ":", "NAME_NOT_PRESENT", ";", "}", "else", "{", "// if we have a variable, just extract its name", "return", "idTree", ".", "getName", "(", ")", ".", "toString", "(", ")", ";", "}", "case", "METHOD_INVOCATION", ":", "MethodInvocationTree", "methodInvocationTree", "=", "(", "MethodInvocationTree", ")", "expressionTree", ";", "MethodSymbol", "methodSym", "=", "ASTHelpers", ".", "getSymbol", "(", "methodInvocationTree", ")", ";", "if", "(", "methodSym", "!=", "null", ")", "{", "String", "name", "=", "methodSym", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ";", "List", "<", "String", ">", "terms", "=", "NamingConventions", ".", "splitToLowercaseTerms", "(", "name", ")", ";", "String", "firstTerm", "=", "Iterables", ".", "getFirst", "(", "terms", ",", "null", ")", ";", "if", "(", "METHODNAME_PREFIXES_TO_REMOVE", ".", "contains", "(", "firstTerm", ")", ")", "{", "if", "(", "terms", ".", "size", "(", ")", "==", "1", ")", "{", "ExpressionTree", "receiver", "=", "ASTHelpers", ".", "getReceiver", "(", "methodInvocationTree", ")", ";", "if", "(", "receiver", "==", "null", ")", "{", "return", "getClassName", "(", "ASTHelpers", ".", "enclosingClass", "(", "methodSym", ")", ")", ";", "}", "// recursively try to get a name from the receiver", "return", "getArgumentName", "(", "receiver", ")", ";", "}", "else", "{", "return", "name", ".", "substring", "(", "firstTerm", ".", "length", "(", ")", ")", ";", "}", "}", "else", "{", "return", "name", ";", "}", "}", "else", "{", "return", "NAME_NOT_PRESENT", ";", "}", "case", "NEW_CLASS", ":", "MethodSymbol", "constructorSym", "=", "ASTHelpers", ".", "getSymbol", "(", "(", "NewClassTree", ")", "expressionTree", ")", ";", "return", "constructorSym", "!=", "null", "&&", "constructorSym", ".", "owner", "!=", "null", "?", "getClassName", "(", "(", "ClassSymbol", ")", "constructorSym", ".", "owner", ")", ":", "NAME_NOT_PRESENT", ";", "default", ":", "return", "NAME_NOT_PRESENT", ";", "}", "}" ]
Extract the name from an argument. <p> <ul> <li>IdentifierTree - if the identifier is 'this' then use the name of the enclosing class, otherwise use the name of the identifier <li>MemberSelectTree - the name of its identifier <li>NewClassTree - the name of the class being constructed <li>Null literal - a wildcard name <li>MethodInvocationTree - use the method name stripping off 'get', 'set', 'is' prefix. If this results in an empty name then recursively search the receiver </ul> All other trees (including literals other than Null literal) do not have a name and this method will return the marker for an unknown name.
[ "Extract", "the", "name", "from", "an", "argument", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/Parameter.java#L164-L214
21,818
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/MockitoUsage.java
MockitoUsage.buildFix
private void buildFix( Description.Builder builder, MethodInvocationTree tree, VisitorState state) { MethodInvocationTree mockitoCall = tree; List<? extends ExpressionTree> args = mockitoCall.getArguments(); Tree mock = mockitoCall.getArguments().get(0); boolean isVerify = ASTHelpers.getSymbol(tree).getSimpleName().contentEquals("verify"); if (isVerify && mock.getKind() == Kind.METHOD_INVOCATION) { MethodInvocationTree invocation = (MethodInvocationTree) mock; String verify = state.getSourceForNode(mockitoCall.getMethodSelect()); String receiver = state.getSourceForNode(ASTHelpers.getReceiver(invocation)); String mode = args.size() > 1 ? ", " + state.getSourceForNode(args.get(1)) : ""; String call = state.getSourceForNode(invocation).substring(receiver.length()); builder.addFix( SuggestedFix.replace(tree, String.format("%s(%s%s)%s", verify, receiver, mode, call))); } if (isVerify && args.size() > 1 && NEVER_METHOD.matches(args.get(1), state)) { // TODO(cushon): handle times(0) the same as never() builder.addFix( SuggestedFix.builder() .addStaticImport("org.mockito.Mockito.verifyZeroInteractions") .replace(tree, String.format("verifyZeroInteractions(%s)", mock)) .build()); } // Always suggest the naive semantics-preserving option, which is just to // delete the assertion: Tree parent = state.getPath().getParentPath().getLeaf(); if (parent.getKind() == Kind.EXPRESSION_STATEMENT) { // delete entire expression statement builder.addFix(SuggestedFix.delete(parent)); } else { builder.addFix(SuggestedFix.delete(tree)); } }
java
private void buildFix( Description.Builder builder, MethodInvocationTree tree, VisitorState state) { MethodInvocationTree mockitoCall = tree; List<? extends ExpressionTree> args = mockitoCall.getArguments(); Tree mock = mockitoCall.getArguments().get(0); boolean isVerify = ASTHelpers.getSymbol(tree).getSimpleName().contentEquals("verify"); if (isVerify && mock.getKind() == Kind.METHOD_INVOCATION) { MethodInvocationTree invocation = (MethodInvocationTree) mock; String verify = state.getSourceForNode(mockitoCall.getMethodSelect()); String receiver = state.getSourceForNode(ASTHelpers.getReceiver(invocation)); String mode = args.size() > 1 ? ", " + state.getSourceForNode(args.get(1)) : ""; String call = state.getSourceForNode(invocation).substring(receiver.length()); builder.addFix( SuggestedFix.replace(tree, String.format("%s(%s%s)%s", verify, receiver, mode, call))); } if (isVerify && args.size() > 1 && NEVER_METHOD.matches(args.get(1), state)) { // TODO(cushon): handle times(0) the same as never() builder.addFix( SuggestedFix.builder() .addStaticImport("org.mockito.Mockito.verifyZeroInteractions") .replace(tree, String.format("verifyZeroInteractions(%s)", mock)) .build()); } // Always suggest the naive semantics-preserving option, which is just to // delete the assertion: Tree parent = state.getPath().getParentPath().getLeaf(); if (parent.getKind() == Kind.EXPRESSION_STATEMENT) { // delete entire expression statement builder.addFix(SuggestedFix.delete(parent)); } else { builder.addFix(SuggestedFix.delete(tree)); } }
[ "private", "void", "buildFix", "(", "Description", ".", "Builder", "builder", ",", "MethodInvocationTree", "tree", ",", "VisitorState", "state", ")", "{", "MethodInvocationTree", "mockitoCall", "=", "tree", ";", "List", "<", "?", "extends", "ExpressionTree", ">", "args", "=", "mockitoCall", ".", "getArguments", "(", ")", ";", "Tree", "mock", "=", "mockitoCall", ".", "getArguments", "(", ")", ".", "get", "(", "0", ")", ";", "boolean", "isVerify", "=", "ASTHelpers", ".", "getSymbol", "(", "tree", ")", ".", "getSimpleName", "(", ")", ".", "contentEquals", "(", "\"verify\"", ")", ";", "if", "(", "isVerify", "&&", "mock", ".", "getKind", "(", ")", "==", "Kind", ".", "METHOD_INVOCATION", ")", "{", "MethodInvocationTree", "invocation", "=", "(", "MethodInvocationTree", ")", "mock", ";", "String", "verify", "=", "state", ".", "getSourceForNode", "(", "mockitoCall", ".", "getMethodSelect", "(", ")", ")", ";", "String", "receiver", "=", "state", ".", "getSourceForNode", "(", "ASTHelpers", ".", "getReceiver", "(", "invocation", ")", ")", ";", "String", "mode", "=", "args", ".", "size", "(", ")", ">", "1", "?", "\", \"", "+", "state", ".", "getSourceForNode", "(", "args", ".", "get", "(", "1", ")", ")", ":", "\"\"", ";", "String", "call", "=", "state", ".", "getSourceForNode", "(", "invocation", ")", ".", "substring", "(", "receiver", ".", "length", "(", ")", ")", ";", "builder", ".", "addFix", "(", "SuggestedFix", ".", "replace", "(", "tree", ",", "String", ".", "format", "(", "\"%s(%s%s)%s\"", ",", "verify", ",", "receiver", ",", "mode", ",", "call", ")", ")", ")", ";", "}", "if", "(", "isVerify", "&&", "args", ".", "size", "(", ")", ">", "1", "&&", "NEVER_METHOD", ".", "matches", "(", "args", ".", "get", "(", "1", ")", ",", "state", ")", ")", "{", "// TODO(cushon): handle times(0) the same as never()", "builder", ".", "addFix", "(", "SuggestedFix", ".", "builder", "(", ")", ".", "addStaticImport", "(", "\"org.mockito.Mockito.verifyZeroInteractions\"", ")", ".", "replace", "(", "tree", ",", "String", ".", "format", "(", "\"verifyZeroInteractions(%s)\"", ",", "mock", ")", ")", ".", "build", "(", ")", ")", ";", "}", "// Always suggest the naive semantics-preserving option, which is just to", "// delete the assertion:", "Tree", "parent", "=", "state", ".", "getPath", "(", ")", ".", "getParentPath", "(", ")", ".", "getLeaf", "(", ")", ";", "if", "(", "parent", ".", "getKind", "(", ")", "==", "Kind", ".", "EXPRESSION_STATEMENT", ")", "{", "// delete entire expression statement", "builder", ".", "addFix", "(", "SuggestedFix", ".", "delete", "(", "parent", ")", ")", ";", "}", "else", "{", "builder", ".", "addFix", "(", "SuggestedFix", ".", "delete", "(", "tree", ")", ")", ";", "}", "}" ]
Create fixes for invalid assertions. <ul> <li>Rewrite `verify(mock.bar())` to `verify(mock).bar()` <li>Rewrite `verify(mock.bar(), times(N))` to `verify(mock, times(N)).bar()` <li>Rewrite `verify(mock, never())` to `verifyZeroInteractions(mock)` <li>Finally, offer to delete the mock statement. </ul>
[ "Create", "fixes", "for", "invalid", "assertions", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/MockitoUsage.java#L82-L114
21,819
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectedConstructorAnnotations.java
InjectedConstructorAnnotations.matchMethod
@Override public Description matchMethod(MethodTree methodTree, VisitorState state) { SuggestedFix.Builder fix = null; if (isInjectedConstructor(methodTree, state)) { for (AnnotationTree annotationTree : methodTree.getModifiers().getAnnotations()) { if (OPTIONAL_INJECTION_MATCHER.matches(annotationTree, state)) { // Replace the annotation with "@Inject" if (fix == null) { fix = SuggestedFix.builder(); } fix = fix.replace(annotationTree, "@Inject"); } else if (BINDING_ANNOTATION_MATCHER.matches(annotationTree, state)) { // Remove the binding annotation if (fix == null) { fix = SuggestedFix.builder(); } fix = fix.delete(annotationTree); } } } if (fix == null) { return Description.NO_MATCH; } else { return describeMatch(methodTree, fix.build()); } }
java
@Override public Description matchMethod(MethodTree methodTree, VisitorState state) { SuggestedFix.Builder fix = null; if (isInjectedConstructor(methodTree, state)) { for (AnnotationTree annotationTree : methodTree.getModifiers().getAnnotations()) { if (OPTIONAL_INJECTION_MATCHER.matches(annotationTree, state)) { // Replace the annotation with "@Inject" if (fix == null) { fix = SuggestedFix.builder(); } fix = fix.replace(annotationTree, "@Inject"); } else if (BINDING_ANNOTATION_MATCHER.matches(annotationTree, state)) { // Remove the binding annotation if (fix == null) { fix = SuggestedFix.builder(); } fix = fix.delete(annotationTree); } } } if (fix == null) { return Description.NO_MATCH; } else { return describeMatch(methodTree, fix.build()); } }
[ "@", "Override", "public", "Description", "matchMethod", "(", "MethodTree", "methodTree", ",", "VisitorState", "state", ")", "{", "SuggestedFix", ".", "Builder", "fix", "=", "null", ";", "if", "(", "isInjectedConstructor", "(", "methodTree", ",", "state", ")", ")", "{", "for", "(", "AnnotationTree", "annotationTree", ":", "methodTree", ".", "getModifiers", "(", ")", ".", "getAnnotations", "(", ")", ")", "{", "if", "(", "OPTIONAL_INJECTION_MATCHER", ".", "matches", "(", "annotationTree", ",", "state", ")", ")", "{", "// Replace the annotation with \"@Inject\"", "if", "(", "fix", "==", "null", ")", "{", "fix", "=", "SuggestedFix", ".", "builder", "(", ")", ";", "}", "fix", "=", "fix", ".", "replace", "(", "annotationTree", ",", "\"@Inject\"", ")", ";", "}", "else", "if", "(", "BINDING_ANNOTATION_MATCHER", ".", "matches", "(", "annotationTree", ",", "state", ")", ")", "{", "// Remove the binding annotation", "if", "(", "fix", "==", "null", ")", "{", "fix", "=", "SuggestedFix", ".", "builder", "(", ")", ";", "}", "fix", "=", "fix", ".", "delete", "(", "annotationTree", ")", ";", "}", "}", "}", "if", "(", "fix", "==", "null", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "else", "{", "return", "describeMatch", "(", "methodTree", ",", "fix", ".", "build", "(", ")", ")", ";", "}", "}" ]
Matches injected constructors annotated with @Inject(optional=true) or binding annotations. Suggests fixes to remove the argument {@code optional=true} or binding annotations.
[ "Matches", "injected", "constructors", "annotated", "with" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectedConstructorAnnotations.java#L68-L93
21,820
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterShadowing.java
TypeParameterShadowing.typeVariablesEnclosing
private static List<TypeVariableSymbol> typeVariablesEnclosing(Symbol sym) { List<TypeVariableSymbol> typeVarScopes = new ArrayList<>(); outer: while (!sym.isStatic()) { sym = sym.owner; switch (sym.getKind()) { case PACKAGE: break outer; case METHOD: case CLASS: typeVarScopes.addAll(sym.getTypeParameters()); break; default: // fall out } } return typeVarScopes; }
java
private static List<TypeVariableSymbol> typeVariablesEnclosing(Symbol sym) { List<TypeVariableSymbol> typeVarScopes = new ArrayList<>(); outer: while (!sym.isStatic()) { sym = sym.owner; switch (sym.getKind()) { case PACKAGE: break outer; case METHOD: case CLASS: typeVarScopes.addAll(sym.getTypeParameters()); break; default: // fall out } } return typeVarScopes; }
[ "private", "static", "List", "<", "TypeVariableSymbol", ">", "typeVariablesEnclosing", "(", "Symbol", "sym", ")", "{", "List", "<", "TypeVariableSymbol", ">", "typeVarScopes", "=", "new", "ArrayList", "<>", "(", ")", ";", "outer", ":", "while", "(", "!", "sym", ".", "isStatic", "(", ")", ")", "{", "sym", "=", "sym", ".", "owner", ";", "switch", "(", "sym", ".", "getKind", "(", ")", ")", "{", "case", "PACKAGE", ":", "break", "outer", ";", "case", "METHOD", ":", "case", "CLASS", ":", "typeVarScopes", ".", "addAll", "(", "sym", ".", "getTypeParameters", "(", ")", ")", ";", "break", ";", "default", ":", "// fall out", "}", "}", "return", "typeVarScopes", ";", "}" ]
Get list of type params of every enclosing class
[ "Get", "list", "of", "type", "params", "of", "every", "enclosing", "class" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/TypeParameterShadowing.java#L237-L253
21,821
google/error-prone
core/src/main/java/com/google/errorprone/refaster/Template.java
Template.actualTypes
protected List<Type> actualTypes(Inliner inliner) { ArrayList<Type> result = new ArrayList<>(); ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList(); for (int i = 0; i < expressionArgumentTypes().size(); i++) { String argName = argNames.get(i); Optional<JCExpression> singleBinding = inliner.getOptionalBinding(new UFreeIdent.Key(argName)); if (singleBinding.isPresent()) { result.add(singleBinding.get().type); } else { Optional<java.util.List<JCExpression>> exprs = inliner.getOptionalBinding(new URepeated.Key(argName)); if (exprs.isPresent() && !exprs.get().isEmpty()) { Type[] exprTys = new Type[exprs.get().size()]; for (int j = 0; j < exprs.get().size(); j++) { exprTys[j] = exprs.get().get(j).type; } // Get the least upper bound of the types of all expressions that the argument matches. // In the special case where exprs is empty, returns the "bottom" type, which is a // subtype of everything. result.add(inliner.types().lub(List.from(exprTys))); } } } for (PlaceholderExpressionKey key : Ordering.natural() .immutableSortedCopy( Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) { result.add(inliner.getBinding(key).type); } return List.from(result); }
java
protected List<Type> actualTypes(Inliner inliner) { ArrayList<Type> result = new ArrayList<>(); ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList(); for (int i = 0; i < expressionArgumentTypes().size(); i++) { String argName = argNames.get(i); Optional<JCExpression> singleBinding = inliner.getOptionalBinding(new UFreeIdent.Key(argName)); if (singleBinding.isPresent()) { result.add(singleBinding.get().type); } else { Optional<java.util.List<JCExpression>> exprs = inliner.getOptionalBinding(new URepeated.Key(argName)); if (exprs.isPresent() && !exprs.get().isEmpty()) { Type[] exprTys = new Type[exprs.get().size()]; for (int j = 0; j < exprs.get().size(); j++) { exprTys[j] = exprs.get().get(j).type; } // Get the least upper bound of the types of all expressions that the argument matches. // In the special case where exprs is empty, returns the "bottom" type, which is a // subtype of everything. result.add(inliner.types().lub(List.from(exprTys))); } } } for (PlaceholderExpressionKey key : Ordering.natural() .immutableSortedCopy( Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) { result.add(inliner.getBinding(key).type); } return List.from(result); }
[ "protected", "List", "<", "Type", ">", "actualTypes", "(", "Inliner", "inliner", ")", "{", "ArrayList", "<", "Type", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "ImmutableList", "<", "String", ">", "argNames", "=", "expressionArgumentTypes", "(", ")", ".", "keySet", "(", ")", ".", "asList", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "expressionArgumentTypes", "(", ")", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "argName", "=", "argNames", ".", "get", "(", "i", ")", ";", "Optional", "<", "JCExpression", ">", "singleBinding", "=", "inliner", ".", "getOptionalBinding", "(", "new", "UFreeIdent", ".", "Key", "(", "argName", ")", ")", ";", "if", "(", "singleBinding", ".", "isPresent", "(", ")", ")", "{", "result", ".", "add", "(", "singleBinding", ".", "get", "(", ")", ".", "type", ")", ";", "}", "else", "{", "Optional", "<", "java", ".", "util", ".", "List", "<", "JCExpression", ">>", "exprs", "=", "inliner", ".", "getOptionalBinding", "(", "new", "URepeated", ".", "Key", "(", "argName", ")", ")", ";", "if", "(", "exprs", ".", "isPresent", "(", ")", "&&", "!", "exprs", ".", "get", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "Type", "[", "]", "exprTys", "=", "new", "Type", "[", "exprs", ".", "get", "(", ")", ".", "size", "(", ")", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "exprs", ".", "get", "(", ")", ".", "size", "(", ")", ";", "j", "++", ")", "{", "exprTys", "[", "j", "]", "=", "exprs", ".", "get", "(", ")", ".", "get", "(", "j", ")", ".", "type", ";", "}", "// Get the least upper bound of the types of all expressions that the argument matches.", "// In the special case where exprs is empty, returns the \"bottom\" type, which is a", "// subtype of everything.", "result", ".", "add", "(", "inliner", ".", "types", "(", ")", ".", "lub", "(", "List", ".", "from", "(", "exprTys", ")", ")", ")", ";", "}", "}", "}", "for", "(", "PlaceholderExpressionKey", "key", ":", "Ordering", ".", "natural", "(", ")", ".", "immutableSortedCopy", "(", "Iterables", ".", "filter", "(", "inliner", ".", "bindings", ".", "keySet", "(", ")", ",", "PlaceholderExpressionKey", ".", "class", ")", ")", ")", "{", "result", ".", "add", "(", "inliner", ".", "getBinding", "(", "key", ")", ".", "type", ")", ";", "}", "return", "List", ".", "from", "(", "result", ")", ";", "}" ]
Returns a list of the actual types to be matched. This consists of the types of the expressions bound to the @BeforeTemplate method parameters, concatenated with the types of the expressions bound to expression placeholders, sorted by the name of the placeholder method.
[ "Returns", "a", "list", "of", "the", "actual", "types", "to", "be", "matched", ".", "This", "consists", "of", "the", "types", "of", "the", "expressions", "bound", "to", "the" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/Template.java#L152-L183
21,822
google/error-prone
core/src/main/java/com/google/errorprone/refaster/Template.java
Template.infer
private Type infer( Warner warner, Inliner inliner, List<Type> freeTypeVariables, List<Type> expectedArgTypes, Type returnType, List<Type> actualArgTypes) throws InferException { Symtab symtab = inliner.symtab(); Type methodType = new MethodType(expectedArgTypes, returnType, List.<Type>nil(), symtab.methodClass); if (!freeTypeVariables.isEmpty()) { methodType = new ForAll(freeTypeVariables, methodType); } Enter enter = inliner.enter(); MethodSymbol methodSymbol = new MethodSymbol(0, inliner.asName("__m__"), methodType, symtab.unknownSymbol); Type site = symtab.methodClass.type; Env<AttrContext> env = enter.getTopLevelEnv(TreeMaker.instance(inliner.getContext()).TopLevel(List.<JCTree>nil())); // Set up the resolution phase: try { Field field = AttrContext.class.getDeclaredField("pendingResolutionPhase"); field.setAccessible(true); field.set(env.info, newMethodResolutionPhase(autoboxing())); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } Object resultInfo; try { Class<?> resultInfoClass = Class.forName("com.sun.tools.javac.comp.Attr$ResultInfo"); Constructor<?> resultInfoCtor = resultInfoClass.getDeclaredConstructor(Attr.class, KindSelector.class, Type.class); resultInfoCtor.setAccessible(true); resultInfo = resultInfoCtor.newInstance( Attr.instance(inliner.getContext()), KindSelector.PCK, Type.noType); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } // Type inference sometimes produces diagnostics, so we need to catch them to avoid interfering // with the enclosing compilation. Log.DeferredDiagnosticHandler handler = new Log.DeferredDiagnosticHandler(Log.instance(inliner.getContext())); try { MethodType result = callCheckMethod(warner, inliner, resultInfo, actualArgTypes, methodSymbol, site, env); if (!handler.getDiagnostics().isEmpty()) { throw new InferException(handler.getDiagnostics()); } return result; } finally { Log.instance(inliner.getContext()).popDiagnosticHandler(handler); } }
java
private Type infer( Warner warner, Inliner inliner, List<Type> freeTypeVariables, List<Type> expectedArgTypes, Type returnType, List<Type> actualArgTypes) throws InferException { Symtab symtab = inliner.symtab(); Type methodType = new MethodType(expectedArgTypes, returnType, List.<Type>nil(), symtab.methodClass); if (!freeTypeVariables.isEmpty()) { methodType = new ForAll(freeTypeVariables, methodType); } Enter enter = inliner.enter(); MethodSymbol methodSymbol = new MethodSymbol(0, inliner.asName("__m__"), methodType, symtab.unknownSymbol); Type site = symtab.methodClass.type; Env<AttrContext> env = enter.getTopLevelEnv(TreeMaker.instance(inliner.getContext()).TopLevel(List.<JCTree>nil())); // Set up the resolution phase: try { Field field = AttrContext.class.getDeclaredField("pendingResolutionPhase"); field.setAccessible(true); field.set(env.info, newMethodResolutionPhase(autoboxing())); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } Object resultInfo; try { Class<?> resultInfoClass = Class.forName("com.sun.tools.javac.comp.Attr$ResultInfo"); Constructor<?> resultInfoCtor = resultInfoClass.getDeclaredConstructor(Attr.class, KindSelector.class, Type.class); resultInfoCtor.setAccessible(true); resultInfo = resultInfoCtor.newInstance( Attr.instance(inliner.getContext()), KindSelector.PCK, Type.noType); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } // Type inference sometimes produces diagnostics, so we need to catch them to avoid interfering // with the enclosing compilation. Log.DeferredDiagnosticHandler handler = new Log.DeferredDiagnosticHandler(Log.instance(inliner.getContext())); try { MethodType result = callCheckMethod(warner, inliner, resultInfo, actualArgTypes, methodSymbol, site, env); if (!handler.getDiagnostics().isEmpty()) { throw new InferException(handler.getDiagnostics()); } return result; } finally { Log.instance(inliner.getContext()).popDiagnosticHandler(handler); } }
[ "private", "Type", "infer", "(", "Warner", "warner", ",", "Inliner", "inliner", ",", "List", "<", "Type", ">", "freeTypeVariables", ",", "List", "<", "Type", ">", "expectedArgTypes", ",", "Type", "returnType", ",", "List", "<", "Type", ">", "actualArgTypes", ")", "throws", "InferException", "{", "Symtab", "symtab", "=", "inliner", ".", "symtab", "(", ")", ";", "Type", "methodType", "=", "new", "MethodType", "(", "expectedArgTypes", ",", "returnType", ",", "List", ".", "<", "Type", ">", "nil", "(", ")", ",", "symtab", ".", "methodClass", ")", ";", "if", "(", "!", "freeTypeVariables", ".", "isEmpty", "(", ")", ")", "{", "methodType", "=", "new", "ForAll", "(", "freeTypeVariables", ",", "methodType", ")", ";", "}", "Enter", "enter", "=", "inliner", ".", "enter", "(", ")", ";", "MethodSymbol", "methodSymbol", "=", "new", "MethodSymbol", "(", "0", ",", "inliner", ".", "asName", "(", "\"__m__\"", ")", ",", "methodType", ",", "symtab", ".", "unknownSymbol", ")", ";", "Type", "site", "=", "symtab", ".", "methodClass", ".", "type", ";", "Env", "<", "AttrContext", ">", "env", "=", "enter", ".", "getTopLevelEnv", "(", "TreeMaker", ".", "instance", "(", "inliner", ".", "getContext", "(", ")", ")", ".", "TopLevel", "(", "List", ".", "<", "JCTree", ">", "nil", "(", ")", ")", ")", ";", "// Set up the resolution phase:", "try", "{", "Field", "field", "=", "AttrContext", ".", "class", ".", "getDeclaredField", "(", "\"pendingResolutionPhase\"", ")", ";", "field", ".", "setAccessible", "(", "true", ")", ";", "field", ".", "set", "(", "env", ".", "info", ",", "newMethodResolutionPhase", "(", "autoboxing", "(", ")", ")", ")", ";", "}", "catch", "(", "ReflectiveOperationException", "e", ")", "{", "throw", "new", "LinkageError", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "Object", "resultInfo", ";", "try", "{", "Class", "<", "?", ">", "resultInfoClass", "=", "Class", ".", "forName", "(", "\"com.sun.tools.javac.comp.Attr$ResultInfo\"", ")", ";", "Constructor", "<", "?", ">", "resultInfoCtor", "=", "resultInfoClass", ".", "getDeclaredConstructor", "(", "Attr", ".", "class", ",", "KindSelector", ".", "class", ",", "Type", ".", "class", ")", ";", "resultInfoCtor", ".", "setAccessible", "(", "true", ")", ";", "resultInfo", "=", "resultInfoCtor", ".", "newInstance", "(", "Attr", ".", "instance", "(", "inliner", ".", "getContext", "(", ")", ")", ",", "KindSelector", ".", "PCK", ",", "Type", ".", "noType", ")", ";", "}", "catch", "(", "ReflectiveOperationException", "e", ")", "{", "throw", "new", "LinkageError", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "// Type inference sometimes produces diagnostics, so we need to catch them to avoid interfering", "// with the enclosing compilation.", "Log", ".", "DeferredDiagnosticHandler", "handler", "=", "new", "Log", ".", "DeferredDiagnosticHandler", "(", "Log", ".", "instance", "(", "inliner", ".", "getContext", "(", ")", ")", ")", ";", "try", "{", "MethodType", "result", "=", "callCheckMethod", "(", "warner", ",", "inliner", ",", "resultInfo", ",", "actualArgTypes", ",", "methodSymbol", ",", "site", ",", "env", ")", ";", "if", "(", "!", "handler", ".", "getDiagnostics", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "InferException", "(", "handler", ".", "getDiagnostics", "(", ")", ")", ";", "}", "return", "result", ";", "}", "finally", "{", "Log", ".", "instance", "(", "inliner", ".", "getContext", "(", ")", ")", ".", "popDiagnosticHandler", "(", "handler", ")", ";", "}", "}" ]
Returns the inferred method type of the template based on the given actual argument types. @throws InferException if no instances of the specified type variables would allow the {@code actualArgTypes} to match the {@code expectedArgTypes}
[ "Returns", "the", "inferred", "method", "type", "of", "the", "template", "based", "on", "the", "given", "actual", "argument", "types", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/Template.java#L419-L480
21,823
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentType.java
IncompatibleArgumentType.populateTypesToEnforce
@CheckReturnValue private boolean populateTypesToEnforce( MethodSymbol declaredMethod, Type calledMethodType, Type calledReceiverType, List<RequiredType> argumentTypeRequirements, VisitorState state) { boolean foundAnyTypeToEnforce = false; List<VarSymbol> params = declaredMethod.params(); for (int i = 0; i < params.size(); i++) { VarSymbol varSymbol = params.get(i); CompatibleWith anno = ASTHelpers.getAnnotation(varSymbol, CompatibleWith.class); if (anno != null) { foundAnyTypeToEnforce = true; // Now we try and resolve the generic type argument in the annotation against the current // method call's projection of this generic type. RequiredType requiredType = resolveRequiredTypeForThisCall( state, calledMethodType, calledReceiverType, declaredMethod, anno.value()); // @CW is on the varags parameter if (declaredMethod.isVarArgs() && i == params.size() - 1) { if (i >= argumentTypeRequirements.size()) { // varargs method with 0 args passed from the caller side, no arguments to enforce // void foo(String...); foo(); break; } else { // Set this required type for all of the arguments in the varargs position. for (int j = i; j < argumentTypeRequirements.size(); j++) { argumentTypeRequirements.set(j, requiredType); } } } else { argumentTypeRequirements.set(i, requiredType); } } } return foundAnyTypeToEnforce; }
java
@CheckReturnValue private boolean populateTypesToEnforce( MethodSymbol declaredMethod, Type calledMethodType, Type calledReceiverType, List<RequiredType> argumentTypeRequirements, VisitorState state) { boolean foundAnyTypeToEnforce = false; List<VarSymbol> params = declaredMethod.params(); for (int i = 0; i < params.size(); i++) { VarSymbol varSymbol = params.get(i); CompatibleWith anno = ASTHelpers.getAnnotation(varSymbol, CompatibleWith.class); if (anno != null) { foundAnyTypeToEnforce = true; // Now we try and resolve the generic type argument in the annotation against the current // method call's projection of this generic type. RequiredType requiredType = resolveRequiredTypeForThisCall( state, calledMethodType, calledReceiverType, declaredMethod, anno.value()); // @CW is on the varags parameter if (declaredMethod.isVarArgs() && i == params.size() - 1) { if (i >= argumentTypeRequirements.size()) { // varargs method with 0 args passed from the caller side, no arguments to enforce // void foo(String...); foo(); break; } else { // Set this required type for all of the arguments in the varargs position. for (int j = i; j < argumentTypeRequirements.size(); j++) { argumentTypeRequirements.set(j, requiredType); } } } else { argumentTypeRequirements.set(i, requiredType); } } } return foundAnyTypeToEnforce; }
[ "@", "CheckReturnValue", "private", "boolean", "populateTypesToEnforce", "(", "MethodSymbol", "declaredMethod", ",", "Type", "calledMethodType", ",", "Type", "calledReceiverType", ",", "List", "<", "RequiredType", ">", "argumentTypeRequirements", ",", "VisitorState", "state", ")", "{", "boolean", "foundAnyTypeToEnforce", "=", "false", ";", "List", "<", "VarSymbol", ">", "params", "=", "declaredMethod", ".", "params", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "params", ".", "size", "(", ")", ";", "i", "++", ")", "{", "VarSymbol", "varSymbol", "=", "params", ".", "get", "(", "i", ")", ";", "CompatibleWith", "anno", "=", "ASTHelpers", ".", "getAnnotation", "(", "varSymbol", ",", "CompatibleWith", ".", "class", ")", ";", "if", "(", "anno", "!=", "null", ")", "{", "foundAnyTypeToEnforce", "=", "true", ";", "// Now we try and resolve the generic type argument in the annotation against the current", "// method call's projection of this generic type.", "RequiredType", "requiredType", "=", "resolveRequiredTypeForThisCall", "(", "state", ",", "calledMethodType", ",", "calledReceiverType", ",", "declaredMethod", ",", "anno", ".", "value", "(", ")", ")", ";", "// @CW is on the varags parameter", "if", "(", "declaredMethod", ".", "isVarArgs", "(", ")", "&&", "i", "==", "params", ".", "size", "(", ")", "-", "1", ")", "{", "if", "(", "i", ">=", "argumentTypeRequirements", ".", "size", "(", ")", ")", "{", "// varargs method with 0 args passed from the caller side, no arguments to enforce", "// void foo(String...); foo();", "break", ";", "}", "else", "{", "// Set this required type for all of the arguments in the varargs position.", "for", "(", "int", "j", "=", "i", ";", "j", "<", "argumentTypeRequirements", ".", "size", "(", ")", ";", "j", "++", ")", "{", "argumentTypeRequirements", ".", "set", "(", "j", ",", "requiredType", ")", ";", "}", "}", "}", "else", "{", "argumentTypeRequirements", ".", "set", "(", "i", ",", "requiredType", ")", ";", "}", "}", "}", "return", "foundAnyTypeToEnforce", ";", "}" ]
caller should explore super-methods.
[ "caller", "should", "explore", "super", "-", "methods", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentType.java#L153-L193
21,824
google/error-prone
check_api/src/main/java/com/google/errorprone/util/Signatures.java
Signatures.classDescriptor
public static String classDescriptor(Type type, Types types) { SigGen sig = new SigGen(types); sig.assembleClassSig(types.erasure(type)); return sig.toString(); }
java
public static String classDescriptor(Type type, Types types) { SigGen sig = new SigGen(types); sig.assembleClassSig(types.erasure(type)); return sig.toString(); }
[ "public", "static", "String", "classDescriptor", "(", "Type", "type", ",", "Types", "types", ")", "{", "SigGen", "sig", "=", "new", "SigGen", "(", "types", ")", ";", "sig", ".", "assembleClassSig", "(", "types", ".", "erasure", "(", "type", ")", ")", ";", "return", "sig", ".", "toString", "(", ")", ";", "}" ]
Returns the binary names of the class.
[ "Returns", "the", "binary", "names", "of", "the", "class", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/Signatures.java#L36-L40
21,825
google/error-prone
check_api/src/main/java/com/google/errorprone/util/Signatures.java
Signatures.descriptor
public static String descriptor(Type type, Types types) { SigGen sig = new SigGen(types); sig.assembleSig(types.erasure(type)); return sig.toString(); }
java
public static String descriptor(Type type, Types types) { SigGen sig = new SigGen(types); sig.assembleSig(types.erasure(type)); return sig.toString(); }
[ "public", "static", "String", "descriptor", "(", "Type", "type", ",", "Types", "types", ")", "{", "SigGen", "sig", "=", "new", "SigGen", "(", "types", ")", ";", "sig", ".", "assembleSig", "(", "types", ".", "erasure", "(", "type", ")", ")", ";", "return", "sig", ".", "toString", "(", ")", ";", "}" ]
Returns a JVMS 4.3.3 method descriptor.
[ "Returns", "a", "JVMS", "4", ".", "3", ".", "3", "method", "descriptor", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/Signatures.java#L43-L47
21,826
google/error-prone
check_api/src/main/java/com/google/errorprone/util/Signatures.java
Signatures.prettyMethodSignature
public static String prettyMethodSignature(ClassSymbol origin, MethodSymbol m) { StringBuilder sb = new StringBuilder(); if (m.isConstructor()) { Name name = m.owner.enclClass().getSimpleName(); if (name.isEmpty()) { // use the superclass name of anonymous classes name = m.owner.enclClass().getSuperclass().asElement().getSimpleName(); } sb.append(name); } else { if (!m.owner.equals(origin)) { sb.append(m.owner.getSimpleName()).append('.'); } sb.append(m.getSimpleName()); } sb.append( m.getParameters().stream() .map(v -> v.type.accept(PRETTY_TYPE_VISITOR, null)) .collect(joining(", ", "(", ")"))); return sb.toString(); }
java
public static String prettyMethodSignature(ClassSymbol origin, MethodSymbol m) { StringBuilder sb = new StringBuilder(); if (m.isConstructor()) { Name name = m.owner.enclClass().getSimpleName(); if (name.isEmpty()) { // use the superclass name of anonymous classes name = m.owner.enclClass().getSuperclass().asElement().getSimpleName(); } sb.append(name); } else { if (!m.owner.equals(origin)) { sb.append(m.owner.getSimpleName()).append('.'); } sb.append(m.getSimpleName()); } sb.append( m.getParameters().stream() .map(v -> v.type.accept(PRETTY_TYPE_VISITOR, null)) .collect(joining(", ", "(", ")"))); return sb.toString(); }
[ "public", "static", "String", "prettyMethodSignature", "(", "ClassSymbol", "origin", ",", "MethodSymbol", "m", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "m", ".", "isConstructor", "(", ")", ")", "{", "Name", "name", "=", "m", ".", "owner", ".", "enclClass", "(", ")", ".", "getSimpleName", "(", ")", ";", "if", "(", "name", ".", "isEmpty", "(", ")", ")", "{", "// use the superclass name of anonymous classes", "name", "=", "m", ".", "owner", ".", "enclClass", "(", ")", ".", "getSuperclass", "(", ")", ".", "asElement", "(", ")", ".", "getSimpleName", "(", ")", ";", "}", "sb", ".", "append", "(", "name", ")", ";", "}", "else", "{", "if", "(", "!", "m", ".", "owner", ".", "equals", "(", "origin", ")", ")", "{", "sb", ".", "append", "(", "m", ".", "owner", ".", "getSimpleName", "(", ")", ")", ".", "append", "(", "'", "'", ")", ";", "}", "sb", ".", "append", "(", "m", ".", "getSimpleName", "(", ")", ")", ";", "}", "sb", ".", "append", "(", "m", ".", "getParameters", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "v", "->", "v", ".", "type", ".", "accept", "(", "PRETTY_TYPE_VISITOR", ",", "null", ")", ")", ".", "collect", "(", "joining", "(", "\", \"", ",", "\"(\"", ",", "\")\"", ")", ")", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Pretty-prints a method signature for use in diagnostics. <p>Uses simple names for declared types, and omitting formal type parameters and the return type since they do not affect overload resolution.
[ "Pretty", "-", "prints", "a", "method", "signature", "for", "use", "in", "diagnostics", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/Signatures.java#L88-L108
21,827
google/error-prone
check_api/src/main/java/com/google/errorprone/util/SourceCodeEscapers.java
SourceCodeEscapers.asUnicodeHexEscape
private static char[] asUnicodeHexEscape(char c) { // Equivalent to String.format("\\u%04x", (int)c); char[] r = new char[6]; r[0] = '\\'; r[1] = 'u'; r[5] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[4] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[3] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[2] = HEX_DIGITS[c & 0xF]; return r; }
java
private static char[] asUnicodeHexEscape(char c) { // Equivalent to String.format("\\u%04x", (int)c); char[] r = new char[6]; r[0] = '\\'; r[1] = 'u'; r[5] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[4] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[3] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[2] = HEX_DIGITS[c & 0xF]; return r; }
[ "private", "static", "char", "[", "]", "asUnicodeHexEscape", "(", "char", "c", ")", "{", "// Equivalent to String.format(\"\\\\u%04x\", (int)c);", "char", "[", "]", "r", "=", "new", "char", "[", "6", "]", ";", "r", "[", "0", "]", "=", "'", "'", ";", "r", "[", "1", "]", "=", "'", "'", ";", "r", "[", "5", "]", "=", "HEX_DIGITS", "[", "c", "&", "0xF", "]", ";", "c", ">>>=", "4", ";", "r", "[", "4", "]", "=", "HEX_DIGITS", "[", "c", "&", "0xF", "]", ";", "c", ">>>=", "4", ";", "r", "[", "3", "]", "=", "HEX_DIGITS", "[", "c", "&", "0xF", "]", ";", "c", ">>>=", "4", ";", "r", "[", "2", "]", "=", "HEX_DIGITS", "[", "c", "&", "0xF", "]", ";", "return", "r", ";", "}" ]
Helper for common case of escaping a single char.
[ "Helper", "for", "common", "case", "of", "escaping", "a", "single", "char", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/SourceCodeEscapers.java#L88-L101
21,828
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NarrowingCompoundAssignment.java
NarrowingCompoundAssignment.identifyBadCast
private static String identifyBadCast(Type lhs, Type rhs, Types types) { if (!lhs.isPrimitive()) { return null; } if (types.isConvertible(rhs, lhs)) { // Exemption if the rhs is convertible to the lhs. // This allows, e.g.: <byte> &= <byte> since the narrowing conversion can never be // detected. // This also allows, for example, char += char, which could overflow, but this is no // different than any other integral addition. return null; } return String.format( "Compound assignments from %s to %s hide lossy casts", prettyType(rhs), prettyType(lhs)); }
java
private static String identifyBadCast(Type lhs, Type rhs, Types types) { if (!lhs.isPrimitive()) { return null; } if (types.isConvertible(rhs, lhs)) { // Exemption if the rhs is convertible to the lhs. // This allows, e.g.: <byte> &= <byte> since the narrowing conversion can never be // detected. // This also allows, for example, char += char, which could overflow, but this is no // different than any other integral addition. return null; } return String.format( "Compound assignments from %s to %s hide lossy casts", prettyType(rhs), prettyType(lhs)); }
[ "private", "static", "String", "identifyBadCast", "(", "Type", "lhs", ",", "Type", "rhs", ",", "Types", "types", ")", "{", "if", "(", "!", "lhs", ".", "isPrimitive", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "types", ".", "isConvertible", "(", "rhs", ",", "lhs", ")", ")", "{", "// Exemption if the rhs is convertible to the lhs.", "// This allows, e.g.: <byte> &= <byte> since the narrowing conversion can never be", "// detected.", "// This also allows, for example, char += char, which could overflow, but this is no", "// different than any other integral addition.", "return", "null", ";", "}", "return", "String", ".", "format", "(", "\"Compound assignments from %s to %s hide lossy casts\"", ",", "prettyType", "(", "rhs", ")", ",", "prettyType", "(", "lhs", ")", ")", ";", "}" ]
Classifies bad casts.
[ "Classifies", "bad", "casts", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/NarrowingCompoundAssignment.java#L125-L139
21,829
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NarrowingCompoundAssignment.java
NarrowingCompoundAssignment.rewriteCompoundAssignment
private static Optional<Fix> rewriteCompoundAssignment( CompoundAssignmentTree tree, VisitorState state) { CharSequence var = state.getSourceForNode(tree.getVariable()); CharSequence expr = state.getSourceForNode(tree.getExpression()); if (var == null || expr == null) { return Optional.absent(); } switch (tree.getKind()) { case RIGHT_SHIFT_ASSIGNMENT: // narrowing the result of a signed right shift does not lose information return Optional.absent(); default: break; } Kind regularAssignmentKind = regularAssignmentFromCompound(tree.getKind()); String op = assignmentToString(regularAssignmentKind); // Add parens to the rhs if necessary to preserve the current precedence // e.g. 's -= 1 - 2' -> 's = s - (1 - 2)' OperatorPrecedence rhsPrecedence = tree.getExpression() instanceof JCBinary ? OperatorPrecedence.from(tree.getExpression().getKind()) : tree.getExpression() instanceof ConditionalExpressionTree ? OperatorPrecedence.TERNARY : null; if (rhsPrecedence != null) { if (!rhsPrecedence.isHigher(OperatorPrecedence.from(regularAssignmentKind))) { expr = String.format("(%s)", expr); } } // e.g. 's *= 42' -> 's = (short) (s * 42)' String castType = getType(tree.getVariable()).toString(); String replacement = String.format("%s = (%s) (%s %s %s)", var, castType, var, op, expr); return Optional.of(SuggestedFix.replace(tree, replacement)); }
java
private static Optional<Fix> rewriteCompoundAssignment( CompoundAssignmentTree tree, VisitorState state) { CharSequence var = state.getSourceForNode(tree.getVariable()); CharSequence expr = state.getSourceForNode(tree.getExpression()); if (var == null || expr == null) { return Optional.absent(); } switch (tree.getKind()) { case RIGHT_SHIFT_ASSIGNMENT: // narrowing the result of a signed right shift does not lose information return Optional.absent(); default: break; } Kind regularAssignmentKind = regularAssignmentFromCompound(tree.getKind()); String op = assignmentToString(regularAssignmentKind); // Add parens to the rhs if necessary to preserve the current precedence // e.g. 's -= 1 - 2' -> 's = s - (1 - 2)' OperatorPrecedence rhsPrecedence = tree.getExpression() instanceof JCBinary ? OperatorPrecedence.from(tree.getExpression().getKind()) : tree.getExpression() instanceof ConditionalExpressionTree ? OperatorPrecedence.TERNARY : null; if (rhsPrecedence != null) { if (!rhsPrecedence.isHigher(OperatorPrecedence.from(regularAssignmentKind))) { expr = String.format("(%s)", expr); } } // e.g. 's *= 42' -> 's = (short) (s * 42)' String castType = getType(tree.getVariable()).toString(); String replacement = String.format("%s = (%s) (%s %s %s)", var, castType, var, op, expr); return Optional.of(SuggestedFix.replace(tree, replacement)); }
[ "private", "static", "Optional", "<", "Fix", ">", "rewriteCompoundAssignment", "(", "CompoundAssignmentTree", "tree", ",", "VisitorState", "state", ")", "{", "CharSequence", "var", "=", "state", ".", "getSourceForNode", "(", "tree", ".", "getVariable", "(", ")", ")", ";", "CharSequence", "expr", "=", "state", ".", "getSourceForNode", "(", "tree", ".", "getExpression", "(", ")", ")", ";", "if", "(", "var", "==", "null", "||", "expr", "==", "null", ")", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "switch", "(", "tree", ".", "getKind", "(", ")", ")", "{", "case", "RIGHT_SHIFT_ASSIGNMENT", ":", "// narrowing the result of a signed right shift does not lose information", "return", "Optional", ".", "absent", "(", ")", ";", "default", ":", "break", ";", "}", "Kind", "regularAssignmentKind", "=", "regularAssignmentFromCompound", "(", "tree", ".", "getKind", "(", ")", ")", ";", "String", "op", "=", "assignmentToString", "(", "regularAssignmentKind", ")", ";", "// Add parens to the rhs if necessary to preserve the current precedence", "// e.g. 's -= 1 - 2' -> 's = s - (1 - 2)'", "OperatorPrecedence", "rhsPrecedence", "=", "tree", ".", "getExpression", "(", ")", "instanceof", "JCBinary", "?", "OperatorPrecedence", ".", "from", "(", "tree", ".", "getExpression", "(", ")", ".", "getKind", "(", ")", ")", ":", "tree", ".", "getExpression", "(", ")", "instanceof", "ConditionalExpressionTree", "?", "OperatorPrecedence", ".", "TERNARY", ":", "null", ";", "if", "(", "rhsPrecedence", "!=", "null", ")", "{", "if", "(", "!", "rhsPrecedence", ".", "isHigher", "(", "OperatorPrecedence", ".", "from", "(", "regularAssignmentKind", ")", ")", ")", "{", "expr", "=", "String", ".", "format", "(", "\"(%s)\"", ",", "expr", ")", ";", "}", "}", "// e.g. 's *= 42' -> 's = (short) (s * 42)'", "String", "castType", "=", "getType", "(", "tree", ".", "getVariable", "(", ")", ")", ".", "toString", "(", ")", ";", "String", "replacement", "=", "String", ".", "format", "(", "\"%s = (%s) (%s %s %s)\"", ",", "var", ",", "castType", ",", "var", ",", "op", ",", "expr", ")", ";", "return", "Optional", ".", "of", "(", "SuggestedFix", ".", "replace", "(", "tree", ",", "replacement", ")", ")", ";", "}" ]
Desugars a compound assignment, making the cast explicit.
[ "Desugars", "a", "compound", "assignment", "making", "the", "cast", "explicit", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/NarrowingCompoundAssignment.java#L142-L178
21,830
google/error-prone
check_api/src/main/java/com/google/errorprone/suppliers/Suppliers.java
Suppliers.typeFromString
public static Supplier<Type> typeFromString(final String typeString) { requireNonNull(typeString); return new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getTypeFromString(typeString); } }; }
java
public static Supplier<Type> typeFromString(final String typeString) { requireNonNull(typeString); return new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getTypeFromString(typeString); } }; }
[ "public", "static", "Supplier", "<", "Type", ">", "typeFromString", "(", "final", "String", "typeString", ")", "{", "requireNonNull", "(", "typeString", ")", ";", "return", "new", "Supplier", "<", "Type", ">", "(", ")", "{", "@", "Override", "public", "Type", "get", "(", "VisitorState", "state", ")", "{", "return", "state", ".", "getTypeFromString", "(", "typeString", ")", ";", "}", "}", ";", "}" ]
Given the string representation of a type, supplies the corresponding type. @param typeString a string representation of a type, e.g., "java.util.List"
[ "Given", "the", "string", "representation", "of", "a", "type", "supplies", "the", "corresponding", "type", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/suppliers/Suppliers.java#L116-L124
21,831
google/error-prone
check_api/src/main/java/com/google/errorprone/suppliers/Suppliers.java
Suppliers.identitySupplier
public static <T> Supplier<T> identitySupplier(final T toSupply) { return new Supplier<T>() { @Override public T get(VisitorState state) { return toSupply; } }; }
java
public static <T> Supplier<T> identitySupplier(final T toSupply) { return new Supplier<T>() { @Override public T get(VisitorState state) { return toSupply; } }; }
[ "public", "static", "<", "T", ">", "Supplier", "<", "T", ">", "identitySupplier", "(", "final", "T", "toSupply", ")", "{", "return", "new", "Supplier", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "T", "get", "(", "VisitorState", "state", ")", "{", "return", "toSupply", ";", "}", "}", ";", "}" ]
Supplies what was given. Useful for adapting to methods that require a supplier. @param toSupply the item to supply
[ "Supplies", "what", "was", "given", ".", "Useful", "for", "adapting", "to", "methods", "that", "require", "a", "supplier", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/suppliers/Suppliers.java#L248-L255
21,832
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java
CreatesDuplicateCallHeuristic.isAcceptableChange
@Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { return findArgumentsForOtherInstances(symbol, node, state).stream() .allMatch(arguments -> !anyArgumentsMatch(changes.changedPairs(), arguments)); }
java
@Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { return findArgumentsForOtherInstances(symbol, node, state).stream() .allMatch(arguments -> !anyArgumentsMatch(changes.changedPairs(), arguments)); }
[ "@", "Override", "public", "boolean", "isAcceptableChange", "(", "Changes", "changes", ",", "Tree", "node", ",", "MethodSymbol", "symbol", ",", "VisitorState", "state", ")", "{", "return", "findArgumentsForOtherInstances", "(", "symbol", ",", "node", ",", "state", ")", ".", "stream", "(", ")", ".", "allMatch", "(", "arguments", "->", "!", "anyArgumentsMatch", "(", "changes", ".", "changedPairs", "(", ")", ",", "arguments", ")", ")", ";", "}" ]
Returns true if there are no other calls to this method which already have an actual parameter in the position we are moving this one too.
[ "Returns", "true", "if", "there", "are", "no", "other", "calls", "to", "this", "method", "which", "already", "have", "an", "actual", "parameter", "in", "the", "position", "we", "are", "moving", "this", "one", "too", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java#L44-L49
21,833
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java
CreatesDuplicateCallHeuristic.anyArgumentsMatch
private static boolean anyArgumentsMatch( List<ParameterPair> changedPairs, List<Parameter> arguments) { return changedPairs.stream() .anyMatch( change -> Objects.equals( change.actual().text(), arguments.get(change.formal().index()).text())); }
java
private static boolean anyArgumentsMatch( List<ParameterPair> changedPairs, List<Parameter> arguments) { return changedPairs.stream() .anyMatch( change -> Objects.equals( change.actual().text(), arguments.get(change.formal().index()).text())); }
[ "private", "static", "boolean", "anyArgumentsMatch", "(", "List", "<", "ParameterPair", ">", "changedPairs", ",", "List", "<", "Parameter", ">", "arguments", ")", "{", "return", "changedPairs", ".", "stream", "(", ")", ".", "anyMatch", "(", "change", "->", "Objects", ".", "equals", "(", "change", ".", "actual", "(", ")", ".", "text", "(", ")", ",", "arguments", ".", "get", "(", "change", ".", "formal", "(", ")", ".", "index", "(", ")", ")", ".", "text", "(", ")", ")", ")", ";", "}" ]
Return true if the replacement name is equal to the argument name for any replacement position.
[ "Return", "true", "if", "the", "replacement", "name", "is", "equal", "to", "the", "argument", "name", "for", "any", "replacement", "position", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristic.java#L54-L61
21,834
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/AmbiguousMethodReference.java
AmbiguousMethodReference.methodReferenceDescriptor
private String methodReferenceDescriptor(Types types, MethodSymbol sym) { StringBuilder sb = new StringBuilder(); sb.append(sym.getSimpleName()).append('('); if (!sym.isStatic()) { sb.append(Signatures.descriptor(sym.owner.type, types)); } sym.params().stream().map(p -> Signatures.descriptor(p.type, types)).forEachOrdered(sb::append); sb.append(")"); return sb.toString(); }
java
private String methodReferenceDescriptor(Types types, MethodSymbol sym) { StringBuilder sb = new StringBuilder(); sb.append(sym.getSimpleName()).append('('); if (!sym.isStatic()) { sb.append(Signatures.descriptor(sym.owner.type, types)); } sym.params().stream().map(p -> Signatures.descriptor(p.type, types)).forEachOrdered(sb::append); sb.append(")"); return sb.toString(); }
[ "private", "String", "methodReferenceDescriptor", "(", "Types", "types", ",", "MethodSymbol", "sym", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "sym", ".", "getSimpleName", "(", ")", ")", ".", "append", "(", "'", "'", ")", ";", "if", "(", "!", "sym", ".", "isStatic", "(", ")", ")", "{", "sb", ".", "append", "(", "Signatures", ".", "descriptor", "(", "sym", ".", "owner", ".", "type", ",", "types", ")", ")", ";", "}", "sym", ".", "params", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "p", "->", "Signatures", ".", "descriptor", "(", "p", ".", "type", ",", "types", ")", ")", ".", "forEachOrdered", "(", "sb", "::", "append", ")", ";", "sb", ".", "append", "(", "\")\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Returns a string descriptor of a method's reference type.
[ "Returns", "a", "string", "descriptor", "of", "a", "method", "s", "reference", "type", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/AmbiguousMethodReference.java#L110-L119
21,835
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariable.java
UnnecessaryBoxedVariable.localVariableMatches
private static boolean localVariableMatches(VariableTree tree, VisitorState state) { ExpressionTree expression = tree.getInitializer(); if (expression == null) { Tree leaf = state.getPath().getParentPath().getLeaf(); if (!(leaf instanceof EnhancedForLoopTree)) { return true; } EnhancedForLoopTree node = (EnhancedForLoopTree) leaf; Type expressionType = ASTHelpers.getType(node.getExpression()); if (expressionType == null) { return false; } Type elemtype = state.getTypes().elemtype(expressionType); // Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type. return elemtype != null && elemtype.isPrimitive(); } Type initializerType = ASTHelpers.getType(expression); if (initializerType == null) { return false; } if (initializerType.isPrimitive()) { return true; } // Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX. return VALUE_OF_MATCHER.matches(expression, state); }
java
private static boolean localVariableMatches(VariableTree tree, VisitorState state) { ExpressionTree expression = tree.getInitializer(); if (expression == null) { Tree leaf = state.getPath().getParentPath().getLeaf(); if (!(leaf instanceof EnhancedForLoopTree)) { return true; } EnhancedForLoopTree node = (EnhancedForLoopTree) leaf; Type expressionType = ASTHelpers.getType(node.getExpression()); if (expressionType == null) { return false; } Type elemtype = state.getTypes().elemtype(expressionType); // Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type. return elemtype != null && elemtype.isPrimitive(); } Type initializerType = ASTHelpers.getType(expression); if (initializerType == null) { return false; } if (initializerType.isPrimitive()) { return true; } // Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX. return VALUE_OF_MATCHER.matches(expression, state); }
[ "private", "static", "boolean", "localVariableMatches", "(", "VariableTree", "tree", ",", "VisitorState", "state", ")", "{", "ExpressionTree", "expression", "=", "tree", ".", "getInitializer", "(", ")", ";", "if", "(", "expression", "==", "null", ")", "{", "Tree", "leaf", "=", "state", ".", "getPath", "(", ")", ".", "getParentPath", "(", ")", ".", "getLeaf", "(", ")", ";", "if", "(", "!", "(", "leaf", "instanceof", "EnhancedForLoopTree", ")", ")", "{", "return", "true", ";", "}", "EnhancedForLoopTree", "node", "=", "(", "EnhancedForLoopTree", ")", "leaf", ";", "Type", "expressionType", "=", "ASTHelpers", ".", "getType", "(", "node", ".", "getExpression", "(", ")", ")", ";", "if", "(", "expressionType", "==", "null", ")", "{", "return", "false", ";", "}", "Type", "elemtype", "=", "state", ".", "getTypes", "(", ")", ".", "elemtype", "(", "expressionType", ")", ";", "// Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type.", "return", "elemtype", "!=", "null", "&&", "elemtype", ".", "isPrimitive", "(", ")", ";", "}", "Type", "initializerType", "=", "ASTHelpers", ".", "getType", "(", "expression", ")", ";", "if", "(", "initializerType", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "initializerType", ".", "isPrimitive", "(", ")", ")", "{", "return", "true", ";", "}", "// Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX.", "return", "VALUE_OF_MATCHER", ".", "matches", "(", "expression", ",", "state", ")", ";", "}" ]
Check to see if the local variable should be considered for replacement, i.e. <ul> <li>A variable without an initializer <li>Enhanced for loop variables can be replaced if they are loops over primitive arrays <li>A variable initialized with a primitive value (which is then auto-boxed) <li>A variable initialized with an invocation of {@code Boxed.valueOf}, since that can be replaced with {@code Boxed.parseBoxed}. </ul>
[ "Check", "to", "see", "if", "the", "local", "variable", "should", "be", "considered", "for", "replacement", "i", ".", "e", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariable.java#L177-L202
21,836
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/AbstractToString.java
AbstractToString.isToString
ToStringKind isToString(Tree parent, ExpressionTree tree, VisitorState state) { // is the enclosing expression string concat? if (isStringConcat(parent, state)) { return ToStringKind.IMPLICIT; } if (parent instanceof ExpressionTree) { ExpressionTree parentExpression = (ExpressionTree) parent; // the enclosing method is print() or println() if (PRINT_STRING.matches(parentExpression, state)) { return ToStringKind.IMPLICIT; } // the enclosing method is String.valueOf() if (VALUE_OF.matches(parentExpression, state)) { return ToStringKind.EXPLICIT; } } return ToStringKind.NONE; }
java
ToStringKind isToString(Tree parent, ExpressionTree tree, VisitorState state) { // is the enclosing expression string concat? if (isStringConcat(parent, state)) { return ToStringKind.IMPLICIT; } if (parent instanceof ExpressionTree) { ExpressionTree parentExpression = (ExpressionTree) parent; // the enclosing method is print() or println() if (PRINT_STRING.matches(parentExpression, state)) { return ToStringKind.IMPLICIT; } // the enclosing method is String.valueOf() if (VALUE_OF.matches(parentExpression, state)) { return ToStringKind.EXPLICIT; } } return ToStringKind.NONE; }
[ "ToStringKind", "isToString", "(", "Tree", "parent", ",", "ExpressionTree", "tree", ",", "VisitorState", "state", ")", "{", "// is the enclosing expression string concat?", "if", "(", "isStringConcat", "(", "parent", ",", "state", ")", ")", "{", "return", "ToStringKind", ".", "IMPLICIT", ";", "}", "if", "(", "parent", "instanceof", "ExpressionTree", ")", "{", "ExpressionTree", "parentExpression", "=", "(", "ExpressionTree", ")", "parent", ";", "// the enclosing method is print() or println()", "if", "(", "PRINT_STRING", ".", "matches", "(", "parentExpression", ",", "state", ")", ")", "{", "return", "ToStringKind", ".", "IMPLICIT", ";", "}", "// the enclosing method is String.valueOf()", "if", "(", "VALUE_OF", ".", "matches", "(", "parentExpression", ",", "state", ")", ")", "{", "return", "ToStringKind", ".", "EXPLICIT", ";", "}", "}", "return", "ToStringKind", ".", "NONE", ";", "}" ]
Classifies expressions that are converted to strings by their enclosing expression.
[ "Classifies", "expressions", "that", "are", "converted", "to", "strings", "by", "their", "enclosing", "expression", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/AbstractToString.java#L162-L179
21,837
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ModifiedButNotUsed.java
ModifiedButNotUsed.newFluentChain
private static boolean newFluentChain(ExpressionTree tree, VisitorState state) { while (tree instanceof MethodInvocationTree && FLUENT_CHAIN.matches(tree, state)) { tree = getReceiver(tree); } return tree != null && FLUENT_CONSTRUCTOR.matches(tree, state); }
java
private static boolean newFluentChain(ExpressionTree tree, VisitorState state) { while (tree instanceof MethodInvocationTree && FLUENT_CHAIN.matches(tree, state)) { tree = getReceiver(tree); } return tree != null && FLUENT_CONSTRUCTOR.matches(tree, state); }
[ "private", "static", "boolean", "newFluentChain", "(", "ExpressionTree", "tree", ",", "VisitorState", "state", ")", "{", "while", "(", "tree", "instanceof", "MethodInvocationTree", "&&", "FLUENT_CHAIN", ".", "matches", "(", "tree", ",", "state", ")", ")", "{", "tree", "=", "getReceiver", "(", "tree", ")", ";", "}", "return", "tree", "!=", "null", "&&", "FLUENT_CONSTRUCTOR", ".", "matches", "(", "tree", ",", "state", ")", ";", "}" ]
Whether this is a chain of method invocations terminating in a new proto or collection builder.
[ "Whether", "this", "is", "a", "chain", "of", "method", "invocations", "terminating", "in", "a", "new", "proto", "or", "collection", "builder", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/ModifiedButNotUsed.java#L299-L304
21,838
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/WellKnownMutability.java
WellKnownMutability.isAnnotation
public static boolean isAnnotation(VisitorState state, Type type) { return isAssignableTo(type, Suppliers.ANNOTATION_TYPE, state); }
java
public static boolean isAnnotation(VisitorState state, Type type) { return isAssignableTo(type, Suppliers.ANNOTATION_TYPE, state); }
[ "public", "static", "boolean", "isAnnotation", "(", "VisitorState", "state", ",", "Type", "type", ")", "{", "return", "isAssignableTo", "(", "type", ",", "Suppliers", ".", "ANNOTATION_TYPE", ",", "state", ")", ";", "}" ]
Returns true if the type is an annotation.
[ "Returns", "true", "if", "the", "type", "is", "an", "annotation", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/WellKnownMutability.java#L371-L373
21,839
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Description.java
Description.getMessageWithoutCheckName
public String getMessageWithoutCheckName() { return linkUrl != null ? String.format("%s\n%s", rawMessage, linkTextForDiagnostic(linkUrl)) : String.format("%s", rawMessage); }
java
public String getMessageWithoutCheckName() { return linkUrl != null ? String.format("%s\n%s", rawMessage, linkTextForDiagnostic(linkUrl)) : String.format("%s", rawMessage); }
[ "public", "String", "getMessageWithoutCheckName", "(", ")", "{", "return", "linkUrl", "!=", "null", "?", "String", ".", "format", "(", "\"%s\\n%s\"", ",", "rawMessage", ",", "linkTextForDiagnostic", "(", "linkUrl", ")", ")", ":", "String", ".", "format", "(", "\"%s\"", ",", "rawMessage", ")", ";", "}" ]
Returns the message, not including the check name but including the link.
[ "Returns", "the", "message", "not", "including", "the", "check", "name", "but", "including", "the", "link", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Description.java#L91-L95
21,840
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Description.java
Description.applySeverityOverride
@CheckReturnValue public Description applySeverityOverride(SeverityLevel severity) { return new Description(position, checkName, rawMessage, linkUrl, fixes, severity); }
java
@CheckReturnValue public Description applySeverityOverride(SeverityLevel severity) { return new Description(position, checkName, rawMessage, linkUrl, fixes, severity); }
[ "@", "CheckReturnValue", "public", "Description", "applySeverityOverride", "(", "SeverityLevel", "severity", ")", "{", "return", "new", "Description", "(", "position", ",", "checkName", ",", "rawMessage", ",", "linkUrl", ",", "fixes", ",", "severity", ")", ";", "}" ]
Internal-only. Has no effect if applied to a Description within a BugChecker.
[ "Internal", "-", "only", ".", "Has", "no", "effect", "if", "applied", "to", "a", "Description", "within", "a", "BugChecker", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Description.java#L126-L129
21,841
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/PenaltyThresholdHeuristic.java
PenaltyThresholdHeuristic.isAcceptableChange
@Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { int numberOfChanges = changes.changedPairs().size(); return changes.totalOriginalCost() - changes.totalAssignmentCost() >= threshold * numberOfChanges; }
java
@Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { int numberOfChanges = changes.changedPairs().size(); return changes.totalOriginalCost() - changes.totalAssignmentCost() >= threshold * numberOfChanges; }
[ "@", "Override", "public", "boolean", "isAcceptableChange", "(", "Changes", "changes", ",", "Tree", "node", ",", "MethodSymbol", "symbol", ",", "VisitorState", "state", ")", "{", "int", "numberOfChanges", "=", "changes", ".", "changedPairs", "(", ")", ".", "size", "(", ")", ";", "return", "changes", ".", "totalOriginalCost", "(", ")", "-", "changes", ".", "totalAssignmentCost", "(", ")", ">=", "threshold", "*", "numberOfChanges", ";", "}" ]
Return true if the change is sufficiently different.
[ "Return", "true", "if", "the", "change", "is", "sufficiently", "different", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/PenaltyThresholdHeuristic.java#L47-L55
21,842
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/WildcardImport.java
WildcardImport.getWildcardImports
private static ImmutableList<ImportTree> getWildcardImports(List<? extends ImportTree> imports) { ImmutableList.Builder<ImportTree> result = ImmutableList.builder(); for (ImportTree tree : imports) { // javac represents on-demand imports as a member select where the selected name is '*'. Tree ident = tree.getQualifiedIdentifier(); if (!(ident instanceof MemberSelectTree)) { continue; } MemberSelectTree select = (MemberSelectTree) ident; if (select.getIdentifier().contentEquals("*")) { result.add(tree); } } return result.build(); }
java
private static ImmutableList<ImportTree> getWildcardImports(List<? extends ImportTree> imports) { ImmutableList.Builder<ImportTree> result = ImmutableList.builder(); for (ImportTree tree : imports) { // javac represents on-demand imports as a member select where the selected name is '*'. Tree ident = tree.getQualifiedIdentifier(); if (!(ident instanceof MemberSelectTree)) { continue; } MemberSelectTree select = (MemberSelectTree) ident; if (select.getIdentifier().contentEquals("*")) { result.add(tree); } } return result.build(); }
[ "private", "static", "ImmutableList", "<", "ImportTree", ">", "getWildcardImports", "(", "List", "<", "?", "extends", "ImportTree", ">", "imports", ")", "{", "ImmutableList", ".", "Builder", "<", "ImportTree", ">", "result", "=", "ImmutableList", ".", "builder", "(", ")", ";", "for", "(", "ImportTree", "tree", ":", "imports", ")", "{", "// javac represents on-demand imports as a member select where the selected name is '*'.", "Tree", "ident", "=", "tree", ".", "getQualifiedIdentifier", "(", ")", ";", "if", "(", "!", "(", "ident", "instanceof", "MemberSelectTree", ")", ")", "{", "continue", ";", "}", "MemberSelectTree", "select", "=", "(", "MemberSelectTree", ")", "ident", ";", "if", "(", "select", ".", "getIdentifier", "(", ")", ".", "contentEquals", "(", "\"*\"", ")", ")", "{", "result", ".", "add", "(", "tree", ")", ";", "}", "}", "return", "result", ".", "build", "(", ")", ";", "}" ]
Collect all on demand imports.
[ "Collect", "all", "on", "demand", "imports", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/WildcardImport.java#L113-L127
21,843
google/error-prone
check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java
InferredNullability.getNullnessGenerics
public ImmutableMap<TypeVariableSymbol, Nullness> getNullnessGenerics( MethodInvocationTree callsite) { ImmutableMap.Builder<TypeVariableSymbol, Nullness> result = ImmutableMap.builder(); for (TypeVariableSymbol tvs : TreeInfo.symbol((JCTree) callsite.getMethodSelect()).getTypeParameters()) { InferenceVariable iv = TypeVariableInferenceVar.create(tvs, callsite); if (constraintGraph.nodes().contains(iv)) { getNullness(iv).ifPresent(nullness -> result.put(tvs, nullness)); } } return result.build(); }
java
public ImmutableMap<TypeVariableSymbol, Nullness> getNullnessGenerics( MethodInvocationTree callsite) { ImmutableMap.Builder<TypeVariableSymbol, Nullness> result = ImmutableMap.builder(); for (TypeVariableSymbol tvs : TreeInfo.symbol((JCTree) callsite.getMethodSelect()).getTypeParameters()) { InferenceVariable iv = TypeVariableInferenceVar.create(tvs, callsite); if (constraintGraph.nodes().contains(iv)) { getNullness(iv).ifPresent(nullness -> result.put(tvs, nullness)); } } return result.build(); }
[ "public", "ImmutableMap", "<", "TypeVariableSymbol", ",", "Nullness", ">", "getNullnessGenerics", "(", "MethodInvocationTree", "callsite", ")", "{", "ImmutableMap", ".", "Builder", "<", "TypeVariableSymbol", ",", "Nullness", ">", "result", "=", "ImmutableMap", ".", "builder", "(", ")", ";", "for", "(", "TypeVariableSymbol", "tvs", ":", "TreeInfo", ".", "symbol", "(", "(", "JCTree", ")", "callsite", ".", "getMethodSelect", "(", ")", ")", ".", "getTypeParameters", "(", ")", ")", "{", "InferenceVariable", "iv", "=", "TypeVariableInferenceVar", ".", "create", "(", "tvs", ",", "callsite", ")", ";", "if", "(", "constraintGraph", ".", "nodes", "(", ")", ".", "contains", "(", "iv", ")", ")", "{", "getNullness", "(", "iv", ")", ".", "ifPresent", "(", "nullness", "->", "result", ".", "put", "(", "tvs", ",", "nullness", ")", ")", ";", "}", "}", "return", "result", ".", "build", "(", ")", ";", "}" ]
Get inferred nullness qualifiers for method-generic type variables at a callsite. When inference is not possible for a given type variable, that type variable is not included in the resulting map.
[ "Get", "inferred", "nullness", "qualifiers", "for", "method", "-", "generic", "type", "variables", "at", "a", "callsite", ".", "When", "inference", "is", "not", "possible", "for", "a", "given", "type", "variable", "that", "type", "variable", "is", "not", "included", "in", "the", "resulting", "map", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java#L53-L64
21,844
google/error-prone
check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java
InferredNullability.getExprNullness
public Optional<Nullness> getExprNullness(ExpressionTree exprTree) { InferenceVariable iv = TypeArgInferenceVar.create(ImmutableList.of(), exprTree); return constraintGraph.nodes().contains(iv) ? getNullness(iv) : Optional.empty(); }
java
public Optional<Nullness> getExprNullness(ExpressionTree exprTree) { InferenceVariable iv = TypeArgInferenceVar.create(ImmutableList.of(), exprTree); return constraintGraph.nodes().contains(iv) ? getNullness(iv) : Optional.empty(); }
[ "public", "Optional", "<", "Nullness", ">", "getExprNullness", "(", "ExpressionTree", "exprTree", ")", "{", "InferenceVariable", "iv", "=", "TypeArgInferenceVar", ".", "create", "(", "ImmutableList", ".", "of", "(", ")", ",", "exprTree", ")", ";", "return", "constraintGraph", ".", "nodes", "(", ")", ".", "contains", "(", "iv", ")", "?", "getNullness", "(", "iv", ")", ":", "Optional", ".", "empty", "(", ")", ";", "}" ]
Get inferred nullness qualifier for an expression, if possible.
[ "Get", "inferred", "nullness", "qualifier", "for", "an", "expression", "if", "possible", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java#L67-L70
21,845
chanjarster/weixin-java-tools
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java
XStreamTransformer.fromXml
@SuppressWarnings("unchecked") public static <T> T fromXml(Class<T> clazz, String xml) { T object = (T) CLASS_2_XSTREAM_INSTANCE.get(clazz).fromXML(xml); return object; }
java
@SuppressWarnings("unchecked") public static <T> T fromXml(Class<T> clazz, String xml) { T object = (T) CLASS_2_XSTREAM_INSTANCE.get(clazz).fromXML(xml); return object; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "fromXml", "(", "Class", "<", "T", ">", "clazz", ",", "String", "xml", ")", "{", "T", "object", "=", "(", "T", ")", "CLASS_2_XSTREAM_INSTANCE", ".", "get", "(", "clazz", ")", ".", "fromXML", "(", "xml", ")", ";", "return", "object", ";", "}" ]
xml -> pojo @param clazz @param xml @return
[ "xml", "-", ">", "pojo" ]
2a0b1c30c0f60c2de466cb8933c945bc0d391edf
https://github.com/chanjarster/weixin-java-tools/blob/2a0b1c30c0f60c2de466cb8933c945bc0d391edf/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java#L22-L26
21,846
chanjarster/weixin-java-tools
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java
XStreamTransformer.toXml
public static <T> String toXml(Class<T> clazz, T object) { return CLASS_2_XSTREAM_INSTANCE.get(clazz).toXML(object); }
java
public static <T> String toXml(Class<T> clazz, T object) { return CLASS_2_XSTREAM_INSTANCE.get(clazz).toXML(object); }
[ "public", "static", "<", "T", ">", "String", "toXml", "(", "Class", "<", "T", ">", "clazz", ",", "T", "object", ")", "{", "return", "CLASS_2_XSTREAM_INSTANCE", ".", "get", "(", "clazz", ")", ".", "toXML", "(", "object", ")", ";", "}" ]
pojo -> xml @param clazz @param object @return
[ "pojo", "-", ">", "xml" ]
2a0b1c30c0f60c2de466cb8933c945bc0d391edf
https://github.com/chanjarster/weixin-java-tools/blob/2a0b1c30c0f60c2de466cb8933c945bc0d391edf/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java#L41-L43
21,847
chanjarster/weixin-java-tools
weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java
StandardSessionManager.processExpires
public void processExpires() { long timeNow = System.currentTimeMillis(); InternalSession sessions[] = findSessions(); int expireHere = 0 ; if(log.isDebugEnabled()) log.debug("Start expire sessions {} at {} sessioncount {}", getName(), timeNow, sessions.length); for (int i = 0; i < sessions.length; i++) { if (sessions[i]!=null && !sessions[i].isValid()) { expireHere++; } } long timeEnd = System.currentTimeMillis(); if(log.isDebugEnabled()) log.debug("End expire sessions {} processingTime {} expired sessions: {}", getName(), timeEnd - timeNow, expireHere); processingTime += ( timeEnd - timeNow ); }
java
public void processExpires() { long timeNow = System.currentTimeMillis(); InternalSession sessions[] = findSessions(); int expireHere = 0 ; if(log.isDebugEnabled()) log.debug("Start expire sessions {} at {} sessioncount {}", getName(), timeNow, sessions.length); for (int i = 0; i < sessions.length; i++) { if (sessions[i]!=null && !sessions[i].isValid()) { expireHere++; } } long timeEnd = System.currentTimeMillis(); if(log.isDebugEnabled()) log.debug("End expire sessions {} processingTime {} expired sessions: {}", getName(), timeEnd - timeNow, expireHere); processingTime += ( timeEnd - timeNow ); }
[ "public", "void", "processExpires", "(", ")", "{", "long", "timeNow", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "InternalSession", "sessions", "[", "]", "=", "findSessions", "(", ")", ";", "int", "expireHere", "=", "0", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"Start expire sessions {} at {} sessioncount {}\"", ",", "getName", "(", ")", ",", "timeNow", ",", "sessions", ".", "length", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sessions", ".", "length", ";", "i", "++", ")", "{", "if", "(", "sessions", "[", "i", "]", "!=", "null", "&&", "!", "sessions", "[", "i", "]", ".", "isValid", "(", ")", ")", "{", "expireHere", "++", ";", "}", "}", "long", "timeEnd", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"End expire sessions {} processingTime {} expired sessions: {}\"", ",", "getName", "(", ")", ",", "timeEnd", "-", "timeNow", ",", "expireHere", ")", ";", "processingTime", "+=", "(", "timeEnd", "-", "timeNow", ")", ";", "}" ]
Invalidate all sessions that have expired.
[ "Invalidate", "all", "sessions", "that", "have", "expired", "." ]
2a0b1c30c0f60c2de466cb8933c945bc0d391edf
https://github.com/chanjarster/weixin-java-tools/blob/2a0b1c30c0f60c2de466cb8933c945bc0d391edf/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java#L250-L268
21,848
chanjarster/weixin-java-tools
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java
StringManager.getString
public String getString(final String key, final Object... args) { String value = getString(key); if (value == null) { value = key; } MessageFormat mf = new MessageFormat(value); mf.setLocale(locale); return mf.format(args, new StringBuffer(), null).toString(); }
java
public String getString(final String key, final Object... args) { String value = getString(key); if (value == null) { value = key; } MessageFormat mf = new MessageFormat(value); mf.setLocale(locale); return mf.format(args, new StringBuffer(), null).toString(); }
[ "public", "String", "getString", "(", "final", "String", "key", ",", "final", "Object", "...", "args", ")", "{", "String", "value", "=", "getString", "(", "key", ")", ";", "if", "(", "value", "==", "null", ")", "{", "value", "=", "key", ";", "}", "MessageFormat", "mf", "=", "new", "MessageFormat", "(", "value", ")", ";", "mf", ".", "setLocale", "(", "locale", ")", ";", "return", "mf", ".", "format", "(", "args", ",", "new", "StringBuffer", "(", ")", ",", "null", ")", ".", "toString", "(", ")", ";", "}" ]
Get a string from the underlying resource bundle and format it with the given set of arguments. @param key @param args
[ "Get", "a", "string", "from", "the", "underlying", "resource", "bundle", "and", "format", "it", "with", "the", "given", "set", "of", "arguments", "." ]
2a0b1c30c0f60c2de466cb8933c945bc0d391edf
https://github.com/chanjarster/weixin-java-tools/blob/2a0b1c30c0f60c2de466cb8933c945bc0d391edf/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java#L151-L160
21,849
JohnSnowLabs/spark-nlp
src/main/scala/com/johnsnowlabs/nlp/annotators/parser/typdep/util/Alphabet.java
Alphabet.lookupIndex
public int lookupIndex (long entry) { int ret = map.get(entry); if (ret <= 0 && !growthStopped) { numEntries++; ret = numEntries; map.put (entry, ret); } return ret - 1; // feature id should be 0-based }
java
public int lookupIndex (long entry) { int ret = map.get(entry); if (ret <= 0 && !growthStopped) { numEntries++; ret = numEntries; map.put (entry, ret); } return ret - 1; // feature id should be 0-based }
[ "public", "int", "lookupIndex", "(", "long", "entry", ")", "{", "int", "ret", "=", "map", ".", "get", "(", "entry", ")", ";", "if", "(", "ret", "<=", "0", "&&", "!", "growthStopped", ")", "{", "numEntries", "++", ";", "ret", "=", "numEntries", ";", "map", ".", "put", "(", "entry", ",", "ret", ")", ";", "}", "return", "ret", "-", "1", ";", "// feature id should be 0-based", "}" ]
Return -1 if entry isn't present.
[ "Return", "-", "1", "if", "entry", "isn", "t", "present", "." ]
cf6c7a86e044b82f7690157c195f77874858bb00
https://github.com/JohnSnowLabs/spark-nlp/blob/cf6c7a86e044b82f7690157c195f77874858bb00/src/main/scala/com/johnsnowlabs/nlp/annotators/parser/typdep/util/Alphabet.java#L39-L48
21,850
huaban/jieba-analysis
src/main/java/com/huaban/analysis/jieba/WordDictionary.java
WordDictionary.init
public void init(Path configFile) { String abspath = configFile.toAbsolutePath().toString(); System.out.println("initialize user dictionary:" + abspath); synchronized (WordDictionary.class) { if (loadedPath.contains(abspath)) return; DirectoryStream<Path> stream; try { stream = Files.newDirectoryStream(configFile, String.format(Locale.getDefault(), "*%s", USER_DICT_SUFFIX)); for (Path path: stream){ System.err.println(String.format(Locale.getDefault(), "loading dict %s", path.toString())); singleton.loadUserDict(path); } loadedPath.add(abspath); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); System.err.println(String.format(Locale.getDefault(), "%s: load user dict failure!", configFile.toString())); } } }
java
public void init(Path configFile) { String abspath = configFile.toAbsolutePath().toString(); System.out.println("initialize user dictionary:" + abspath); synchronized (WordDictionary.class) { if (loadedPath.contains(abspath)) return; DirectoryStream<Path> stream; try { stream = Files.newDirectoryStream(configFile, String.format(Locale.getDefault(), "*%s", USER_DICT_SUFFIX)); for (Path path: stream){ System.err.println(String.format(Locale.getDefault(), "loading dict %s", path.toString())); singleton.loadUserDict(path); } loadedPath.add(abspath); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); System.err.println(String.format(Locale.getDefault(), "%s: load user dict failure!", configFile.toString())); } } }
[ "public", "void", "init", "(", "Path", "configFile", ")", "{", "String", "abspath", "=", "configFile", ".", "toAbsolutePath", "(", ")", ".", "toString", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"initialize user dictionary:\"", "+", "abspath", ")", ";", "synchronized", "(", "WordDictionary", ".", "class", ")", "{", "if", "(", "loadedPath", ".", "contains", "(", "abspath", ")", ")", "return", ";", "DirectoryStream", "<", "Path", ">", "stream", ";", "try", "{", "stream", "=", "Files", ".", "newDirectoryStream", "(", "configFile", ",", "String", ".", "format", "(", "Locale", ".", "getDefault", "(", ")", ",", "\"*%s\"", ",", "USER_DICT_SUFFIX", ")", ")", ";", "for", "(", "Path", "path", ":", "stream", ")", "{", "System", ".", "err", ".", "println", "(", "String", ".", "format", "(", "Locale", ".", "getDefault", "(", ")", ",", "\"loading dict %s\"", ",", "path", ".", "toString", "(", ")", ")", ")", ";", "singleton", ".", "loadUserDict", "(", "path", ")", ";", "}", "loadedPath", ".", "add", "(", "abspath", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// TODO Auto-generated catch block", "// e.printStackTrace();", "System", ".", "err", ".", "println", "(", "String", ".", "format", "(", "Locale", ".", "getDefault", "(", ")", ",", "\"%s: load user dict failure!\"", ",", "configFile", ".", "toString", "(", ")", ")", ")", ";", "}", "}", "}" ]
for ES to initialize the user dictionary. @param configFile
[ "for", "ES", "to", "initialize", "the", "user", "dictionary", "." ]
57d2733a9a3b0adc1eda2fbf827fd270153110f4
https://github.com/huaban/jieba-analysis/blob/57d2733a9a3b0adc1eda2fbf827fd270153110f4/src/main/java/com/huaban/analysis/jieba/WordDictionary.java#L55-L76
21,851
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferReverseIntIteratorFlyweight.java
BufferReverseIntIteratorFlyweight.wrap
public void wrap(ImmutableRoaringBitmap r) { this.roaringBitmap = r; this.hs = 0; this.pos = (short) (this.roaringBitmap.highLowContainer.size() - 1); this.nextContainer(); }
java
public void wrap(ImmutableRoaringBitmap r) { this.roaringBitmap = r; this.hs = 0; this.pos = (short) (this.roaringBitmap.highLowContainer.size() - 1); this.nextContainer(); }
[ "public", "void", "wrap", "(", "ImmutableRoaringBitmap", "r", ")", "{", "this", ".", "roaringBitmap", "=", "r", ";", "this", ".", "hs", "=", "0", ";", "this", ".", "pos", "=", "(", "short", ")", "(", "this", ".", "roaringBitmap", ".", "highLowContainer", ".", "size", "(", ")", "-", "1", ")", ";", "this", ".", "nextContainer", "(", ")", ";", "}" ]
Prepares a bitmap for iteration @param r bitmap to be iterated over
[ "Prepares", "a", "bitmap", "for", "iteration" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferReverseIntIteratorFlyweight.java#L111-L116
21,852
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.appendCopy
protected void appendCopy(RoaringArray sa, int index) { extendArray(1); this.keys[this.size] = sa.keys[index]; this.values[this.size] = sa.values[index].clone(); this.size++; }
java
protected void appendCopy(RoaringArray sa, int index) { extendArray(1); this.keys[this.size] = sa.keys[index]; this.values[this.size] = sa.values[index].clone(); this.size++; }
[ "protected", "void", "appendCopy", "(", "RoaringArray", "sa", ",", "int", "index", ")", "{", "extendArray", "(", "1", ")", ";", "this", ".", "keys", "[", "this", ".", "size", "]", "=", "sa", ".", "keys", "[", "index", "]", ";", "this", ".", "values", "[", "this", ".", "size", "]", "=", "sa", ".", "values", "[", "index", "]", ".", "clone", "(", ")", ";", "this", ".", "size", "++", ";", "}" ]
Append copy of the one value from another array @param sa other array @param index index in the other array
[ "Append", "copy", "of", "the", "one", "value", "from", "another", "array" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L194-L199
21,853
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.extendArray
protected void extendArray(int k) { // size + 1 could overflow if (this.size + k > this.keys.length) { int newCapacity; if (this.keys.length < 1024) { newCapacity = 2 * (this.size + k); } else { newCapacity = 5 * (this.size + k) / 4; } this.keys = Arrays.copyOf(this.keys, newCapacity); this.values = Arrays.copyOf(this.values, newCapacity); } }
java
protected void extendArray(int k) { // size + 1 could overflow if (this.size + k > this.keys.length) { int newCapacity; if (this.keys.length < 1024) { newCapacity = 2 * (this.size + k); } else { newCapacity = 5 * (this.size + k) / 4; } this.keys = Arrays.copyOf(this.keys, newCapacity); this.values = Arrays.copyOf(this.values, newCapacity); } }
[ "protected", "void", "extendArray", "(", "int", "k", ")", "{", "// size + 1 could overflow", "if", "(", "this", ".", "size", "+", "k", ">", "this", ".", "keys", ".", "length", ")", "{", "int", "newCapacity", ";", "if", "(", "this", ".", "keys", ".", "length", "<", "1024", ")", "{", "newCapacity", "=", "2", "*", "(", "this", ".", "size", "+", "k", ")", ";", "}", "else", "{", "newCapacity", "=", "5", "*", "(", "this", ".", "size", "+", "k", ")", "/", "4", ";", "}", "this", ".", "keys", "=", "Arrays", ".", "copyOf", "(", "this", ".", "keys", ",", "newCapacity", ")", ";", "this", ".", "values", "=", "Arrays", ".", "copyOf", "(", "this", ".", "values", ",", "newCapacity", ")", ";", "}", "}" ]
make sure there is capacity for at least k more elements
[ "make", "sure", "there", "is", "capacity", "for", "at", "least", "k", "more", "elements" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L662-L674
21,854
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.getContainerPointer
public ContainerPointer getContainerPointer(final int startIndex) { return new ContainerPointer() { int k = startIndex; @Override public void advance() { ++k; } @Override public ContainerPointer clone() { try { return (ContainerPointer) super.clone(); } catch (CloneNotSupportedException e) { return null;// will not happen } } @Override public int compareTo(ContainerPointer o) { if (key() != o.key()) { return Util.toIntUnsigned(key()) - Util.toIntUnsigned(o.key()); } return o.getCardinality() - getCardinality(); } @Override public int getCardinality() { return getContainer().getCardinality(); } @Override public Container getContainer() { if (k >= RoaringArray.this.size) { return null; } return RoaringArray.this.values[k]; } @Override public boolean isBitmapContainer() { return getContainer() instanceof BitmapContainer; } @Override public boolean isRunContainer() { return getContainer() instanceof RunContainer; } @Override public short key() { return RoaringArray.this.keys[k]; } }; }
java
public ContainerPointer getContainerPointer(final int startIndex) { return new ContainerPointer() { int k = startIndex; @Override public void advance() { ++k; } @Override public ContainerPointer clone() { try { return (ContainerPointer) super.clone(); } catch (CloneNotSupportedException e) { return null;// will not happen } } @Override public int compareTo(ContainerPointer o) { if (key() != o.key()) { return Util.toIntUnsigned(key()) - Util.toIntUnsigned(o.key()); } return o.getCardinality() - getCardinality(); } @Override public int getCardinality() { return getContainer().getCardinality(); } @Override public Container getContainer() { if (k >= RoaringArray.this.size) { return null; } return RoaringArray.this.values[k]; } @Override public boolean isBitmapContainer() { return getContainer() instanceof BitmapContainer; } @Override public boolean isRunContainer() { return getContainer() instanceof RunContainer; } @Override public short key() { return RoaringArray.this.keys[k]; } }; }
[ "public", "ContainerPointer", "getContainerPointer", "(", "final", "int", "startIndex", ")", "{", "return", "new", "ContainerPointer", "(", ")", "{", "int", "k", "=", "startIndex", ";", "@", "Override", "public", "void", "advance", "(", ")", "{", "++", "k", ";", "}", "@", "Override", "public", "ContainerPointer", "clone", "(", ")", "{", "try", "{", "return", "(", "ContainerPointer", ")", "super", ".", "clone", "(", ")", ";", "}", "catch", "(", "CloneNotSupportedException", "e", ")", "{", "return", "null", ";", "// will not happen", "}", "}", "@", "Override", "public", "int", "compareTo", "(", "ContainerPointer", "o", ")", "{", "if", "(", "key", "(", ")", "!=", "o", ".", "key", "(", ")", ")", "{", "return", "Util", ".", "toIntUnsigned", "(", "key", "(", ")", ")", "-", "Util", ".", "toIntUnsigned", "(", "o", ".", "key", "(", ")", ")", ";", "}", "return", "o", ".", "getCardinality", "(", ")", "-", "getCardinality", "(", ")", ";", "}", "@", "Override", "public", "int", "getCardinality", "(", ")", "{", "return", "getContainer", "(", ")", ".", "getCardinality", "(", ")", ";", "}", "@", "Override", "public", "Container", "getContainer", "(", ")", "{", "if", "(", "k", ">=", "RoaringArray", ".", "this", ".", "size", ")", "{", "return", "null", ";", "}", "return", "RoaringArray", ".", "this", ".", "values", "[", "k", "]", ";", "}", "@", "Override", "public", "boolean", "isBitmapContainer", "(", ")", "{", "return", "getContainer", "(", ")", "instanceof", "BitmapContainer", ";", "}", "@", "Override", "public", "boolean", "isRunContainer", "(", ")", "{", "return", "getContainer", "(", ")", "instanceof", "RunContainer", ";", "}", "@", "Override", "public", "short", "key", "(", ")", "{", "return", "RoaringArray", ".", "this", ".", "keys", "[", "k", "]", ";", "}", "}", ";", "}" ]
Create a ContainerPointer for this RoaringArray @param startIndex starting index in the container list @return a ContainerPointer
[ "Create", "a", "ContainerPointer", "for", "this", "RoaringArray" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L702-L760
21,855
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.insertNewKeyValueAt
protected void insertNewKeyValueAt(int i, short key, Container value) { extendArray(1); System.arraycopy(keys, i, keys, i + 1, size - i); keys[i] = key; System.arraycopy(values, i, values, i + 1, size - i); values[i] = value; size++; }
java
protected void insertNewKeyValueAt(int i, short key, Container value) { extendArray(1); System.arraycopy(keys, i, keys, i + 1, size - i); keys[i] = key; System.arraycopy(values, i, values, i + 1, size - i); values[i] = value; size++; }
[ "protected", "void", "insertNewKeyValueAt", "(", "int", "i", ",", "short", "key", ",", "Container", "value", ")", "{", "extendArray", "(", "1", ")", ";", "System", ".", "arraycopy", "(", "keys", ",", "i", ",", "keys", ",", "i", "+", "1", ",", "size", "-", "i", ")", ";", "keys", "[", "i", "]", "=", "key", ";", "System", ".", "arraycopy", "(", "values", ",", "i", ",", "values", ",", "i", "+", "1", ",", "size", "-", "i", ")", ";", "values", "[", "i", "]", "=", "value", ";", "size", "++", ";", "}" ]
insert a new key, it is assumed that it does not exist
[ "insert", "a", "new", "key", "it", "is", "assumed", "that", "it", "does", "not", "exist" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L808-L815
21,856
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.first
public int first() { assertNonEmpty(); short firstKey = keys[0]; Container container = values[0]; return firstKey << 16 | container.first(); }
java
public int first() { assertNonEmpty(); short firstKey = keys[0]; Container container = values[0]; return firstKey << 16 | container.first(); }
[ "public", "int", "first", "(", ")", "{", "assertNonEmpty", "(", ")", ";", "short", "firstKey", "=", "keys", "[", "0", "]", ";", "Container", "container", "=", "values", "[", "0", "]", ";", "return", "firstKey", "<<", "16", "|", "container", ".", "first", "(", ")", ";", "}" ]
Gets the first value in the array @return the first value in the array @throws NoSuchElementException if empty
[ "Gets", "the", "first", "value", "in", "the", "array" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L987-L992
21,857
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.last
public int last() { assertNonEmpty(); short lastKey = keys[size - 1]; Container container = values[size - 1]; return lastKey << 16 | container.last(); }
java
public int last() { assertNonEmpty(); short lastKey = keys[size - 1]; Container container = values[size - 1]; return lastKey << 16 | container.last(); }
[ "public", "int", "last", "(", ")", "{", "assertNonEmpty", "(", ")", ";", "short", "lastKey", "=", "keys", "[", "size", "-", "1", "]", ";", "Container", "container", "=", "values", "[", "size", "-", "1", "]", ";", "return", "lastKey", "<<", "16", "|", "container", ".", "last", "(", ")", ";", "}" ]
Gets the last value in the array @return the last value in the array @throws NoSuchElementException if empty
[ "Gets", "the", "last", "value", "in", "the", "array" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L999-L1004
21,858
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
Roaring64NavigableMap.select
@Override public long select(final long j) throws IllegalArgumentException { if (!doCacheCardinalities) { return selectNoCache(j); } // Ensure all cumulatives as we we have straightforward way to know in advance the high of the // j-th value int indexOk = ensureCumulatives(highestHigh()); if (highToBitmap.isEmpty()) { return throwSelectInvalidIndex(j); } // Use normal binarySearch as cardinality does not depends on considering longs signed or // unsigned // We need sortedCumulatedCardinality not to contain duplicated, else binarySearch may return // any of the duplicates: we need to ensure it holds no high associated to an empty bitmap int position = Arrays.binarySearch(sortedCumulatedCardinality, 0, indexOk, j); if (position >= 0) { if (position == indexOk - 1) { // .select has been called on this.getCardinality return throwSelectInvalidIndex(j); } // There is a bucket leading to this cardinality: the j-th element is the first element of // next bucket int high = sortedHighs[position + 1]; BitmapDataProvider nextBitmap = highToBitmap.get(high); return RoaringIntPacking.pack(high, nextBitmap.select(0)); } else { // There is no bucket with this cardinality int insertionPoint = -position - 1; final long previousBucketCardinality; if (insertionPoint == 0) { previousBucketCardinality = 0L; } else if (insertionPoint >= indexOk) { return throwSelectInvalidIndex(j); } else { previousBucketCardinality = sortedCumulatedCardinality[insertionPoint - 1]; } // We get a 'select' query for a single bitmap: should fit in an int final int givenBitmapSelect = (int) (j - previousBucketCardinality); int high = sortedHighs[insertionPoint]; BitmapDataProvider lowBitmap = highToBitmap.get(high); int low = lowBitmap.select(givenBitmapSelect); return RoaringIntPacking.pack(high, low); } }
java
@Override public long select(final long j) throws IllegalArgumentException { if (!doCacheCardinalities) { return selectNoCache(j); } // Ensure all cumulatives as we we have straightforward way to know in advance the high of the // j-th value int indexOk = ensureCumulatives(highestHigh()); if (highToBitmap.isEmpty()) { return throwSelectInvalidIndex(j); } // Use normal binarySearch as cardinality does not depends on considering longs signed or // unsigned // We need sortedCumulatedCardinality not to contain duplicated, else binarySearch may return // any of the duplicates: we need to ensure it holds no high associated to an empty bitmap int position = Arrays.binarySearch(sortedCumulatedCardinality, 0, indexOk, j); if (position >= 0) { if (position == indexOk - 1) { // .select has been called on this.getCardinality return throwSelectInvalidIndex(j); } // There is a bucket leading to this cardinality: the j-th element is the first element of // next bucket int high = sortedHighs[position + 1]; BitmapDataProvider nextBitmap = highToBitmap.get(high); return RoaringIntPacking.pack(high, nextBitmap.select(0)); } else { // There is no bucket with this cardinality int insertionPoint = -position - 1; final long previousBucketCardinality; if (insertionPoint == 0) { previousBucketCardinality = 0L; } else if (insertionPoint >= indexOk) { return throwSelectInvalidIndex(j); } else { previousBucketCardinality = sortedCumulatedCardinality[insertionPoint - 1]; } // We get a 'select' query for a single bitmap: should fit in an int final int givenBitmapSelect = (int) (j - previousBucketCardinality); int high = sortedHighs[insertionPoint]; BitmapDataProvider lowBitmap = highToBitmap.get(high); int low = lowBitmap.select(givenBitmapSelect); return RoaringIntPacking.pack(high, low); } }
[ "@", "Override", "public", "long", "select", "(", "final", "long", "j", ")", "throws", "IllegalArgumentException", "{", "if", "(", "!", "doCacheCardinalities", ")", "{", "return", "selectNoCache", "(", "j", ")", ";", "}", "// Ensure all cumulatives as we we have straightforward way to know in advance the high of the", "// j-th value", "int", "indexOk", "=", "ensureCumulatives", "(", "highestHigh", "(", ")", ")", ";", "if", "(", "highToBitmap", ".", "isEmpty", "(", ")", ")", "{", "return", "throwSelectInvalidIndex", "(", "j", ")", ";", "}", "// Use normal binarySearch as cardinality does not depends on considering longs signed or", "// unsigned", "// We need sortedCumulatedCardinality not to contain duplicated, else binarySearch may return", "// any of the duplicates: we need to ensure it holds no high associated to an empty bitmap", "int", "position", "=", "Arrays", ".", "binarySearch", "(", "sortedCumulatedCardinality", ",", "0", ",", "indexOk", ",", "j", ")", ";", "if", "(", "position", ">=", "0", ")", "{", "if", "(", "position", "==", "indexOk", "-", "1", ")", "{", "// .select has been called on this.getCardinality", "return", "throwSelectInvalidIndex", "(", "j", ")", ";", "}", "// There is a bucket leading to this cardinality: the j-th element is the first element of", "// next bucket", "int", "high", "=", "sortedHighs", "[", "position", "+", "1", "]", ";", "BitmapDataProvider", "nextBitmap", "=", "highToBitmap", ".", "get", "(", "high", ")", ";", "return", "RoaringIntPacking", ".", "pack", "(", "high", ",", "nextBitmap", ".", "select", "(", "0", ")", ")", ";", "}", "else", "{", "// There is no bucket with this cardinality", "int", "insertionPoint", "=", "-", "position", "-", "1", ";", "final", "long", "previousBucketCardinality", ";", "if", "(", "insertionPoint", "==", "0", ")", "{", "previousBucketCardinality", "=", "0L", ";", "}", "else", "if", "(", "insertionPoint", ">=", "indexOk", ")", "{", "return", "throwSelectInvalidIndex", "(", "j", ")", ";", "}", "else", "{", "previousBucketCardinality", "=", "sortedCumulatedCardinality", "[", "insertionPoint", "-", "1", "]", ";", "}", "// We get a 'select' query for a single bitmap: should fit in an int", "final", "int", "givenBitmapSelect", "=", "(", "int", ")", "(", "j", "-", "previousBucketCardinality", ")", ";", "int", "high", "=", "sortedHighs", "[", "insertionPoint", "]", ";", "BitmapDataProvider", "lowBitmap", "=", "highToBitmap", ".", "get", "(", "high", ")", ";", "int", "low", "=", "lowBitmap", ".", "select", "(", "givenBitmapSelect", ")", ";", "return", "RoaringIntPacking", ".", "pack", "(", "high", ",", "low", ")", ";", "}", "}" ]
Return the jth value stored in this bitmap. @param j index of the value @return the value @throws IllegalArgumentException if j is out of the bounds of the bitmap cardinality
[ "Return", "the", "jth", "value", "stored", "in", "this", "bitmap", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java#L340-L393
21,859
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
Roaring64NavigableMap.serialize
@Override public void serialize(DataOutput out) throws IOException { // TODO: Should we transport the performance tweak 'doCacheCardinalities'? out.writeBoolean(signedLongs); out.writeInt(highToBitmap.size()); for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { out.writeInt(entry.getKey().intValue()); entry.getValue().serialize(out); } }
java
@Override public void serialize(DataOutput out) throws IOException { // TODO: Should we transport the performance tweak 'doCacheCardinalities'? out.writeBoolean(signedLongs); out.writeInt(highToBitmap.size()); for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { out.writeInt(entry.getKey().intValue()); entry.getValue().serialize(out); } }
[ "@", "Override", "public", "void", "serialize", "(", "DataOutput", "out", ")", "throws", "IOException", "{", "// TODO: Should we transport the performance tweak 'doCacheCardinalities'?", "out", ".", "writeBoolean", "(", "signedLongs", ")", ";", "out", ".", "writeInt", "(", "highToBitmap", ".", "size", "(", ")", ")", ";", "for", "(", "Entry", "<", "Integer", ",", "BitmapDataProvider", ">", "entry", ":", "highToBitmap", ".", "entrySet", "(", ")", ")", "{", "out", ".", "writeInt", "(", "entry", ".", "getKey", "(", ")", ".", "intValue", "(", ")", ")", ";", "entry", ".", "getValue", "(", ")", ".", "serialize", "(", "out", ")", ";", "}", "}" ]
Serialize this bitmap. Unlike RoaringBitmap, there is no specification for now: it may change from onve java version to another, and from one RoaringBitmap version to another. Consider calling {@link #runOptimize} before serialization to improve compression. The current bitmap is not modified. @param out the DataOutput stream @throws IOException Signals that an I/O exception has occurred.
[ "Serialize", "this", "bitmap", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java#L1123-L1134
21,860
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
Roaring64NavigableMap.toArray
@Override public long[] toArray() { long cardinality = this.getLongCardinality(); if (cardinality > Integer.MAX_VALUE) { throw new IllegalStateException("The cardinality does not fit in an array"); } final long[] array = new long[(int) cardinality]; int pos = 0; LongIterator it = getLongIterator(); while (it.hasNext()) { array[pos++] = it.next(); } return array; }
java
@Override public long[] toArray() { long cardinality = this.getLongCardinality(); if (cardinality > Integer.MAX_VALUE) { throw new IllegalStateException("The cardinality does not fit in an array"); } final long[] array = new long[(int) cardinality]; int pos = 0; LongIterator it = getLongIterator(); while (it.hasNext()) { array[pos++] = it.next(); } return array; }
[ "@", "Override", "public", "long", "[", "]", "toArray", "(", ")", "{", "long", "cardinality", "=", "this", ".", "getLongCardinality", "(", ")", ";", "if", "(", "cardinality", ">", "Integer", ".", "MAX_VALUE", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The cardinality does not fit in an array\"", ")", ";", "}", "final", "long", "[", "]", "array", "=", "new", "long", "[", "(", "int", ")", "cardinality", "]", ";", "int", "pos", "=", "0", ";", "LongIterator", "it", "=", "getLongIterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "array", "[", "pos", "++", "]", "=", "it", ".", "next", "(", ")", ";", "}", "return", "array", ";", "}" ]
Return the set values as an array, if the cardinality is smaller than 2147483648. The long values are in sorted order. @return array representing the set values.
[ "Return", "the", "set", "values", "as", "an", "array", "if", "the", "cardinality", "is", "smaller", "than", "2147483648", ".", "The", "long", "values", "are", "in", "sorted", "order", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java#L1209-L1225
21,861
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
Roaring64NavigableMap.bitmapOf
public static Roaring64NavigableMap bitmapOf(final long... dat) { final Roaring64NavigableMap ans = new Roaring64NavigableMap(); ans.add(dat); return ans; }
java
public static Roaring64NavigableMap bitmapOf(final long... dat) { final Roaring64NavigableMap ans = new Roaring64NavigableMap(); ans.add(dat); return ans; }
[ "public", "static", "Roaring64NavigableMap", "bitmapOf", "(", "final", "long", "...", "dat", ")", "{", "final", "Roaring64NavigableMap", "ans", "=", "new", "Roaring64NavigableMap", "(", ")", ";", "ans", ".", "add", "(", "dat", ")", ";", "return", "ans", ";", "}" ]
Generate a bitmap with the specified values set to true. The provided longs values don't have to be in sorted order, but it may be preferable to sort them from a performance point of view. @param dat set values @return a new bitmap
[ "Generate", "a", "bitmap", "with", "the", "specified", "values", "set", "to", "true", ".", "The", "provided", "longs", "values", "don", "t", "have", "to", "be", "in", "sorted", "order", "but", "it", "may", "be", "preferable", "to", "sort", "them", "from", "a", "performance", "point", "of", "view", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java#L1234-L1238
21,862
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
Roaring64NavigableMap.add
public void add(final long rangeStart, final long rangeEnd) { int startHigh = high(rangeStart); int startLow = low(rangeStart); int endHigh = high(rangeEnd); int endLow = low(rangeEnd); for (int high = startHigh; high <= endHigh; high++) { final int currentStartLow; if (startHigh == high) { // The whole range starts in this bucket currentStartLow = startLow; } else { // Add the bucket from the beginning currentStartLow = 0; } long startLowAsLong = Util.toUnsignedLong(currentStartLow); final long endLowAsLong; if (endHigh == high) { // The whole range ends in this bucket endLowAsLong = Util.toUnsignedLong(endLow); } else { // Add the bucket until the end: we have a +1 as, in RoaringBitmap.add(long,long), the end // is excluded endLowAsLong = Util.toUnsignedLong(-1) + 1; } if (endLowAsLong > startLowAsLong) { // Initialize the bitmap only if there is access data to write BitmapDataProvider bitmap = highToBitmap.get(high); if (bitmap == null) { bitmap = new MutableRoaringBitmap(); pushBitmapForHigh(high, bitmap); } if (bitmap instanceof RoaringBitmap) { ((RoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); } else if (bitmap instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); } else { throw new UnsupportedOperationException("TODO. Not for " + bitmap.getClass()); } } } invalidateAboveHigh(startHigh); }
java
public void add(final long rangeStart, final long rangeEnd) { int startHigh = high(rangeStart); int startLow = low(rangeStart); int endHigh = high(rangeEnd); int endLow = low(rangeEnd); for (int high = startHigh; high <= endHigh; high++) { final int currentStartLow; if (startHigh == high) { // The whole range starts in this bucket currentStartLow = startLow; } else { // Add the bucket from the beginning currentStartLow = 0; } long startLowAsLong = Util.toUnsignedLong(currentStartLow); final long endLowAsLong; if (endHigh == high) { // The whole range ends in this bucket endLowAsLong = Util.toUnsignedLong(endLow); } else { // Add the bucket until the end: we have a +1 as, in RoaringBitmap.add(long,long), the end // is excluded endLowAsLong = Util.toUnsignedLong(-1) + 1; } if (endLowAsLong > startLowAsLong) { // Initialize the bitmap only if there is access data to write BitmapDataProvider bitmap = highToBitmap.get(high); if (bitmap == null) { bitmap = new MutableRoaringBitmap(); pushBitmapForHigh(high, bitmap); } if (bitmap instanceof RoaringBitmap) { ((RoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); } else if (bitmap instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); } else { throw new UnsupportedOperationException("TODO. Not for " + bitmap.getClass()); } } } invalidateAboveHigh(startHigh); }
[ "public", "void", "add", "(", "final", "long", "rangeStart", ",", "final", "long", "rangeEnd", ")", "{", "int", "startHigh", "=", "high", "(", "rangeStart", ")", ";", "int", "startLow", "=", "low", "(", "rangeStart", ")", ";", "int", "endHigh", "=", "high", "(", "rangeEnd", ")", ";", "int", "endLow", "=", "low", "(", "rangeEnd", ")", ";", "for", "(", "int", "high", "=", "startHigh", ";", "high", "<=", "endHigh", ";", "high", "++", ")", "{", "final", "int", "currentStartLow", ";", "if", "(", "startHigh", "==", "high", ")", "{", "// The whole range starts in this bucket", "currentStartLow", "=", "startLow", ";", "}", "else", "{", "// Add the bucket from the beginning", "currentStartLow", "=", "0", ";", "}", "long", "startLowAsLong", "=", "Util", ".", "toUnsignedLong", "(", "currentStartLow", ")", ";", "final", "long", "endLowAsLong", ";", "if", "(", "endHigh", "==", "high", ")", "{", "// The whole range ends in this bucket", "endLowAsLong", "=", "Util", ".", "toUnsignedLong", "(", "endLow", ")", ";", "}", "else", "{", "// Add the bucket until the end: we have a +1 as, in RoaringBitmap.add(long,long), the end", "// is excluded", "endLowAsLong", "=", "Util", ".", "toUnsignedLong", "(", "-", "1", ")", "+", "1", ";", "}", "if", "(", "endLowAsLong", ">", "startLowAsLong", ")", "{", "// Initialize the bitmap only if there is access data to write", "BitmapDataProvider", "bitmap", "=", "highToBitmap", ".", "get", "(", "high", ")", ";", "if", "(", "bitmap", "==", "null", ")", "{", "bitmap", "=", "new", "MutableRoaringBitmap", "(", ")", ";", "pushBitmapForHigh", "(", "high", ",", "bitmap", ")", ";", "}", "if", "(", "bitmap", "instanceof", "RoaringBitmap", ")", "{", "(", "(", "RoaringBitmap", ")", "bitmap", ")", ".", "add", "(", "startLowAsLong", ",", "endLowAsLong", ")", ";", "}", "else", "if", "(", "bitmap", "instanceof", "MutableRoaringBitmap", ")", "{", "(", "(", "MutableRoaringBitmap", ")", "bitmap", ")", ".", "add", "(", "startLowAsLong", ",", "endLowAsLong", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"TODO. Not for \"", "+", "bitmap", ".", "getClass", "(", ")", ")", ";", "}", "}", "}", "invalidateAboveHigh", "(", "startHigh", ")", ";", "}" ]
Add to the current bitmap all longs in [rangeStart,rangeEnd). @param rangeStart inclusive beginning of range @param rangeEnd exclusive ending of range
[ "Add", "to", "the", "current", "bitmap", "all", "longs", "in", "[", "rangeStart", "rangeEnd", ")", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java#L1259-L1307
21,863
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringArray.java
MutableRoaringArray.serializedSizeInBytes
@Override public int serializedSizeInBytes() { int count = headerSize(); // for each container, we store cardinality (16 bits), key (16 bits) and location offset (32 // bits). for (int k = 0; k < this.size; ++k) { count += values[k].getArraySizeInBytes(); } return count; }
java
@Override public int serializedSizeInBytes() { int count = headerSize(); // for each container, we store cardinality (16 bits), key (16 bits) and location offset (32 // bits). for (int k = 0; k < this.size; ++k) { count += values[k].getArraySizeInBytes(); } return count; }
[ "@", "Override", "public", "int", "serializedSizeInBytes", "(", ")", "{", "int", "count", "=", "headerSize", "(", ")", ";", "// for each container, we store cardinality (16 bits), key (16 bits) and location offset (32", "// bits).", "for", "(", "int", "k", "=", "0", ";", "k", "<", "this", ".", "size", ";", "++", "k", ")", "{", "count", "+=", "values", "[", "k", "]", ".", "getArraySizeInBytes", "(", ")", ";", "}", "return", "count", ";", "}" ]
Report the number of bytes required for serialization. @return the size in bytes
[ "Report", "the", "number", "of", "bytes", "required", "for", "serialization", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringArray.java#L745-L754
21,864
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java
MappeableRunContainer.appendValueLength
private void appendValueLength(int value, int index) { int previousValue = toIntUnsigned(getValue(index)); int length = toIntUnsigned(getLength(index)); int offset = value - previousValue; if (offset > length) { setLength(index, (short) offset); } }
java
private void appendValueLength(int value, int index) { int previousValue = toIntUnsigned(getValue(index)); int length = toIntUnsigned(getLength(index)); int offset = value - previousValue; if (offset > length) { setLength(index, (short) offset); } }
[ "private", "void", "appendValueLength", "(", "int", "value", ",", "int", "index", ")", "{", "int", "previousValue", "=", "toIntUnsigned", "(", "getValue", "(", "index", ")", ")", ";", "int", "length", "=", "toIntUnsigned", "(", "getLength", "(", "index", ")", ")", ";", "int", "offset", "=", "value", "-", "previousValue", ";", "if", "(", "offset", ">", "length", ")", "{", "setLength", "(", "index", ",", "(", "short", ")", "offset", ")", ";", "}", "}" ]
Append a value length with all values until a given value
[ "Append", "a", "value", "length", "with", "all", "values", "until", "a", "given", "value" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L665-L672
21,865
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java
MappeableRunContainer.canPrependValueLength
private boolean canPrependValueLength(int value, int index) { if (index < this.nbrruns) { int nextValue = toIntUnsigned(getValue(index)); if (nextValue == value + 1) { return true; } } return false; }
java
private boolean canPrependValueLength(int value, int index) { if (index < this.nbrruns) { int nextValue = toIntUnsigned(getValue(index)); if (nextValue == value + 1) { return true; } } return false; }
[ "private", "boolean", "canPrependValueLength", "(", "int", "value", ",", "int", "index", ")", "{", "if", "(", "index", "<", "this", ".", "nbrruns", ")", "{", "int", "nextValue", "=", "toIntUnsigned", "(", "getValue", "(", "index", ")", ")", ";", "if", "(", "nextValue", "==", "value", "+", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
To check if a value length can be prepended with a given value
[ "To", "check", "if", "a", "value", "length", "can", "be", "prepended", "with", "a", "given", "value" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L676-L684
21,866
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java
MappeableRunContainer.closeValueLength
private void closeValueLength(int value, int index) { int initialValue = toIntUnsigned(getValue(index)); setLength(index, (short) (value - initialValue)); }
java
private void closeValueLength(int value, int index) { int initialValue = toIntUnsigned(getValue(index)); setLength(index, (short) (value - initialValue)); }
[ "private", "void", "closeValueLength", "(", "int", "value", ",", "int", "index", ")", "{", "int", "initialValue", "=", "toIntUnsigned", "(", "getValue", "(", "index", ")", ")", ";", "setLength", "(", "index", ",", "(", "short", ")", "(", "value", "-", "initialValue", ")", ")", ";", "}" ]
To set the last value of a value length
[ "To", "set", "the", "last", "value", "of", "a", "value", "length" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L702-L705
21,867
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java
MappeableRunContainer.contains
public static boolean contains(ByteBuffer buf, int position, short x, final int numRuns) { int index = bufferedUnsignedInterleavedBinarySearch(buf, position, 0, numRuns, x); if (index >= 0) { return true; } index = -index - 2; // points to preceding value, possibly -1 if (index != -1) {// possible match int offset = toIntUnsigned(x) - toIntUnsigned(buf.getShort(position + index * 2 * 2)); int le = toIntUnsigned(buf.getShort(position + index * 2 * 2 + 2)); if (offset <= le) { return true; } } return false; }
java
public static boolean contains(ByteBuffer buf, int position, short x, final int numRuns) { int index = bufferedUnsignedInterleavedBinarySearch(buf, position, 0, numRuns, x); if (index >= 0) { return true; } index = -index - 2; // points to preceding value, possibly -1 if (index != -1) {// possible match int offset = toIntUnsigned(x) - toIntUnsigned(buf.getShort(position + index * 2 * 2)); int le = toIntUnsigned(buf.getShort(position + index * 2 * 2 + 2)); if (offset <= le) { return true; } } return false; }
[ "public", "static", "boolean", "contains", "(", "ByteBuffer", "buf", ",", "int", "position", ",", "short", "x", ",", "final", "int", "numRuns", ")", "{", "int", "index", "=", "bufferedUnsignedInterleavedBinarySearch", "(", "buf", ",", "position", ",", "0", ",", "numRuns", ",", "x", ")", ";", "if", "(", "index", ">=", "0", ")", "{", "return", "true", ";", "}", "index", "=", "-", "index", "-", "2", ";", "// points to preceding value, possibly -1", "if", "(", "index", "!=", "-", "1", ")", "{", "// possible match", "int", "offset", "=", "toIntUnsigned", "(", "x", ")", "-", "toIntUnsigned", "(", "buf", ".", "getShort", "(", "position", "+", "index", "*", "2", "*", "2", ")", ")", ";", "int", "le", "=", "toIntUnsigned", "(", "buf", ".", "getShort", "(", "position", "+", "index", "*", "2", "*", "2", "+", "2", ")", ")", ";", "if", "(", "offset", "<=", "le", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether the run container contains x. @param buf underlying ByteBuffer @param position starting position of the container in the ByteBuffer @param x target 16-bit value @param numRuns number of runs @return whether the run container contains x
[ "Checks", "whether", "the", "run", "container", "contains", "x", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L733-L749
21,868
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java
MappeableRunContainer.prependValueLength
private void prependValueLength(int value, int index) { int initialValue = toIntUnsigned(getValue(index)); int length = toIntUnsigned(getLength(index)); setValue(index, (short) value); setLength(index, (short) (initialValue - value + length)); }
java
private void prependValueLength(int value, int index) { int initialValue = toIntUnsigned(getValue(index)); int length = toIntUnsigned(getLength(index)); setValue(index, (short) value); setLength(index, (short) (initialValue - value + length)); }
[ "private", "void", "prependValueLength", "(", "int", "value", ",", "int", "index", ")", "{", "int", "initialValue", "=", "toIntUnsigned", "(", "getValue", "(", "index", ")", ")", ";", "int", "length", "=", "toIntUnsigned", "(", "getLength", "(", "index", ")", ")", ";", "setValue", "(", "index", ",", "(", "short", ")", "value", ")", ";", "setLength", "(", "index", ",", "(", "short", ")", "(", "initialValue", "-", "value", "+", "length", ")", ")", ";", "}" ]
Prepend a value length with all values starting from a given value
[ "Prepend", "a", "value", "length", "with", "all", "values", "starting", "from", "a", "given", "value" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L1920-L1925
21,869
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java
MappeableRunContainer.smartAppend
private void smartAppend(short[] vl, short val) { int oldend; if ((nbrruns == 0) || ( toIntUnsigned(val) > (oldend = toIntUnsigned(vl[2 * (nbrruns - 1)]) + toIntUnsigned(vl[2 * (nbrruns - 1) + 1])) + 1)) { // we add a new one vl[2 * nbrruns] = val; vl[2 * nbrruns + 1] = 0; nbrruns++; return; } if (val == (short) (oldend + 1)) { // we merge vl[2 * (nbrruns - 1) + 1]++; } }
java
private void smartAppend(short[] vl, short val) { int oldend; if ((nbrruns == 0) || ( toIntUnsigned(val) > (oldend = toIntUnsigned(vl[2 * (nbrruns - 1)]) + toIntUnsigned(vl[2 * (nbrruns - 1) + 1])) + 1)) { // we add a new one vl[2 * nbrruns] = val; vl[2 * nbrruns + 1] = 0; nbrruns++; return; } if (val == (short) (oldend + 1)) { // we merge vl[2 * (nbrruns - 1) + 1]++; } }
[ "private", "void", "smartAppend", "(", "short", "[", "]", "vl", ",", "short", "val", ")", "{", "int", "oldend", ";", "if", "(", "(", "nbrruns", "==", "0", ")", "||", "(", "toIntUnsigned", "(", "val", ")", ">", "(", "oldend", "=", "toIntUnsigned", "(", "vl", "[", "2", "*", "(", "nbrruns", "-", "1", ")", "]", ")", "+", "toIntUnsigned", "(", "vl", "[", "2", "*", "(", "nbrruns", "-", "1", ")", "+", "1", "]", ")", ")", "+", "1", ")", ")", "{", "// we add a new one", "vl", "[", "2", "*", "nbrruns", "]", "=", "val", ";", "vl", "[", "2", "*", "nbrruns", "+", "1", "]", "=", "0", ";", "nbrruns", "++", ";", "return", ";", "}", "if", "(", "val", "==", "(", "short", ")", "(", "oldend", "+", "1", ")", ")", "{", "// we merge", "vl", "[", "2", "*", "(", "nbrruns", "-", "1", ")", "+", "1", "]", "++", ";", "}", "}" ]
to return ArrayContainer or BitmapContainer
[ "to", "return", "ArrayContainer", "or", "BitmapContainer" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L2070-L2083
21,870
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java
MappeableRunContainer.valueLengthContains
private boolean valueLengthContains(int value, int index) { int initialValue = toIntUnsigned(getValue(index)); int length = toIntUnsigned(getLength(index)); return value <= initialValue + length; }
java
private boolean valueLengthContains(int value, int index) { int initialValue = toIntUnsigned(getValue(index)); int length = toIntUnsigned(getLength(index)); return value <= initialValue + length; }
[ "private", "boolean", "valueLengthContains", "(", "int", "value", ",", "int", "index", ")", "{", "int", "initialValue", "=", "toIntUnsigned", "(", "getValue", "(", "index", ")", ")", ";", "int", "length", "=", "toIntUnsigned", "(", "getLength", "(", "index", ")", ")", ";", "return", "value", "<=", "initialValue", "+", "length", ";", "}" ]
To check if a value length contains a given value
[ "To", "check", "if", "a", "value", "length", "contains", "a", "given", "value" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L2341-L2346
21,871
RoaringBitmap/RoaringBitmap
jmh/src/main/java/org/roaringbitmap/runcontainer/RandomUtil.java
RandomUtil.negate
static int[] negate(int[] x, int Max) { int[] ans = new int[Max - x.length]; int i = 0; int c = 0; for (int j = 0; j < x.length; ++j) { int v = x[j]; for (; i < v; ++i) ans[c++] = i; ++i; } while (c < ans.length) ans[c++] = i++; return ans; }
java
static int[] negate(int[] x, int Max) { int[] ans = new int[Max - x.length]; int i = 0; int c = 0; for (int j = 0; j < x.length; ++j) { int v = x[j]; for (; i < v; ++i) ans[c++] = i; ++i; } while (c < ans.length) ans[c++] = i++; return ans; }
[ "static", "int", "[", "]", "negate", "(", "int", "[", "]", "x", ",", "int", "Max", ")", "{", "int", "[", "]", "ans", "=", "new", "int", "[", "Max", "-", "x", ".", "length", "]", ";", "int", "i", "=", "0", ";", "int", "c", "=", "0", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "x", ".", "length", ";", "++", "j", ")", "{", "int", "v", "=", "x", "[", "j", "]", ";", "for", "(", ";", "i", "<", "v", ";", "++", "i", ")", "ans", "[", "++", "]", "=", "i", ";", "++", "i", ";", "}", "while", "(", "c", "<", "ans", ".", "length", ")", "ans", "[", "c", "++", "]", "=", "i", "++", ";", "return", "ans", ";", "}" ]
output all integers from the range [0,Max) that are not in the array
[ "output", "all", "integers", "from", "the", "range", "[", "0", "Max", ")", "that", "are", "not", "in", "the", "array" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/jmh/src/main/java/org/roaringbitmap/runcontainer/RandomUtil.java#L42-L55
21,872
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java
MappeableBitmapContainer.contains
public static boolean contains(ByteBuffer buf, int position, final short i) { final int x = toIntUnsigned(i); return (buf.getLong(x / 64 * 8 + position) & (1L << x)) != 0; }
java
public static boolean contains(ByteBuffer buf, int position, final short i) { final int x = toIntUnsigned(i); return (buf.getLong(x / 64 * 8 + position) & (1L << x)) != 0; }
[ "public", "static", "boolean", "contains", "(", "ByteBuffer", "buf", ",", "int", "position", ",", "final", "short", "i", ")", "{", "final", "int", "x", "=", "toIntUnsigned", "(", "i", ")", ";", "return", "(", "buf", ".", "getLong", "(", "x", "/", "64", "*", "8", "+", "position", ")", "&", "(", "1L", "<<", "x", ")", ")", "!=", "0", ";", "}" ]
Checks whether the container contains the value i. @param buf underlying buffer @param position position of the container in the buffer @param i index @return whether the container contains the value i
[ "Checks", "whether", "the", "container", "contains", "the", "value", "i", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java#L418-L421
21,873
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java
MappeableBitmapContainer.nextClearBit
public int nextClearBit(final int i) { int x = i >> 6; // i / 64 with sign extension long w = ~bitmap.get(x); w >>>= i; if (w != 0) { return i + numberOfTrailingZeros(w); } int length = bitmap.limit(); for (++x; x < length; ++x) { long map = ~bitmap.get(x); if (map != 0L) { return x * 64 + numberOfTrailingZeros(map); } } return MAX_CAPACITY; }
java
public int nextClearBit(final int i) { int x = i >> 6; // i / 64 with sign extension long w = ~bitmap.get(x); w >>>= i; if (w != 0) { return i + numberOfTrailingZeros(w); } int length = bitmap.limit(); for (++x; x < length; ++x) { long map = ~bitmap.get(x); if (map != 0L) { return x * 64 + numberOfTrailingZeros(map); } } return MAX_CAPACITY; }
[ "public", "int", "nextClearBit", "(", "final", "int", "i", ")", "{", "int", "x", "=", "i", ">>", "6", ";", "// i / 64 with sign extension", "long", "w", "=", "~", "bitmap", ".", "get", "(", "x", ")", ";", "w", ">>>=", "i", ";", "if", "(", "w", "!=", "0", ")", "{", "return", "i", "+", "numberOfTrailingZeros", "(", "w", ")", ";", "}", "int", "length", "=", "bitmap", ".", "limit", "(", ")", ";", "for", "(", "++", "x", ";", "x", "<", "length", ";", "++", "x", ")", "{", "long", "map", "=", "~", "bitmap", ".", "get", "(", "x", ")", ";", "if", "(", "map", "!=", "0L", ")", "{", "return", "x", "*", "64", "+", "numberOfTrailingZeros", "(", "map", ")", ";", "}", "}", "return", "MAX_CAPACITY", ";", "}" ]
Find the index of the next clear bit greater or equal to i. @param i starting index @return index of the next clear bit
[ "Find", "the", "index", "of", "the", "next", "clear", "bit", "greater", "or", "equal", "to", "i", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java#L1279-L1294
21,874
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java
MappeableBitmapContainer.prevClearBit
public int prevClearBit(final int i) { int x = i >> 6; // i / 64 with sign extension long w = ~bitmap.get(x); w <<= 64 - i - 1; if (w != 0L) { return i - Long.numberOfLeadingZeros(w); } for (--x; x >= 0; --x) { long map = ~bitmap.get(x); if (map != 0L) { return x * 64 + 63 - Long.numberOfLeadingZeros(map); } } return -1; }
java
public int prevClearBit(final int i) { int x = i >> 6; // i / 64 with sign extension long w = ~bitmap.get(x); w <<= 64 - i - 1; if (w != 0L) { return i - Long.numberOfLeadingZeros(w); } for (--x; x >= 0; --x) { long map = ~bitmap.get(x); if (map != 0L) { return x * 64 + 63 - Long.numberOfLeadingZeros(map); } } return -1; }
[ "public", "int", "prevClearBit", "(", "final", "int", "i", ")", "{", "int", "x", "=", "i", ">>", "6", ";", "// i / 64 with sign extension", "long", "w", "=", "~", "bitmap", ".", "get", "(", "x", ")", ";", "w", "<<=", "64", "-", "i", "-", "1", ";", "if", "(", "w", "!=", "0L", ")", "{", "return", "i", "-", "Long", ".", "numberOfLeadingZeros", "(", "w", ")", ";", "}", "for", "(", "--", "x", ";", "x", ">=", "0", ";", "--", "x", ")", "{", "long", "map", "=", "~", "bitmap", ".", "get", "(", "x", ")", ";", "if", "(", "map", "!=", "0L", ")", "{", "return", "x", "*", "64", "+", "63", "-", "Long", ".", "numberOfLeadingZeros", "(", "map", ")", ";", "}", "}", "return", "-", "1", ";", "}" ]
Find the index of the previous clear bit less than or equal to i. @param i starting index @return index of the previous clear bit
[ "Find", "the", "index", "of", "the", "previous", "clear", "bit", "less", "than", "or", "equal", "to", "i", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java#L1518-L1532
21,875
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java
MappeableBitmapContainer.toLongArray
public long[] toLongArray() { long[] answer = new long[bitmap.limit()]; bitmap.rewind(); bitmap.get(answer); return answer; }
java
public long[] toLongArray() { long[] answer = new long[bitmap.limit()]; bitmap.rewind(); bitmap.get(answer); return answer; }
[ "public", "long", "[", "]", "toLongArray", "(", ")", "{", "long", "[", "]", "answer", "=", "new", "long", "[", "bitmap", ".", "limit", "(", ")", "]", ";", "bitmap", ".", "rewind", "(", ")", ";", "bitmap", ".", "get", "(", "answer", ")", ";", "return", "answer", ";", "}" ]
Create a copy of the content of this container as a long array. This creates a copy. @return copy of the content as a long array
[ "Create", "a", "copy", "of", "the", "content", "of", "this", "container", "as", "a", "long", "array", ".", "This", "creates", "a", "copy", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableBitmapContainer.java#L1714-L1719
21,876
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/BitmapContainer.java
BitmapContainer.toLongBuffer
public LongBuffer toLongBuffer() { LongBuffer lb = LongBuffer.allocate(bitmap.length); lb.put(bitmap); return lb; }
java
public LongBuffer toLongBuffer() { LongBuffer lb = LongBuffer.allocate(bitmap.length); lb.put(bitmap); return lb; }
[ "public", "LongBuffer", "toLongBuffer", "(", ")", "{", "LongBuffer", "lb", "=", "LongBuffer", ".", "allocate", "(", "bitmap", ".", "length", ")", ";", "lb", ".", "put", "(", "bitmap", ")", ";", "return", "lb", ";", "}" ]
Return the content of this container as a LongBuffer. This creates a copy and might be relatively slow. @return the LongBuffer
[ "Return", "the", "content", "of", "this", "container", "as", "a", "LongBuffer", ".", "This", "creates", "a", "copy", "and", "might", "be", "relatively", "slow", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/BitmapContainer.java#L1295-L1299
21,877
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableArrayContainer.java
MappeableArrayContainer.contains
public static boolean contains(ByteBuffer buf, int position, final short x, int cardinality) { return BufferUtil.unsignedBinarySearch(buf, position, 0, cardinality, x) >= 0; }
java
public static boolean contains(ByteBuffer buf, int position, final short x, int cardinality) { return BufferUtil.unsignedBinarySearch(buf, position, 0, cardinality, x) >= 0; }
[ "public", "static", "boolean", "contains", "(", "ByteBuffer", "buf", ",", "int", "position", ",", "final", "short", "x", ",", "int", "cardinality", ")", "{", "return", "BufferUtil", ".", "unsignedBinarySearch", "(", "buf", ",", "position", ",", "0", ",", "cardinality", ",", "x", ")", ">=", "0", ";", "}" ]
Checks whether the container contains the value x. @param buf underlying buffer @param position starting position of the container in the ByteBuffer @param x target value x @param cardinality container cardinality @return whether the container contains the value x
[ "Checks", "whether", "the", "container", "contains", "the", "value", "x", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableArrayContainer.java#L374-L376
21,878
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/ArrayContainer.java
ArrayContainer.increaseCapacity
private void increaseCapacity(boolean allowIllegalSize) { int newCapacity = (this.content.length == 0) ? DEFAULT_INIT_SIZE : this.content.length < 64 ? this.content.length * 2 : this.content.length < 1067 ? this.content.length * 3 / 2 : this.content.length * 5 / 4; // never allocate more than we will ever need if (newCapacity > ArrayContainer.DEFAULT_MAX_SIZE && !allowIllegalSize) { newCapacity = ArrayContainer.DEFAULT_MAX_SIZE; } // if we are within 1/16th of the max, go to max if (newCapacity > ArrayContainer.DEFAULT_MAX_SIZE - ArrayContainer.DEFAULT_MAX_SIZE / 16 && !allowIllegalSize) { newCapacity = ArrayContainer.DEFAULT_MAX_SIZE; } this.content = Arrays.copyOf(this.content, newCapacity); }
java
private void increaseCapacity(boolean allowIllegalSize) { int newCapacity = (this.content.length == 0) ? DEFAULT_INIT_SIZE : this.content.length < 64 ? this.content.length * 2 : this.content.length < 1067 ? this.content.length * 3 / 2 : this.content.length * 5 / 4; // never allocate more than we will ever need if (newCapacity > ArrayContainer.DEFAULT_MAX_SIZE && !allowIllegalSize) { newCapacity = ArrayContainer.DEFAULT_MAX_SIZE; } // if we are within 1/16th of the max, go to max if (newCapacity > ArrayContainer.DEFAULT_MAX_SIZE - ArrayContainer.DEFAULT_MAX_SIZE / 16 && !allowIllegalSize) { newCapacity = ArrayContainer.DEFAULT_MAX_SIZE; } this.content = Arrays.copyOf(this.content, newCapacity); }
[ "private", "void", "increaseCapacity", "(", "boolean", "allowIllegalSize", ")", "{", "int", "newCapacity", "=", "(", "this", ".", "content", ".", "length", "==", "0", ")", "?", "DEFAULT_INIT_SIZE", ":", "this", ".", "content", ".", "length", "<", "64", "?", "this", ".", "content", ".", "length", "*", "2", ":", "this", ".", "content", ".", "length", "<", "1067", "?", "this", ".", "content", ".", "length", "*", "3", "/", "2", ":", "this", ".", "content", ".", "length", "*", "5", "/", "4", ";", "// never allocate more than we will ever need", "if", "(", "newCapacity", ">", "ArrayContainer", ".", "DEFAULT_MAX_SIZE", "&&", "!", "allowIllegalSize", ")", "{", "newCapacity", "=", "ArrayContainer", ".", "DEFAULT_MAX_SIZE", ";", "}", "// if we are within 1/16th of the max, go to max", "if", "(", "newCapacity", ">", "ArrayContainer", ".", "DEFAULT_MAX_SIZE", "-", "ArrayContainer", ".", "DEFAULT_MAX_SIZE", "/", "16", "&&", "!", "allowIllegalSize", ")", "{", "newCapacity", "=", "ArrayContainer", ".", "DEFAULT_MAX_SIZE", ";", "}", "this", ".", "content", "=", "Arrays", ".", "copyOf", "(", "this", ".", "content", ",", "newCapacity", ")", ";", "}" ]
the illegal container does not return it.
[ "the", "illegal", "container", "does", "not", "return", "it", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/ArrayContainer.java#L592-L607
21,879
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/FastRankRoaringBitmap.java
FastRankRoaringBitmap.preComputeCardinalities
private void preComputeCardinalities() { if (!cumulatedCardinalitiesCacheIsValid) { int nbBuckets = highLowContainer.size(); // Ensure the cache size is the right one if (highToCumulatedCardinality == null || highToCumulatedCardinality.length != nbBuckets) { highToCumulatedCardinality = new int[nbBuckets]; } // Ensure the cache content is valid if (highToCumulatedCardinality.length >= 1) { // As we compute the cumulated cardinalities, the first index is an edge case highToCumulatedCardinality[0] = highLowContainer.getContainerAtIndex(0).getCardinality(); for (int i = 1; i < highToCumulatedCardinality.length; i++) { highToCumulatedCardinality[i] = highToCumulatedCardinality[i - 1] + highLowContainer.getContainerAtIndex(i).getCardinality(); } } cumulatedCardinalitiesCacheIsValid = true; } }
java
private void preComputeCardinalities() { if (!cumulatedCardinalitiesCacheIsValid) { int nbBuckets = highLowContainer.size(); // Ensure the cache size is the right one if (highToCumulatedCardinality == null || highToCumulatedCardinality.length != nbBuckets) { highToCumulatedCardinality = new int[nbBuckets]; } // Ensure the cache content is valid if (highToCumulatedCardinality.length >= 1) { // As we compute the cumulated cardinalities, the first index is an edge case highToCumulatedCardinality[0] = highLowContainer.getContainerAtIndex(0).getCardinality(); for (int i = 1; i < highToCumulatedCardinality.length; i++) { highToCumulatedCardinality[i] = highToCumulatedCardinality[i - 1] + highLowContainer.getContainerAtIndex(i).getCardinality(); } } cumulatedCardinalitiesCacheIsValid = true; } }
[ "private", "void", "preComputeCardinalities", "(", ")", "{", "if", "(", "!", "cumulatedCardinalitiesCacheIsValid", ")", "{", "int", "nbBuckets", "=", "highLowContainer", ".", "size", "(", ")", ";", "// Ensure the cache size is the right one", "if", "(", "highToCumulatedCardinality", "==", "null", "||", "highToCumulatedCardinality", ".", "length", "!=", "nbBuckets", ")", "{", "highToCumulatedCardinality", "=", "new", "int", "[", "nbBuckets", "]", ";", "}", "// Ensure the cache content is valid", "if", "(", "highToCumulatedCardinality", ".", "length", ">=", "1", ")", "{", "// As we compute the cumulated cardinalities, the first index is an edge case", "highToCumulatedCardinality", "[", "0", "]", "=", "highLowContainer", ".", "getContainerAtIndex", "(", "0", ")", ".", "getCardinality", "(", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "highToCumulatedCardinality", ".", "length", ";", "i", "++", ")", "{", "highToCumulatedCardinality", "[", "i", "]", "=", "highToCumulatedCardinality", "[", "i", "-", "1", "]", "+", "highLowContainer", ".", "getContainerAtIndex", "(", "i", ")", ".", "getCardinality", "(", ")", ";", "}", "}", "cumulatedCardinalitiesCacheIsValid", "=", "true", ";", "}", "}" ]
On any .rank or .select operation, we pre-compute all cumulated cardinalities. It will enable using a binary-search to spot the relevant underlying bucket. We may prefer to cache cardinality only up-to the selected rank, but it would lead to a more complex implementation
[ "On", "any", ".", "rank", "or", ".", "select", "operation", "we", "pre", "-", "compute", "all", "cumulated", "cardinalities", ".", "It", "will", "enable", "using", "a", "binary", "-", "search", "to", "spot", "the", "relevant", "underlying", "bucket", ".", "We", "may", "prefer", "to", "cache", "cardinality", "only", "up", "-", "to", "the", "selected", "rank", "but", "it", "would", "lead", "to", "a", "more", "complex", "implementation" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/FastRankRoaringBitmap.java#L159-L181
21,880
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/ImmutableRoaringBitmap.java
ImmutableRoaringBitmap.contains
public boolean contains(long minimum, long supremum) { MutableRoaringBitmap.rangeSanityCheck(minimum, supremum); short firstKey = highbits(minimum); short lastKey = highbits(supremum); int span = BufferUtil.toIntUnsigned(lastKey) - BufferUtil.toIntUnsigned(firstKey); int len = highLowContainer.size(); if (len < span) { return false; } int begin = highLowContainer.getIndex(firstKey); int end = highLowContainer.getIndex(lastKey); end = end < 0 ? -end -1 : end; if (begin < 0 || end - begin != span) { return false; } int min = (short)minimum & 0xFFFF; int sup = (short)supremum & 0xFFFF; if (firstKey == lastKey) { return highLowContainer.getContainerAtIndex(begin).contains(min, sup); } if (!highLowContainer.getContainerAtIndex(begin).contains(min, 1 << 16)) { return false; } if (end < len && !highLowContainer.getContainerAtIndex(end).contains(0, sup)) { return false; } for (int i = begin + 1; i < end; ++i) { if (highLowContainer.getContainerAtIndex(i).getCardinality() != 1 << 16) { return false; } } return true; }
java
public boolean contains(long minimum, long supremum) { MutableRoaringBitmap.rangeSanityCheck(minimum, supremum); short firstKey = highbits(minimum); short lastKey = highbits(supremum); int span = BufferUtil.toIntUnsigned(lastKey) - BufferUtil.toIntUnsigned(firstKey); int len = highLowContainer.size(); if (len < span) { return false; } int begin = highLowContainer.getIndex(firstKey); int end = highLowContainer.getIndex(lastKey); end = end < 0 ? -end -1 : end; if (begin < 0 || end - begin != span) { return false; } int min = (short)minimum & 0xFFFF; int sup = (short)supremum & 0xFFFF; if (firstKey == lastKey) { return highLowContainer.getContainerAtIndex(begin).contains(min, sup); } if (!highLowContainer.getContainerAtIndex(begin).contains(min, 1 << 16)) { return false; } if (end < len && !highLowContainer.getContainerAtIndex(end).contains(0, sup)) { return false; } for (int i = begin + 1; i < end; ++i) { if (highLowContainer.getContainerAtIndex(i).getCardinality() != 1 << 16) { return false; } } return true; }
[ "public", "boolean", "contains", "(", "long", "minimum", ",", "long", "supremum", ")", "{", "MutableRoaringBitmap", ".", "rangeSanityCheck", "(", "minimum", ",", "supremum", ")", ";", "short", "firstKey", "=", "highbits", "(", "minimum", ")", ";", "short", "lastKey", "=", "highbits", "(", "supremum", ")", ";", "int", "span", "=", "BufferUtil", ".", "toIntUnsigned", "(", "lastKey", ")", "-", "BufferUtil", ".", "toIntUnsigned", "(", "firstKey", ")", ";", "int", "len", "=", "highLowContainer", ".", "size", "(", ")", ";", "if", "(", "len", "<", "span", ")", "{", "return", "false", ";", "}", "int", "begin", "=", "highLowContainer", ".", "getIndex", "(", "firstKey", ")", ";", "int", "end", "=", "highLowContainer", ".", "getIndex", "(", "lastKey", ")", ";", "end", "=", "end", "<", "0", "?", "-", "end", "-", "1", ":", "end", ";", "if", "(", "begin", "<", "0", "||", "end", "-", "begin", "!=", "span", ")", "{", "return", "false", ";", "}", "int", "min", "=", "(", "short", ")", "minimum", "&", "0xFFFF", ";", "int", "sup", "=", "(", "short", ")", "supremum", "&", "0xFFFF", ";", "if", "(", "firstKey", "==", "lastKey", ")", "{", "return", "highLowContainer", ".", "getContainerAtIndex", "(", "begin", ")", ".", "contains", "(", "min", ",", "sup", ")", ";", "}", "if", "(", "!", "highLowContainer", ".", "getContainerAtIndex", "(", "begin", ")", ".", "contains", "(", "min", ",", "1", "<<", "16", ")", ")", "{", "return", "false", ";", "}", "if", "(", "end", "<", "len", "&&", "!", "highLowContainer", ".", "getContainerAtIndex", "(", "end", ")", ".", "contains", "(", "0", ",", "sup", ")", ")", "{", "return", "false", ";", "}", "for", "(", "int", "i", "=", "begin", "+", "1", ";", "i", "<", "end", ";", "++", "i", ")", "{", "if", "(", "highLowContainer", ".", "getContainerAtIndex", "(", "i", ")", ".", "getCardinality", "(", ")", "!=", "1", "<<", "16", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if the bitmap contains the range. @param minimum the inclusive lower bound of the range @param supremum the exclusive upper bound of the range @return whether the bitmap intersects with the range
[ "Checks", "if", "the", "bitmap", "contains", "the", "range", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/ImmutableRoaringBitmap.java#L1003-L1036
21,881
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/ImmutableRoaringBitmap.java
ImmutableRoaringBitmap.toArray
@Override public int[] toArray() { final int[] array = new int[this.getCardinality()]; int pos = 0, pos2 = 0; while (pos < this.highLowContainer.size()) { final int hs = BufferUtil.toIntUnsigned(this.highLowContainer.getKeyAtIndex(pos)) << 16; final MappeableContainer c = this.highLowContainer.getContainerAtIndex(pos++); c.fillLeastSignificant16bits(array, pos2, hs); pos2 += c.getCardinality(); } return array; }
java
@Override public int[] toArray() { final int[] array = new int[this.getCardinality()]; int pos = 0, pos2 = 0; while (pos < this.highLowContainer.size()) { final int hs = BufferUtil.toIntUnsigned(this.highLowContainer.getKeyAtIndex(pos)) << 16; final MappeableContainer c = this.highLowContainer.getContainerAtIndex(pos++); c.fillLeastSignificant16bits(array, pos2, hs); pos2 += c.getCardinality(); } return array; }
[ "@", "Override", "public", "int", "[", "]", "toArray", "(", ")", "{", "final", "int", "[", "]", "array", "=", "new", "int", "[", "this", ".", "getCardinality", "(", ")", "]", ";", "int", "pos", "=", "0", ",", "pos2", "=", "0", ";", "while", "(", "pos", "<", "this", ".", "highLowContainer", ".", "size", "(", ")", ")", "{", "final", "int", "hs", "=", "BufferUtil", ".", "toIntUnsigned", "(", "this", ".", "highLowContainer", ".", "getKeyAtIndex", "(", "pos", ")", ")", "<<", "16", ";", "final", "MappeableContainer", "c", "=", "this", ".", "highLowContainer", ".", "getContainerAtIndex", "(", "pos", "++", ")", ";", "c", ".", "fillLeastSignificant16bits", "(", "array", ",", "pos2", ",", "hs", ")", ";", "pos2", "+=", "c", ".", "getCardinality", "(", ")", ";", "}", "return", "array", ";", "}" ]
Return the set values as an array if the cardinality is less than 2147483648. The integer values are in sorted order. @return array representing the set values.
[ "Return", "the", "set", "values", "as", "an", "array", "if", "the", "cardinality", "is", "less", "than", "2147483648", ".", "The", "integer", "values", "are", "in", "sorted", "order", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/ImmutableRoaringBitmap.java#L1725-L1736
21,882
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/ImmutableRoaringBitmap.java
ImmutableRoaringBitmap.toMutableRoaringBitmap
public MutableRoaringBitmap toMutableRoaringBitmap() { MutableRoaringBitmap c = new MutableRoaringBitmap(); MappeableContainerPointer mcp = highLowContainer.getContainerPointer(); while (mcp.hasContainer()) { c.getMappeableRoaringArray().appendCopy(mcp.key(), mcp.getContainer()); mcp.advance(); } return c; }
java
public MutableRoaringBitmap toMutableRoaringBitmap() { MutableRoaringBitmap c = new MutableRoaringBitmap(); MappeableContainerPointer mcp = highLowContainer.getContainerPointer(); while (mcp.hasContainer()) { c.getMappeableRoaringArray().appendCopy(mcp.key(), mcp.getContainer()); mcp.advance(); } return c; }
[ "public", "MutableRoaringBitmap", "toMutableRoaringBitmap", "(", ")", "{", "MutableRoaringBitmap", "c", "=", "new", "MutableRoaringBitmap", "(", ")", ";", "MappeableContainerPointer", "mcp", "=", "highLowContainer", ".", "getContainerPointer", "(", ")", ";", "while", "(", "mcp", ".", "hasContainer", "(", ")", ")", "{", "c", ".", "getMappeableRoaringArray", "(", ")", ".", "appendCopy", "(", "mcp", ".", "key", "(", ")", ",", "mcp", ".", "getContainer", "(", ")", ")", ";", "mcp", ".", "advance", "(", ")", ";", "}", "return", "c", ";", "}" ]
Copies the content of this bitmap to a bitmap that can be modified. @return a mutable bitmap.
[ "Copies", "the", "content", "of", "this", "bitmap", "to", "a", "bitmap", "that", "can", "be", "modified", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/ImmutableRoaringBitmap.java#L1743-L1751
21,883
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/insights/BitmapAnalyser.java
BitmapAnalyser.analyse
public static BitmapStatistics analyse(RoaringBitmap r) { int acCount = 0; int acCardinalitySum = 0; int bcCount = 0; int rcCount = 0; ContainerPointer cp = r.getContainerPointer(); while (cp.getContainer() != null) { if (cp.isBitmapContainer()) { bcCount += 1; } else if (cp.isRunContainer()) { rcCount += 1; } else { acCount += 1; acCardinalitySum += cp.getCardinality(); } cp.advance(); } BitmapStatistics.ArrayContainersStats acStats = new BitmapStatistics.ArrayContainersStats(acCount, acCardinalitySum); return new BitmapStatistics(acStats, bcCount, rcCount); }
java
public static BitmapStatistics analyse(RoaringBitmap r) { int acCount = 0; int acCardinalitySum = 0; int bcCount = 0; int rcCount = 0; ContainerPointer cp = r.getContainerPointer(); while (cp.getContainer() != null) { if (cp.isBitmapContainer()) { bcCount += 1; } else if (cp.isRunContainer()) { rcCount += 1; } else { acCount += 1; acCardinalitySum += cp.getCardinality(); } cp.advance(); } BitmapStatistics.ArrayContainersStats acStats = new BitmapStatistics.ArrayContainersStats(acCount, acCardinalitySum); return new BitmapStatistics(acStats, bcCount, rcCount); }
[ "public", "static", "BitmapStatistics", "analyse", "(", "RoaringBitmap", "r", ")", "{", "int", "acCount", "=", "0", ";", "int", "acCardinalitySum", "=", "0", ";", "int", "bcCount", "=", "0", ";", "int", "rcCount", "=", "0", ";", "ContainerPointer", "cp", "=", "r", ".", "getContainerPointer", "(", ")", ";", "while", "(", "cp", ".", "getContainer", "(", ")", "!=", "null", ")", "{", "if", "(", "cp", ".", "isBitmapContainer", "(", ")", ")", "{", "bcCount", "+=", "1", ";", "}", "else", "if", "(", "cp", ".", "isRunContainer", "(", ")", ")", "{", "rcCount", "+=", "1", ";", "}", "else", "{", "acCount", "+=", "1", ";", "acCardinalitySum", "+=", "cp", ".", "getCardinality", "(", ")", ";", "}", "cp", ".", "advance", "(", ")", ";", "}", "BitmapStatistics", ".", "ArrayContainersStats", "acStats", "=", "new", "BitmapStatistics", ".", "ArrayContainersStats", "(", "acCount", ",", "acCardinalitySum", ")", ";", "return", "new", "BitmapStatistics", "(", "acStats", ",", "bcCount", ",", "rcCount", ")", ";", "}" ]
Analyze the internal representation of bitmap @param r the bitmap @return the statistics
[ "Analyze", "the", "internal", "representation", "of", "bitmap" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/insights/BitmapAnalyser.java#L15-L35
21,884
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/insights/BitmapAnalyser.java
BitmapAnalyser.analyse
public static BitmapStatistics analyse(Collection<? extends RoaringBitmap> bitmaps) { return bitmaps .stream() .reduce( BitmapStatistics.empty, (acc, r) -> acc.merge(BitmapAnalyser.analyse(r)), BitmapStatistics::merge); }
java
public static BitmapStatistics analyse(Collection<? extends RoaringBitmap> bitmaps) { return bitmaps .stream() .reduce( BitmapStatistics.empty, (acc, r) -> acc.merge(BitmapAnalyser.analyse(r)), BitmapStatistics::merge); }
[ "public", "static", "BitmapStatistics", "analyse", "(", "Collection", "<", "?", "extends", "RoaringBitmap", ">", "bitmaps", ")", "{", "return", "bitmaps", ".", "stream", "(", ")", ".", "reduce", "(", "BitmapStatistics", ".", "empty", ",", "(", "acc", ",", "r", ")", "->", "acc", ".", "merge", "(", "BitmapAnalyser", ".", "analyse", "(", "r", ")", ")", ",", "BitmapStatistics", "::", "merge", ")", ";", "}" ]
Analyze the internal representation of bitmaps @param bitmaps the bitmaps @return the statistics
[ "Analyze", "the", "internal", "representation", "of", "bitmaps" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/insights/BitmapAnalyser.java#L42-L49
21,885
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java
BufferUtil.getSizeInBytesFromCardinalityEtc
protected static int getSizeInBytesFromCardinalityEtc(int card, int numRuns, boolean isRunEncoded) { if (isRunEncoded) { return 2 + numRuns * 2 * 2; // each run uses 2 shorts, plus the initial short giving num runs } boolean isBitmap = card > MappeableArrayContainer.DEFAULT_MAX_SIZE; if (isBitmap) { return MappeableBitmapContainer.MAX_CAPACITY / 8; } else { return card * 2; } }
java
protected static int getSizeInBytesFromCardinalityEtc(int card, int numRuns, boolean isRunEncoded) { if (isRunEncoded) { return 2 + numRuns * 2 * 2; // each run uses 2 shorts, plus the initial short giving num runs } boolean isBitmap = card > MappeableArrayContainer.DEFAULT_MAX_SIZE; if (isBitmap) { return MappeableBitmapContainer.MAX_CAPACITY / 8; } else { return card * 2; } }
[ "protected", "static", "int", "getSizeInBytesFromCardinalityEtc", "(", "int", "card", ",", "int", "numRuns", ",", "boolean", "isRunEncoded", ")", "{", "if", "(", "isRunEncoded", ")", "{", "return", "2", "+", "numRuns", "*", "2", "*", "2", ";", "// each run uses 2 shorts, plus the initial short giving num runs", "}", "boolean", "isBitmap", "=", "card", ">", "MappeableArrayContainer", ".", "DEFAULT_MAX_SIZE", ";", "if", "(", "isBitmap", ")", "{", "return", "MappeableBitmapContainer", ".", "MAX_CAPACITY", "/", "8", ";", "}", "else", "{", "return", "card", "*", "2", ";", "}", "}" ]
From the cardinality of a container, compute the corresponding size in bytes of the container. Additional information is required if the container is run encoded. @param card the cardinality if this is not run encoded, otherwise ignored @param numRuns number of runs if run encoded, othewise ignored @param isRunEncoded boolean @return the size in bytes
[ "From", "the", "cardinality", "of", "a", "container", "compute", "the", "corresponding", "size", "in", "bytes", "of", "the", "container", ".", "Additional", "information", "is", "required", "if", "the", "container", "is", "run", "encoded", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java#L492-L504
21,886
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java
BufferUtil.unsignedIntersects
public static boolean unsignedIntersects(ShortBuffer set1, int length1, ShortBuffer set2, int length2) { if ((0 == length1) || (0 == length2)) { return false; } int k1 = 0; int k2 = 0; // could be more efficient with galloping short s1 = set1.get(k1); short s2 = set2.get(k2); mainwhile: while (true) { if (toIntUnsigned(s2) < toIntUnsigned(s1)) { do { ++k2; if (k2 == length2) { break mainwhile; } s2 = set2.get(k2); } while (toIntUnsigned(s2) < toIntUnsigned(s1)); } if (toIntUnsigned(s1) < toIntUnsigned(s2)) { do { ++k1; if (k1 == length1) { break mainwhile; } s1 = set1.get(k1); } while (toIntUnsigned(s1) < toIntUnsigned(s2)); } else { return true; } } return false; }
java
public static boolean unsignedIntersects(ShortBuffer set1, int length1, ShortBuffer set2, int length2) { if ((0 == length1) || (0 == length2)) { return false; } int k1 = 0; int k2 = 0; // could be more efficient with galloping short s1 = set1.get(k1); short s2 = set2.get(k2); mainwhile: while (true) { if (toIntUnsigned(s2) < toIntUnsigned(s1)) { do { ++k2; if (k2 == length2) { break mainwhile; } s2 = set2.get(k2); } while (toIntUnsigned(s2) < toIntUnsigned(s1)); } if (toIntUnsigned(s1) < toIntUnsigned(s2)) { do { ++k1; if (k1 == length1) { break mainwhile; } s1 = set1.get(k1); } while (toIntUnsigned(s1) < toIntUnsigned(s2)); } else { return true; } } return false; }
[ "public", "static", "boolean", "unsignedIntersects", "(", "ShortBuffer", "set1", ",", "int", "length1", ",", "ShortBuffer", "set2", ",", "int", "length2", ")", "{", "if", "(", "(", "0", "==", "length1", ")", "||", "(", "0", "==", "length2", ")", ")", "{", "return", "false", ";", "}", "int", "k1", "=", "0", ";", "int", "k2", "=", "0", ";", "// could be more efficient with galloping", "short", "s1", "=", "set1", ".", "get", "(", "k1", ")", ";", "short", "s2", "=", "set2", ".", "get", "(", "k2", ")", ";", "mainwhile", ":", "while", "(", "true", ")", "{", "if", "(", "toIntUnsigned", "(", "s2", ")", "<", "toIntUnsigned", "(", "s1", ")", ")", "{", "do", "{", "++", "k2", ";", "if", "(", "k2", "==", "length2", ")", "{", "break", "mainwhile", ";", "}", "s2", "=", "set2", ".", "get", "(", "k2", ")", ";", "}", "while", "(", "toIntUnsigned", "(", "s2", ")", "<", "toIntUnsigned", "(", "s1", ")", ")", ";", "}", "if", "(", "toIntUnsigned", "(", "s1", ")", "<", "toIntUnsigned", "(", "s2", ")", ")", "{", "do", "{", "++", "k1", ";", "if", "(", "k1", "==", "length1", ")", "{", "break", "mainwhile", ";", "}", "s1", "=", "set1", ".", "get", "(", "k1", ")", ";", "}", "while", "(", "toIntUnsigned", "(", "s1", ")", "<", "toIntUnsigned", "(", "s2", ")", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if two arrays intersect @param set1 first array @param length1 length of first array @param set2 second array @param length2 length of second array @return true if they intersect
[ "Checks", "if", "two", "arrays", "intersect" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java#L762-L797
21,887
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/Util.java
Util.fillArrayANDNOT
public static void fillArrayANDNOT(final short[] container, final long[] bitmap1, final long[] bitmap2) { int pos = 0; if (bitmap1.length != bitmap2.length) { throw new IllegalArgumentException("not supported"); } for (int k = 0; k < bitmap1.length; ++k) { long bitset = bitmap1[k] & (~bitmap2[k]); while (bitset != 0) { container[pos++] = (short) (k * 64 + numberOfTrailingZeros(bitset)); bitset &= (bitset - 1); } } }
java
public static void fillArrayANDNOT(final short[] container, final long[] bitmap1, final long[] bitmap2) { int pos = 0; if (bitmap1.length != bitmap2.length) { throw new IllegalArgumentException("not supported"); } for (int k = 0; k < bitmap1.length; ++k) { long bitset = bitmap1[k] & (~bitmap2[k]); while (bitset != 0) { container[pos++] = (short) (k * 64 + numberOfTrailingZeros(bitset)); bitset &= (bitset - 1); } } }
[ "public", "static", "void", "fillArrayANDNOT", "(", "final", "short", "[", "]", "container", ",", "final", "long", "[", "]", "bitmap1", ",", "final", "long", "[", "]", "bitmap2", ")", "{", "int", "pos", "=", "0", ";", "if", "(", "bitmap1", ".", "length", "!=", "bitmap2", ".", "length", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"not supported\"", ")", ";", "}", "for", "(", "int", "k", "=", "0", ";", "k", "<", "bitmap1", ".", "length", ";", "++", "k", ")", "{", "long", "bitset", "=", "bitmap1", "[", "k", "]", "&", "(", "~", "bitmap2", "[", "k", "]", ")", ";", "while", "(", "bitset", "!=", "0", ")", "{", "container", "[", "pos", "++", "]", "=", "(", "short", ")", "(", "k", "*", "64", "+", "numberOfTrailingZeros", "(", "bitset", ")", ")", ";", "bitset", "&=", "(", "bitset", "-", "1", ")", ";", "}", "}", "}" ]
Compute the bitwise ANDNOT between two long arrays and write the set bits in the container. @param container where we write @param bitmap1 first bitmap @param bitmap2 second bitmap
[ "Compute", "the", "bitwise", "ANDNOT", "between", "two", "long", "arrays", "and", "write", "the", "set", "bits", "in", "the", "container", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L244-L257
21,888
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/Util.java
Util.flipBitmapRange
public static void flipBitmapRange(long[] bitmap, int start, int end) { if (start == end) { return; } int firstword = start / 64; int endword = (end - 1) / 64; bitmap[firstword] ^= ~(~0L << start); for (int i = firstword; i < endword; i++) { bitmap[i] = ~bitmap[i]; } bitmap[endword] ^= ~0L >>> -end; }
java
public static void flipBitmapRange(long[] bitmap, int start, int end) { if (start == end) { return; } int firstword = start / 64; int endword = (end - 1) / 64; bitmap[firstword] ^= ~(~0L << start); for (int i = firstword; i < endword; i++) { bitmap[i] = ~bitmap[i]; } bitmap[endword] ^= ~0L >>> -end; }
[ "public", "static", "void", "flipBitmapRange", "(", "long", "[", "]", "bitmap", ",", "int", "start", ",", "int", "end", ")", "{", "if", "(", "start", "==", "end", ")", "{", "return", ";", "}", "int", "firstword", "=", "start", "/", "64", ";", "int", "endword", "=", "(", "end", "-", "1", ")", "/", "64", ";", "bitmap", "[", "firstword", "]", "^=", "~", "(", "~", "0L", "<<", "start", ")", ";", "for", "(", "int", "i", "=", "firstword", ";", "i", "<", "endword", ";", "i", "++", ")", "{", "bitmap", "[", "i", "]", "=", "~", "bitmap", "[", "i", "]", ";", "}", "bitmap", "[", "endword", "]", "^=", "~", "0L", ">>>", "-", "end", ";", "}" ]
flip bits at start, start+1,..., end-1 @param bitmap array of words to be modified @param start first index to be modified (inclusive) @param end last index to be modified (exclusive)
[ "flip", "bits", "at", "start", "start", "+", "1", "...", "end", "-", "1" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L288-L299
21,889
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/Util.java
Util.hybridUnsignedBinarySearch
protected static int hybridUnsignedBinarySearch(final short[] array, final int begin, final int end, final short k) { int ikey = toIntUnsigned(k); // next line accelerates the possibly common case where the value would // be inserted at the end if ((end > 0) && (toIntUnsigned(array[end - 1]) < ikey)) { return -end - 1; } int low = begin; int high = end - 1; // 32 in the next line matches the size of a cache line while (low + 32 <= high) { final int middleIndex = (low + high) >>> 1; final int middleValue = toIntUnsigned(array[middleIndex]); if (middleValue < ikey) { low = middleIndex + 1; } else if (middleValue > ikey) { high = middleIndex - 1; } else { return middleIndex; } } // we finish the job with a sequential search int x = low; for (; x <= high; ++x) { final int val = toIntUnsigned(array[x]); if (val >= ikey) { if (val == ikey) { return x; } break; } } return -(x + 1); }
java
protected static int hybridUnsignedBinarySearch(final short[] array, final int begin, final int end, final short k) { int ikey = toIntUnsigned(k); // next line accelerates the possibly common case where the value would // be inserted at the end if ((end > 0) && (toIntUnsigned(array[end - 1]) < ikey)) { return -end - 1; } int low = begin; int high = end - 1; // 32 in the next line matches the size of a cache line while (low + 32 <= high) { final int middleIndex = (low + high) >>> 1; final int middleValue = toIntUnsigned(array[middleIndex]); if (middleValue < ikey) { low = middleIndex + 1; } else if (middleValue > ikey) { high = middleIndex - 1; } else { return middleIndex; } } // we finish the job with a sequential search int x = low; for (; x <= high; ++x) { final int val = toIntUnsigned(array[x]); if (val >= ikey) { if (val == ikey) { return x; } break; } } return -(x + 1); }
[ "protected", "static", "int", "hybridUnsignedBinarySearch", "(", "final", "short", "[", "]", "array", ",", "final", "int", "begin", ",", "final", "int", "end", ",", "final", "short", "k", ")", "{", "int", "ikey", "=", "toIntUnsigned", "(", "k", ")", ";", "// next line accelerates the possibly common case where the value would", "// be inserted at the end", "if", "(", "(", "end", ">", "0", ")", "&&", "(", "toIntUnsigned", "(", "array", "[", "end", "-", "1", "]", ")", "<", "ikey", ")", ")", "{", "return", "-", "end", "-", "1", ";", "}", "int", "low", "=", "begin", ";", "int", "high", "=", "end", "-", "1", ";", "// 32 in the next line matches the size of a cache line", "while", "(", "low", "+", "32", "<=", "high", ")", "{", "final", "int", "middleIndex", "=", "(", "low", "+", "high", ")", ">>>", "1", ";", "final", "int", "middleValue", "=", "toIntUnsigned", "(", "array", "[", "middleIndex", "]", ")", ";", "if", "(", "middleValue", "<", "ikey", ")", "{", "low", "=", "middleIndex", "+", "1", ";", "}", "else", "if", "(", "middleValue", ">", "ikey", ")", "{", "high", "=", "middleIndex", "-", "1", ";", "}", "else", "{", "return", "middleIndex", ";", "}", "}", "// we finish the job with a sequential search", "int", "x", "=", "low", ";", "for", "(", ";", "x", "<=", "high", ";", "++", "x", ")", "{", "final", "int", "val", "=", "toIntUnsigned", "(", "array", "[", "x", "]", ")", ";", "if", "(", "val", ">=", "ikey", ")", "{", "if", "(", "val", "==", "ikey", ")", "{", "return", "x", ";", "}", "break", ";", "}", "}", "return", "-", "(", "x", "+", "1", ")", ";", "}" ]
starts with binary search and finishes with a sequential search
[ "starts", "with", "binary", "search", "and", "finishes", "with", "a", "sequential", "search" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L363-L398
21,890
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/Util.java
Util.setBitmapRange
public static void setBitmapRange(long[] bitmap, int start, int end) { if (start == end) { return; } int firstword = start / 64; int endword = (end - 1) / 64; if (firstword == endword) { bitmap[firstword] |= (~0L << start) & (~0L >>> -end); return; } bitmap[firstword] |= ~0L << start; for (int i = firstword + 1; i < endword; i++) { bitmap[i] = ~0L; } bitmap[endword] |= ~0L >>> -end; }
java
public static void setBitmapRange(long[] bitmap, int start, int end) { if (start == end) { return; } int firstword = start / 64; int endword = (end - 1) / 64; if (firstword == endword) { bitmap[firstword] |= (~0L << start) & (~0L >>> -end); return; } bitmap[firstword] |= ~0L << start; for (int i = firstword + 1; i < endword; i++) { bitmap[i] = ~0L; } bitmap[endword] |= ~0L >>> -end; }
[ "public", "static", "void", "setBitmapRange", "(", "long", "[", "]", "bitmap", ",", "int", "start", ",", "int", "end", ")", "{", "if", "(", "start", "==", "end", ")", "{", "return", ";", "}", "int", "firstword", "=", "start", "/", "64", ";", "int", "endword", "=", "(", "end", "-", "1", ")", "/", "64", ";", "if", "(", "firstword", "==", "endword", ")", "{", "bitmap", "[", "firstword", "]", "|=", "(", "~", "0L", "<<", "start", ")", "&", "(", "~", "0L", ">>>", "-", "end", ")", ";", "return", ";", "}", "bitmap", "[", "firstword", "]", "|=", "~", "0L", "<<", "start", ";", "for", "(", "int", "i", "=", "firstword", "+", "1", ";", "i", "<", "endword", ";", "i", "++", ")", "{", "bitmap", "[", "i", "]", "=", "~", "0L", ";", "}", "bitmap", "[", "endword", "]", "|=", "~", "0L", ">>>", "-", "end", ";", "}" ]
set bits at start, start+1,..., end-1 @param bitmap array of words to be modified @param start first index to be modified (inclusive) @param end last index to be modified (exclusive)
[ "set", "bits", "at", "start", "start", "+", "1", "...", "end", "-", "1" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L501-L516
21,891
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/Util.java
Util.unsignedIntersect2by2
public static int unsignedIntersect2by2(final short[] set1, final int length1, final short[] set2, final int length2, final short[] buffer) { final int THRESHOLD = 25; if (set1.length * THRESHOLD < set2.length) { return unsignedOneSidedGallopingIntersect2by2(set1, length1, set2, length2, buffer); } else if (set2.length * THRESHOLD < set1.length) { return unsignedOneSidedGallopingIntersect2by2(set2, length2, set1, length1, buffer); } else { return unsignedLocalIntersect2by2(set1, length1, set2, length2, buffer); } }
java
public static int unsignedIntersect2by2(final short[] set1, final int length1, final short[] set2, final int length2, final short[] buffer) { final int THRESHOLD = 25; if (set1.length * THRESHOLD < set2.length) { return unsignedOneSidedGallopingIntersect2by2(set1, length1, set2, length2, buffer); } else if (set2.length * THRESHOLD < set1.length) { return unsignedOneSidedGallopingIntersect2by2(set2, length2, set1, length1, buffer); } else { return unsignedLocalIntersect2by2(set1, length1, set2, length2, buffer); } }
[ "public", "static", "int", "unsignedIntersect2by2", "(", "final", "short", "[", "]", "set1", ",", "final", "int", "length1", ",", "final", "short", "[", "]", "set2", ",", "final", "int", "length2", ",", "final", "short", "[", "]", "buffer", ")", "{", "final", "int", "THRESHOLD", "=", "25", ";", "if", "(", "set1", ".", "length", "*", "THRESHOLD", "<", "set2", ".", "length", ")", "{", "return", "unsignedOneSidedGallopingIntersect2by2", "(", "set1", ",", "length1", ",", "set2", ",", "length2", ",", "buffer", ")", ";", "}", "else", "if", "(", "set2", ".", "length", "*", "THRESHOLD", "<", "set1", ".", "length", ")", "{", "return", "unsignedOneSidedGallopingIntersect2by2", "(", "set2", ",", "length2", ",", "set1", ",", "length1", ",", "buffer", ")", ";", "}", "else", "{", "return", "unsignedLocalIntersect2by2", "(", "set1", ",", "length1", ",", "set2", ",", "length2", ",", "buffer", ")", ";", "}", "}" ]
Intersect two sorted lists and write the result to the provided output array @param set1 first array @param length1 length of first array @param set2 second array @param length2 length of second array @param buffer output array @return cardinality of the intersection
[ "Intersect", "two", "sorted", "lists", "and", "write", "the", "result", "to", "the", "provided", "output", "array" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L779-L789
21,892
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/Util.java
Util.unsignedUnion2by2
public static int unsignedUnion2by2( final short[] set1, final int offset1, final int length1, final short[] set2, final int offset2, final int length2, final short[] buffer) { if (0 == length2) { System.arraycopy(set1, offset1, buffer, 0, length1); return length1; } if (0 == length1) { System.arraycopy(set2, offset2, buffer, 0, length2); return length2; } int pos = 0; int k1 = offset1, k2 = offset2; short s1 = set1[k1]; short s2 = set2[k2]; while (true) { int v1 = toIntUnsigned(s1); int v2 = toIntUnsigned(s2); if (v1 < v2) { buffer[pos++] = s1; ++k1; if (k1 >= length1 + offset1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2 + offset2); return pos + length2 - k2 + offset2; } s1 = set1[k1]; } else if (v1 == v2) { buffer[pos++] = s1; ++k1; ++k2; if (k1 >= length1 + offset1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2 + offset2); return pos + length2 - k2 + offset2; } if (k2 >= length2 + offset2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1 + offset1); return pos + length1 - k1 + offset1; } s1 = set1[k1]; s2 = set2[k2]; } else {// if (set1[k1]>set2[k2]) buffer[pos++] = s2; ++k2; if (k2 >= length2 + offset2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1 + offset1); return pos + length1 - k1 + offset1; } s2 = set2[k2]; } } // return pos; }
java
public static int unsignedUnion2by2( final short[] set1, final int offset1, final int length1, final short[] set2, final int offset2, final int length2, final short[] buffer) { if (0 == length2) { System.arraycopy(set1, offset1, buffer, 0, length1); return length1; } if (0 == length1) { System.arraycopy(set2, offset2, buffer, 0, length2); return length2; } int pos = 0; int k1 = offset1, k2 = offset2; short s1 = set1[k1]; short s2 = set2[k2]; while (true) { int v1 = toIntUnsigned(s1); int v2 = toIntUnsigned(s2); if (v1 < v2) { buffer[pos++] = s1; ++k1; if (k1 >= length1 + offset1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2 + offset2); return pos + length2 - k2 + offset2; } s1 = set1[k1]; } else if (v1 == v2) { buffer[pos++] = s1; ++k1; ++k2; if (k1 >= length1 + offset1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2 + offset2); return pos + length2 - k2 + offset2; } if (k2 >= length2 + offset2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1 + offset1); return pos + length1 - k1 + offset1; } s1 = set1[k1]; s2 = set2[k2]; } else {// if (set1[k1]>set2[k2]) buffer[pos++] = s2; ++k2; if (k2 >= length2 + offset2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1 + offset1); return pos + length1 - k1 + offset1; } s2 = set2[k2]; } } // return pos; }
[ "public", "static", "int", "unsignedUnion2by2", "(", "final", "short", "[", "]", "set1", ",", "final", "int", "offset1", ",", "final", "int", "length1", ",", "final", "short", "[", "]", "set2", ",", "final", "int", "offset2", ",", "final", "int", "length2", ",", "final", "short", "[", "]", "buffer", ")", "{", "if", "(", "0", "==", "length2", ")", "{", "System", ".", "arraycopy", "(", "set1", ",", "offset1", ",", "buffer", ",", "0", ",", "length1", ")", ";", "return", "length1", ";", "}", "if", "(", "0", "==", "length1", ")", "{", "System", ".", "arraycopy", "(", "set2", ",", "offset2", ",", "buffer", ",", "0", ",", "length2", ")", ";", "return", "length2", ";", "}", "int", "pos", "=", "0", ";", "int", "k1", "=", "offset1", ",", "k2", "=", "offset2", ";", "short", "s1", "=", "set1", "[", "k1", "]", ";", "short", "s2", "=", "set2", "[", "k2", "]", ";", "while", "(", "true", ")", "{", "int", "v1", "=", "toIntUnsigned", "(", "s1", ")", ";", "int", "v2", "=", "toIntUnsigned", "(", "s2", ")", ";", "if", "(", "v1", "<", "v2", ")", "{", "buffer", "[", "pos", "++", "]", "=", "s1", ";", "++", "k1", ";", "if", "(", "k1", ">=", "length1", "+", "offset1", ")", "{", "System", ".", "arraycopy", "(", "set2", ",", "k2", ",", "buffer", ",", "pos", ",", "length2", "-", "k2", "+", "offset2", ")", ";", "return", "pos", "+", "length2", "-", "k2", "+", "offset2", ";", "}", "s1", "=", "set1", "[", "k1", "]", ";", "}", "else", "if", "(", "v1", "==", "v2", ")", "{", "buffer", "[", "pos", "++", "]", "=", "s1", ";", "++", "k1", ";", "++", "k2", ";", "if", "(", "k1", ">=", "length1", "+", "offset1", ")", "{", "System", ".", "arraycopy", "(", "set2", ",", "k2", ",", "buffer", ",", "pos", ",", "length2", "-", "k2", "+", "offset2", ")", ";", "return", "pos", "+", "length2", "-", "k2", "+", "offset2", ";", "}", "if", "(", "k2", ">=", "length2", "+", "offset2", ")", "{", "System", ".", "arraycopy", "(", "set1", ",", "k1", ",", "buffer", ",", "pos", ",", "length1", "-", "k1", "+", "offset1", ")", ";", "return", "pos", "+", "length1", "-", "k1", "+", "offset1", ";", "}", "s1", "=", "set1", "[", "k1", "]", ";", "s2", "=", "set2", "[", "k2", "]", ";", "}", "else", "{", "// if (set1[k1]>set2[k2])", "buffer", "[", "pos", "++", "]", "=", "s2", ";", "++", "k2", ";", "if", "(", "k2", ">=", "length2", "+", "offset2", ")", "{", "System", ".", "arraycopy", "(", "set1", ",", "k1", ",", "buffer", ",", "pos", ",", "length1", "-", "k1", "+", "offset1", ")", ";", "return", "pos", "+", "length1", "-", "k1", "+", "offset1", ";", "}", "s2", "=", "set2", "[", "k2", "]", ";", "}", "}", "// return pos;", "}" ]
Unite two sorted lists and write the result to the provided output array @param set1 first array @param offset1 offset of first array @param length1 length of first array @param set2 second array @param offset2 offset of second array @param length2 length of second array @param buffer output array @return cardinality of the union
[ "Unite", "two", "sorted", "lists", "and", "write", "the", "result", "to", "the", "provided", "output", "array" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L1005-L1057
21,893
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/Util.java
Util.partialRadixSort
public static void partialRadixSort(int[] data) { final int radix = 8; int shift = 16; int mask = 0xFF0000; int[] copy = new int[data.length]; int[] histogram = new int[(1 << radix) + 1]; while (shift < 32) { for (int i = 0; i < data.length; ++i) { ++histogram[((data[i] & mask) >>> shift) + 1]; } for (int i = 0; i < 1 << radix; ++i) { histogram[i + 1] += histogram[i]; } for (int i = 0; i < data.length; ++i) { copy[histogram[(data[i] & mask) >>> shift]++] = data[i]; } System.arraycopy(copy, 0, data, 0, data.length); shift += radix; mask <<= radix; Arrays.fill(histogram, 0); } }
java
public static void partialRadixSort(int[] data) { final int radix = 8; int shift = 16; int mask = 0xFF0000; int[] copy = new int[data.length]; int[] histogram = new int[(1 << radix) + 1]; while (shift < 32) { for (int i = 0; i < data.length; ++i) { ++histogram[((data[i] & mask) >>> shift) + 1]; } for (int i = 0; i < 1 << radix; ++i) { histogram[i + 1] += histogram[i]; } for (int i = 0; i < data.length; ++i) { copy[histogram[(data[i] & mask) >>> shift]++] = data[i]; } System.arraycopy(copy, 0, data, 0, data.length); shift += radix; mask <<= radix; Arrays.fill(histogram, 0); } }
[ "public", "static", "void", "partialRadixSort", "(", "int", "[", "]", "data", ")", "{", "final", "int", "radix", "=", "8", ";", "int", "shift", "=", "16", ";", "int", "mask", "=", "0xFF0000", ";", "int", "[", "]", "copy", "=", "new", "int", "[", "data", ".", "length", "]", ";", "int", "[", "]", "histogram", "=", "new", "int", "[", "(", "1", "<<", "radix", ")", "+", "1", "]", ";", "while", "(", "shift", "<", "32", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "++", "i", ")", "{", "++", "histogram", "[", "(", "(", "data", "[", "i", "]", "&", "mask", ")", ">>>", "shift", ")", "+", "1", "]", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "1", "<<", "radix", ";", "++", "i", ")", "{", "histogram", "[", "i", "+", "1", "]", "+=", "histogram", "[", "i", "]", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "++", "i", ")", "{", "copy", "[", "histogram", "[", "(", "data", "[", "i", "]", "&", "mask", ")", ">>>", "shift", "]", "++", "]", "=", "data", "[", "i", "]", ";", "}", "System", ".", "arraycopy", "(", "copy", ",", "0", ",", "data", ",", "0", ",", "data", ".", "length", ")", ";", "shift", "+=", "radix", ";", "mask", "<<=", "radix", ";", "Arrays", ".", "fill", "(", "histogram", ",", "0", ")", ";", "}", "}" ]
Sorts the data by the 16 bit prefix. @param data - the data
[ "Sorts", "the", "data", "by", "the", "16", "bit", "prefix", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L1082-L1103
21,894
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
RoaringBitmap.bitmapOfUnordered
public static RoaringBitmap bitmapOfUnordered(final int... data) { RoaringBitmapWriter<RoaringBitmap> writer = writer().constantMemory() .doPartialRadixSort().get(); writer.addMany(data); writer.flush(); return writer.getUnderlying(); }
java
public static RoaringBitmap bitmapOfUnordered(final int... data) { RoaringBitmapWriter<RoaringBitmap> writer = writer().constantMemory() .doPartialRadixSort().get(); writer.addMany(data); writer.flush(); return writer.getUnderlying(); }
[ "public", "static", "RoaringBitmap", "bitmapOfUnordered", "(", "final", "int", "...", "data", ")", "{", "RoaringBitmapWriter", "<", "RoaringBitmap", ">", "writer", "=", "writer", "(", ")", ".", "constantMemory", "(", ")", ".", "doPartialRadixSort", "(", ")", ".", "get", "(", ")", ";", "writer", ".", "addMany", "(", "data", ")", ";", "writer", ".", "flush", "(", ")", ";", "return", "writer", ".", "getUnderlying", "(", ")", ";", "}" ]
Efficiently builds a RoaringBitmap from unordered data @param data unsorted data @return a new bitmap
[ "Efficiently", "builds", "a", "RoaringBitmap", "from", "unordered", "data" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java#L536-L542
21,895
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
RoaringBitmap.intersects
public static boolean intersects(final RoaringBitmap x1, final RoaringBitmap x2) { final int length1 = x1.highLowContainer.size(), length2 = x2.highLowContainer.size(); int pos1 = 0, pos2 = 0; while (pos1 < length1 && pos2 < length2) { final short s1 = x1.highLowContainer.getKeyAtIndex(pos1); final short s2 = x2.highLowContainer.getKeyAtIndex(pos2); if (s1 == s2) { final Container c1 = x1.highLowContainer.getContainerAtIndex(pos1); final Container c2 = x2.highLowContainer.getContainerAtIndex(pos2); if (c1.intersects(c2)) { return true; } ++pos1; ++pos2; } else if (Util.compareUnsigned(s1, s2) < 0) { // s1 < s2 pos1 = x1.highLowContainer.advanceUntil(s2, pos1); } else { // s1 > s2 pos2 = x2.highLowContainer.advanceUntil(s1, pos2); } } return false; }
java
public static boolean intersects(final RoaringBitmap x1, final RoaringBitmap x2) { final int length1 = x1.highLowContainer.size(), length2 = x2.highLowContainer.size(); int pos1 = 0, pos2 = 0; while (pos1 < length1 && pos2 < length2) { final short s1 = x1.highLowContainer.getKeyAtIndex(pos1); final short s2 = x2.highLowContainer.getKeyAtIndex(pos2); if (s1 == s2) { final Container c1 = x1.highLowContainer.getContainerAtIndex(pos1); final Container c2 = x2.highLowContainer.getContainerAtIndex(pos2); if (c1.intersects(c2)) { return true; } ++pos1; ++pos2; } else if (Util.compareUnsigned(s1, s2) < 0) { // s1 < s2 pos1 = x1.highLowContainer.advanceUntil(s2, pos1); } else { // s1 > s2 pos2 = x2.highLowContainer.advanceUntil(s1, pos2); } } return false; }
[ "public", "static", "boolean", "intersects", "(", "final", "RoaringBitmap", "x1", ",", "final", "RoaringBitmap", "x2", ")", "{", "final", "int", "length1", "=", "x1", ".", "highLowContainer", ".", "size", "(", ")", ",", "length2", "=", "x2", ".", "highLowContainer", ".", "size", "(", ")", ";", "int", "pos1", "=", "0", ",", "pos2", "=", "0", ";", "while", "(", "pos1", "<", "length1", "&&", "pos2", "<", "length2", ")", "{", "final", "short", "s1", "=", "x1", ".", "highLowContainer", ".", "getKeyAtIndex", "(", "pos1", ")", ";", "final", "short", "s2", "=", "x2", ".", "highLowContainer", ".", "getKeyAtIndex", "(", "pos2", ")", ";", "if", "(", "s1", "==", "s2", ")", "{", "final", "Container", "c1", "=", "x1", ".", "highLowContainer", ".", "getContainerAtIndex", "(", "pos1", ")", ";", "final", "Container", "c2", "=", "x2", ".", "highLowContainer", ".", "getContainerAtIndex", "(", "pos2", ")", ";", "if", "(", "c1", ".", "intersects", "(", "c2", ")", ")", "{", "return", "true", ";", "}", "++", "pos1", ";", "++", "pos2", ";", "}", "else", "if", "(", "Util", ".", "compareUnsigned", "(", "s1", ",", "s2", ")", "<", "0", ")", "{", "// s1 < s2", "pos1", "=", "x1", ".", "highLowContainer", ".", "advanceUntil", "(", "s2", ",", "pos1", ")", ";", "}", "else", "{", "// s1 > s2", "pos2", "=", "x2", ".", "highLowContainer", ".", "advanceUntil", "(", "s1", ",", "pos2", ")", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether the two bitmaps intersect. This can be much faster than calling "and" and checking the cardinality of the result. @param x1 first bitmap @param x2 other bitmap @return true if they intersect
[ "Checks", "whether", "the", "two", "bitmaps", "intersect", ".", "This", "can", "be", "much", "faster", "than", "calling", "and", "and", "checking", "the", "cardinality", "of", "the", "result", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java#L625-L647
21,896
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
RoaringBitmap.add
public void add(final long rangeStart, final long rangeEnd) { rangeSanityCheck(rangeStart, rangeEnd); if (rangeStart >= rangeEnd) { return; // empty range } final int hbStart = Util.toIntUnsigned(Util.highbits(rangeStart)); final int lbStart = Util.toIntUnsigned(Util.lowbits(rangeStart)); final int hbLast = Util.toIntUnsigned(Util.highbits(rangeEnd - 1)); final int lbLast = Util.toIntUnsigned(Util.lowbits(rangeEnd - 1)); for (int hb = hbStart; hb <= hbLast; ++hb) { // first container may contain partial range final int containerStart = (hb == hbStart) ? lbStart : 0; // last container may contain partial range final int containerLast = (hb == hbLast) ? lbLast : Util.maxLowBitAsInteger(); final int i = highLowContainer.getIndex((short) hb); if (i >= 0) { final Container c = highLowContainer.getContainerAtIndex(i).iadd(containerStart, containerLast + 1); highLowContainer.setContainerAtIndex(i, c); } else { highLowContainer.insertNewKeyValueAt(-i - 1, (short) hb, Container.rangeOfOnes(containerStart, containerLast + 1)); } } }
java
public void add(final long rangeStart, final long rangeEnd) { rangeSanityCheck(rangeStart, rangeEnd); if (rangeStart >= rangeEnd) { return; // empty range } final int hbStart = Util.toIntUnsigned(Util.highbits(rangeStart)); final int lbStart = Util.toIntUnsigned(Util.lowbits(rangeStart)); final int hbLast = Util.toIntUnsigned(Util.highbits(rangeEnd - 1)); final int lbLast = Util.toIntUnsigned(Util.lowbits(rangeEnd - 1)); for (int hb = hbStart; hb <= hbLast; ++hb) { // first container may contain partial range final int containerStart = (hb == hbStart) ? lbStart : 0; // last container may contain partial range final int containerLast = (hb == hbLast) ? lbLast : Util.maxLowBitAsInteger(); final int i = highLowContainer.getIndex((short) hb); if (i >= 0) { final Container c = highLowContainer.getContainerAtIndex(i).iadd(containerStart, containerLast + 1); highLowContainer.setContainerAtIndex(i, c); } else { highLowContainer.insertNewKeyValueAt(-i - 1, (short) hb, Container.rangeOfOnes(containerStart, containerLast + 1)); } } }
[ "public", "void", "add", "(", "final", "long", "rangeStart", ",", "final", "long", "rangeEnd", ")", "{", "rangeSanityCheck", "(", "rangeStart", ",", "rangeEnd", ")", ";", "if", "(", "rangeStart", ">=", "rangeEnd", ")", "{", "return", ";", "// empty range", "}", "final", "int", "hbStart", "=", "Util", ".", "toIntUnsigned", "(", "Util", ".", "highbits", "(", "rangeStart", ")", ")", ";", "final", "int", "lbStart", "=", "Util", ".", "toIntUnsigned", "(", "Util", ".", "lowbits", "(", "rangeStart", ")", ")", ";", "final", "int", "hbLast", "=", "Util", ".", "toIntUnsigned", "(", "Util", ".", "highbits", "(", "rangeEnd", "-", "1", ")", ")", ";", "final", "int", "lbLast", "=", "Util", ".", "toIntUnsigned", "(", "Util", ".", "lowbits", "(", "rangeEnd", "-", "1", ")", ")", ";", "for", "(", "int", "hb", "=", "hbStart", ";", "hb", "<=", "hbLast", ";", "++", "hb", ")", "{", "// first container may contain partial range", "final", "int", "containerStart", "=", "(", "hb", "==", "hbStart", ")", "?", "lbStart", ":", "0", ";", "// last container may contain partial range", "final", "int", "containerLast", "=", "(", "hb", "==", "hbLast", ")", "?", "lbLast", ":", "Util", ".", "maxLowBitAsInteger", "(", ")", ";", "final", "int", "i", "=", "highLowContainer", ".", "getIndex", "(", "(", "short", ")", "hb", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "final", "Container", "c", "=", "highLowContainer", ".", "getContainerAtIndex", "(", "i", ")", ".", "iadd", "(", "containerStart", ",", "containerLast", "+", "1", ")", ";", "highLowContainer", ".", "setContainerAtIndex", "(", "i", ",", "c", ")", ";", "}", "else", "{", "highLowContainer", ".", "insertNewKeyValueAt", "(", "-", "i", "-", "1", ",", "(", "short", ")", "hb", ",", "Container", ".", "rangeOfOnes", "(", "containerStart", ",", "containerLast", "+", "1", ")", ")", ";", "}", "}", "}" ]
Add to the current bitmap all integers in [rangeStart,rangeEnd). @param rangeStart inclusive beginning of range @param rangeEnd exclusive ending of range
[ "Add", "to", "the", "current", "bitmap", "all", "integers", "in", "[", "rangeStart", "rangeEnd", ")", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java#L1069-L1096
21,897
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
RoaringBitmap.isHammingSimilar
public boolean isHammingSimilar(RoaringBitmap other, int tolerance) { final int size1 = highLowContainer.size(); final int size2 = other.highLowContainer.size(); int pos1 = 0; int pos2 = 0; int budget = tolerance; while(budget >= 0 && pos1 < size1 && pos2 < size2) { final short key1 = this.highLowContainer.getKeyAtIndex(pos1); final short key2 = other.highLowContainer.getKeyAtIndex(pos2); Container left = highLowContainer.getContainerAtIndex(pos1); Container right = other.highLowContainer.getContainerAtIndex(pos2); if(key1 == key2) { budget -= left.xorCardinality(right); ++pos1; ++pos2; } else if(Util.compareUnsigned(key1, key2) < 0) { budget -= left.getCardinality(); ++pos1; } else { budget -= right.getCardinality(); ++pos2; } } while(budget >= 0 && pos1 < size1) { Container container = highLowContainer.getContainerAtIndex(pos1++); budget -= container.getCardinality(); } while(budget >= 0 && pos2 < size2) { Container container = other.highLowContainer.getContainerAtIndex(pos2++); budget -= container.getCardinality(); } return budget >= 0; }
java
public boolean isHammingSimilar(RoaringBitmap other, int tolerance) { final int size1 = highLowContainer.size(); final int size2 = other.highLowContainer.size(); int pos1 = 0; int pos2 = 0; int budget = tolerance; while(budget >= 0 && pos1 < size1 && pos2 < size2) { final short key1 = this.highLowContainer.getKeyAtIndex(pos1); final short key2 = other.highLowContainer.getKeyAtIndex(pos2); Container left = highLowContainer.getContainerAtIndex(pos1); Container right = other.highLowContainer.getContainerAtIndex(pos2); if(key1 == key2) { budget -= left.xorCardinality(right); ++pos1; ++pos2; } else if(Util.compareUnsigned(key1, key2) < 0) { budget -= left.getCardinality(); ++pos1; } else { budget -= right.getCardinality(); ++pos2; } } while(budget >= 0 && pos1 < size1) { Container container = highLowContainer.getContainerAtIndex(pos1++); budget -= container.getCardinality(); } while(budget >= 0 && pos2 < size2) { Container container = other.highLowContainer.getContainerAtIndex(pos2++); budget -= container.getCardinality(); } return budget >= 0; }
[ "public", "boolean", "isHammingSimilar", "(", "RoaringBitmap", "other", ",", "int", "tolerance", ")", "{", "final", "int", "size1", "=", "highLowContainer", ".", "size", "(", ")", ";", "final", "int", "size2", "=", "other", ".", "highLowContainer", ".", "size", "(", ")", ";", "int", "pos1", "=", "0", ";", "int", "pos2", "=", "0", ";", "int", "budget", "=", "tolerance", ";", "while", "(", "budget", ">=", "0", "&&", "pos1", "<", "size1", "&&", "pos2", "<", "size2", ")", "{", "final", "short", "key1", "=", "this", ".", "highLowContainer", ".", "getKeyAtIndex", "(", "pos1", ")", ";", "final", "short", "key2", "=", "other", ".", "highLowContainer", ".", "getKeyAtIndex", "(", "pos2", ")", ";", "Container", "left", "=", "highLowContainer", ".", "getContainerAtIndex", "(", "pos1", ")", ";", "Container", "right", "=", "other", ".", "highLowContainer", ".", "getContainerAtIndex", "(", "pos2", ")", ";", "if", "(", "key1", "==", "key2", ")", "{", "budget", "-=", "left", ".", "xorCardinality", "(", "right", ")", ";", "++", "pos1", ";", "++", "pos2", ";", "}", "else", "if", "(", "Util", ".", "compareUnsigned", "(", "key1", ",", "key2", ")", "<", "0", ")", "{", "budget", "-=", "left", ".", "getCardinality", "(", ")", ";", "++", "pos1", ";", "}", "else", "{", "budget", "-=", "right", ".", "getCardinality", "(", ")", ";", "++", "pos2", ";", "}", "}", "while", "(", "budget", ">=", "0", "&&", "pos1", "<", "size1", ")", "{", "Container", "container", "=", "highLowContainer", ".", "getContainerAtIndex", "(", "pos1", "++", ")", ";", "budget", "-=", "container", ".", "getCardinality", "(", ")", ";", "}", "while", "(", "budget", ">=", "0", "&&", "pos2", "<", "size2", ")", "{", "Container", "container", "=", "other", ".", "highLowContainer", ".", "getContainerAtIndex", "(", "pos2", "++", ")", ";", "budget", "-=", "container", ".", "getCardinality", "(", ")", ";", "}", "return", "budget", ">=", "0", ";", "}" ]
Returns true if the other bitmap has no more than tolerance bits differing from this bitmap. The other may be transformed into a bitmap equal to this bitmap in no more than tolerance bit flips if this method returns true. @param other the bitmap to compare to @param tolerance the maximum number of bits that may differ @return true if the number of differing bits is smaller than tolerance
[ "Returns", "true", "if", "the", "other", "bitmap", "has", "no", "more", "than", "tolerance", "bits", "differing", "from", "this", "bitmap", ".", "The", "other", "may", "be", "transformed", "into", "a", "bitmap", "equal", "to", "this", "bitmap", "in", "no", "more", "than", "tolerance", "bit", "flips", "if", "this", "method", "returns", "true", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java#L1515-L1547
21,898
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
RoaringBitmap.hasRunCompression
public boolean hasRunCompression() { for (int i = 0; i < this.highLowContainer.size(); i++) { Container c = this.highLowContainer.getContainerAtIndex(i); if (c instanceof RunContainer) { return true; } } return false; }
java
public boolean hasRunCompression() { for (int i = 0; i < this.highLowContainer.size(); i++) { Container c = this.highLowContainer.getContainerAtIndex(i); if (c instanceof RunContainer) { return true; } } return false; }
[ "public", "boolean", "hasRunCompression", "(", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "highLowContainer", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Container", "c", "=", "this", ".", "highLowContainer", ".", "getContainerAtIndex", "(", "i", ")", ";", "if", "(", "c", "instanceof", "RunContainer", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check whether this bitmap has had its runs compressed. @return whether this bitmap has run compression
[ "Check", "whether", "this", "bitmap", "has", "had", "its", "runs", "compressed", "." ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java#L1793-L1801
21,899
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
RoaringBitmap.runOptimize
public boolean runOptimize() { boolean answer = false; for (int i = 0; i < this.highLowContainer.size(); i++) { Container c = this.highLowContainer.getContainerAtIndex(i).runOptimize(); if (c instanceof RunContainer) { answer = true; } this.highLowContainer.setContainerAtIndex(i, c); } return answer; }
java
public boolean runOptimize() { boolean answer = false; for (int i = 0; i < this.highLowContainer.size(); i++) { Container c = this.highLowContainer.getContainerAtIndex(i).runOptimize(); if (c instanceof RunContainer) { answer = true; } this.highLowContainer.setContainerAtIndex(i, c); } return answer; }
[ "public", "boolean", "runOptimize", "(", ")", "{", "boolean", "answer", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "highLowContainer", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Container", "c", "=", "this", ".", "highLowContainer", ".", "getContainerAtIndex", "(", "i", ")", ".", "runOptimize", "(", ")", ";", "if", "(", "c", "instanceof", "RunContainer", ")", "{", "answer", "=", "true", ";", "}", "this", ".", "highLowContainer", ".", "setContainerAtIndex", "(", "i", ",", "c", ")", ";", "}", "return", "answer", ";", "}" ]
Use a run-length encoding where it is more space efficient @return whether a change was applied
[ "Use", "a", "run", "-", "length", "encoding", "where", "it", "is", "more", "space", "efficient" ]
b26fd0a1330fd4d2877f4d74feb69ceb812e9efa
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java#L2270-L2280