Skip to content

Apache Lucene open-source search software

build: fix/reformat python sources (#15651)

Robert Muir77744c0850bf
diff --git a/.pre-commit-config.yml b/.pre-commit-config.yml
index d5028cc05fb..085857dd376 100644
--- a/.pre-commit-config.yml
+++ b/.pre-commit-config.yml
@@ -195,17 +195,6 @@ repos:
UV_FROZEN: "1"
types_or: [ python, pyi, jupyter ]
require_serial: true
- exclude:
- glob:
- # TODO: fix the issues with these files separately
- - gradle/regenerate/jflex/htmlentity.py
- - gradle/regenerate/packed/gen_BulkOperation.py
- - gradle/regenerate/moman/createLevAutomata.py
- - lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/**/{gen_ForUtil.py,gen_ForDeltaUtil.py}
- - lucene/core/src/java/org/apache/lucene/codecs/**/gen_ForUtil.py
- - lucene/core/src/java/org/apache/lucene/util/automaton/UTF32ToUTF8.py
- - lucene/core/src/java/org/apache/lucene/util/packed/gen_BulkOperation.py
- - lucene/core/src/test/org/apache/lucene/util/makeEuroparlLineFile.py
- id: ruff-format
language: system
@@ -217,17 +206,6 @@ repos:
UV_FROZEN: "1"
types_or: [ python, pyi, jupyter ]
require_serial: true
- exclude:
- glob:
- # TODO: fix the formatting of these files separately
- - gradle/regenerate/jflex/htmlentity.py
- - gradle/regenerate/moman/createLevAutomata.py
- - gradle/regenerate/packed/{gen_BulkOperation.py,gen_Packed64SingleBlock.py}
- - lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/**/{gen_ForUtil.py,gen_ForDeltaUtil.py}
- - lucene/core/src/java/org/apache/lucene/codecs/**/gen_ForUtil.py
- - lucene/core/src/java/org/apache/lucene/util/packed/{gen_BulkOperation.py,gen_Packed64SingleBlock.py}
- - lucene/core/src/java/org/apache/lucene/util/automaton/UTF32ToUTF8.py
- - lucene/core/src/test/org/apache/lucene/util/makeEuroparlLineFile.py
- id: test-ast-grep
name: Check ast-grep rules
diff --git a/gradle/regenerate/jflex/htmlentity.py b/gradle/regenerate/jflex/htmlentity.py
index c74aabd5180..a81a2ecf209 100644
--- a/gradle/regenerate/jflex/htmlentity.py
+++ b/gradle/regenerate/jflex/htmlentity.py
@@ -19,79 +19,86 @@ import sys
# A simple python script to generate an HTML entity map and a regex alternation
# for inclusion in HTMLStripCharFilter.jflex.
+
def main():
- with open(sys.argv[1], 'w') as f:
- sys.stdout = f
-
- print(get_apache_license())
- codes = {}
- regex = re.compile(r'\s*<!ENTITY\s+(\S+)\s+"&(?:#38;)?#(\d+);"')
- for line in get_entity_text().split('\n'):
- match = regex.match(line)
- if match:
- key = match.group(1)
- if key == 'quot': codes[key] = r'\"'
- elif key == 'nbsp': codes[key] = ' ';
- else : codes[key] = r'\u%04X' % int(match.group(2))
-
- keys = sorted(codes)
-
- first_entry = True
- output_line = 'CharacterEntities = ( '
- for key in keys:
- new_entry = ('"%s"' if first_entry else ' | "%s"') % key
- first_entry = False
- if len(output_line) + len(new_entry) >= 80:
- print(output_line)
- output_line = ' '
- output_line += new_entry
- if key in ('quot','copy','gt','lt','reg','amp'):
- new_entry = ' | "%s"' % key.upper()
- if len(output_line) + len(new_entry) >= 80:
- print(output_line)
- output_line = ' '
- output_line += new_entry
- print(output_line, ')')
-
- print('%{')
- print(' private static final Map<String,String> upperCaseVariantsAccepted')
- print(' = new HashMap<>();')
- print(' static {')
- print(' upperCaseVariantsAccepted.put("quot", "QUOT");')
- print(' upperCaseVariantsAccepted.put("copy", "COPY");')
- print(' upperCaseVariantsAccepted.put("gt", "GT");')
- print(' upperCaseVariantsAccepted.put("lt", "LT");')
- print(' upperCaseVariantsAccepted.put("reg", "REG");')
- print(' upperCaseVariantsAccepted.put("amp", "AMP");')
- print(' }')
- print(' private static final CharArrayMap<Character> entityValues')
- print(' = new CharArrayMap<>(%i, false);' % len(keys))
- print(' static {')
- print(' String[] entities = {')
- output_line = ' '
- for key in keys:
- new_entry = ' "%s", "%s",' % (key, codes[key])
- if len(output_line) + len(new_entry) >= 80:
- print(output_line)
- output_line = ' '
- output_line += new_entry
- print(output_line[:-1])
- print(' };')
- print(' for (int i = 0 ; i < entities.length ; i += 2) {')
- print(' Character value = entities[i + 1].charAt(0);')
- print(' entityValues.put(entities[i], value);')
- print(' String upperCaseVariant = upperCaseVariantsAccepted.get(entities[i]);')
- print(' if (upperCaseVariant != null) {')
- print(' entityValues.put(upperCaseVariant, value);')
- print(' }')
- print(' }')
- print(" }")
- print("%}")
+ with open(sys.argv[1], "w") as f:
+ sys.stdout = f
+
+ print(get_apache_license())
+ codes = {}
+ regex = re.compile(r'\s*<!ENTITY\s+(\S+)\s+"&(?:#38;)?#(\d+);"')
+ for line in get_entity_text().split("\n"):
+ match = regex.match(line)
+ if match:
+ key = match.group(1)
+ if key == "quot":
+ codes[key] = r"\""
+ elif key == "nbsp":
+ codes[key] = " "
+ else:
+ codes[key] = r"\u%04X" % int(match.group(2))
+
+ keys = sorted(codes)
+
+ first_entry = True
+ output_line = "CharacterEntities = ( "
+ for key in keys:
+ new_entry = ('"%s"' if first_entry else ' | "%s"') % key
+ first_entry = False
+ if len(output_line) + len(new_entry) >= 80:
+ print(output_line)
+ output_line = " "
+ output_line += new_entry
+ if key in ("quot", "copy", "gt", "lt", "reg", "amp"):
+ new_entry = ' | "%s"' % key.upper()
+ if len(output_line) + len(new_entry) >= 80:
+ print(output_line)
+ output_line = " "
+ output_line += new_entry
+ print(output_line, ")")
+
+ print("%{")
+ print(" private static final Map<String,String> upperCaseVariantsAccepted")
+ print(" = new HashMap<>();")
+ print(" static {")
+ print(' upperCaseVariantsAccepted.put("quot", "QUOT");')
+ print(' upperCaseVariantsAccepted.put("copy", "COPY");')
+ print(' upperCaseVariantsAccepted.put("gt", "GT");')
+ print(' upperCaseVariantsAccepted.put("lt", "LT");')
+ print(' upperCaseVariantsAccepted.put("reg", "REG");')
+ print(' upperCaseVariantsAccepted.put("amp", "AMP");')
+ print(" }")
+ print(" private static final CharArrayMap<Character> entityValues")
+ print(" = new CharArrayMap<>(%i, false);" % len(keys))
+ print(" static {")
+ print(" String[] entities = {")
+ output_line = " "
+ for key in keys:
+ new_entry = ' "%s", "%s",' % (key, codes[key])
+ if len(output_line) + len(new_entry) >= 80:
+ print(output_line)
+ output_line = " "
+ output_line += new_entry
+ print(output_line[:-1])
+ print(" };")
+ print(" for (int i = 0 ; i < entities.length ; i += 2) {")
+ print(" Character value = entities[i + 1].charAt(0);")
+ print(" entityValues.put(entities[i], value);")
+ print(
+ " String upperCaseVariant = upperCaseVariantsAccepted.get(entities[i]);"
+ )
+ print(" if (upperCaseVariant != null) {")
+ print(" entityValues.put(upperCaseVariant, value);")
+ print(" }")
+ print(" }")
+ print(" }")
+ print("%}")
+
def get_entity_text():
-# The text below is taken verbatim from
-# <http://www.w3.org/TR/REC-html40/sgml/entities.html>:
- text = r"""
+ # The text below is taken verbatim from
+ # <http://www.w3.org/TR/REC-html40/sgml/entities.html>:
+ text = r"""
F.1. XHTML Character Entities
XHTML DTDs make available a standard collection of named character entities. Those entities are defined in this section.
@@ -517,10 +524,11 @@ You can download this version of this file from http://www.w3.org/TR/2010/REC-xh
<!-- end of xhtml-symbol.ent -->
"""
- return text
+ return text
+
def get_apache_license():
- license = r"""/*
+ license = r"""/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
@@ -538,6 +546,7 @@ def get_apache_license():
*/
"""
- return license
+ return license
+
main()
diff --git a/gradle/regenerate/moman/createLevAutomata.py b/gradle/regenerate/moman/createLevAutomata.py
index f90b68ba9bc..8be9a68a8fe 100644
--- a/gradle/regenerate/moman/createLevAutomata.py
+++ b/gradle/regenerate/moman/createLevAutomata.py
@@ -23,11 +23,11 @@ import os
import sys
-MODE = 'array'
+MODE = "array"
PACKED = True
WORD = 64
LOG2_WORD = int(math.log(WORD) / math.log(2))
-HEADER_COMMENT = '''/*
+HEADER_COMMENT = """/*
Parametric transitions for LEV1.
┏━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
┃ char vector ┃ State 0 ┃ State 1 ┃ State 2 ┃ State 3 ┃ State 4 ┃
@@ -43,9 +43,9 @@ HEADER_COMMENT = '''/*
We store this table in toState and offsetIncr.
toState = [ i+1 | for entry in entries].
offsetIncrs = [j | for entry in entries].
-*/'''
+*/"""
-STATE0_COMMENT = '''/*
+STATE0_COMMENT = """/*
* 1 vectors; 2 states per vector; array length = 2
* Parametric transitions for LEV1 (position = w)
* ┏━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
@@ -53,9 +53,9 @@ STATE0_COMMENT = '''/*
* ┡━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━┩
* │ () │ (1, 0) │ (-1, 0) │
* └─────────────┴─────────┴─────────┘
- */'''
+ */"""
-STATE1_COMMENT = '''/*
+STATE1_COMMENT = """/*
* 2 vectors; 3 states per vector; array length = 6
* Parametric transitions for LEV1 (position = w-1)
* ┏━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
@@ -64,8 +64,8 @@ STATE1_COMMENT = '''/*
* │ (0) │ (2, 0) │ (-1, 0) │ (-1, 0) │
* │ (1) │ (0, 1) │ (1, 1) │ (1, 1) │
* └─────────────┴─────────┴─────────┴─────────┘
- */'''
-STATE2_COMMENT = '''/*
+ */"""
+STATE2_COMMENT = """/*
* 4 vectors; 5 states per vector; array length = 20
* Parametric transitions for LEV1 ( position == w-2 )
* ┏━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
@@ -76,8 +76,8 @@ STATE2_COMMENT = '''/*
* │ (1,0) │ (0, 1) │ (1, 1) │ (1, 1) │ (1, 1) │ (1, 1) │
* │ (1,1) │ (0, 1) │ (1, 1) │ (2, 1) │ (2, 1) │ (1, 1) │
* └─────────────┴─────────┴─────────┴─────────┴─────────┴─────────┘
- */'''
-STATE3_COMMENT = '''/*
+ */"""
+STATE3_COMMENT = """/*
* 8 vectors; 5 states per vector; array length = 40
* Parametric transitions for LEV1 (0 <= position <= w-3 )
* ┏━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
@@ -92,493 +92,549 @@ STATE3_COMMENT = '''/*
* │ (1,1,0) │ (0, 1) │ (1, 1) │ (2, 1) │ (2, 1) │ (1, 1) │
* │ (1,1,1) │ (0, 1) │ (1, 1) │ (2, 1) │ (3, 1) │ (4, 1) │
* └─────────────┴─────────┴─────────┴─────────┴─────────┴─────────┘
- */'''
+ */"""
STATE_COMMENT = [STATE0_COMMENT, STATE1_COMMENT, STATE2_COMMENT, STATE3_COMMENT]
# MODE = 'switch'
+
class LineOutput:
+ def __init__(self, indent=""):
+ self.l = []
+ self._indent = self.startIndent = indent
+ self.inComment = False
- def __init__(self, indent=''):
- self.l = []
- self._indent = self.startIndent = indent
- self.inComment = False
+ def __call__(self, s, indent=0):
+ if s.find("}") != -1:
+ assert self._indent != self.startIndent
+ self._indent = self._indent[:-2]
- def __call__(self, s, indent=0):
- if s.find('}') != -1:
- assert self._indent != self.startIndent
- self._indent = self._indent[:-2]
+ if indent != 0:
+ indent0 = " " * (len(self._indent) // 2 + indent)
+ else:
+ indent0 = self._indent
- if indent != 0:
- indent0 = ' ' * (len(self._indent) // 2 + indent)
- else:
- indent0 = self._indent
+ if s.find("/*") != -1:
+ if s.find("*/") == -1:
+ self.inComment = True
+ elif s.find("*/") != -1:
+ self.inComment = True
- if s.find('/*') != -1:
- if s.find('*/') == -1:
- self.inComment = True
- elif s.find('*/') != -1:
- self.inComment = True
+ if self.inComment:
+ self.l.append(indent0 + s)
+ else:
+ self.l.append(indent0 + s.lstrip())
- if self.inComment:
- self.l.append(indent0 + s)
- else:
- self.l.append(indent0 + s.lstrip())
+ self.inComment = self.inComment and s.find("*/") == -1
- self.inComment = self.inComment and s.find('*/') == -1
+ if s.find("{") != -1:
+ self._indent += " "
- if s.find('{') != -1:
- self._indent += ' '
+ def __str__(self):
+ if True:
+ assert self._indent == self.startIndent, "indent %d vs start indent %d" % (
+ len(self._indent),
+ len(self.startIndent),
+ )
+ return "\n".join(self.l)
- def __str__(self):
- if True:
- assert self._indent == self.startIndent, 'indent %d vs start indent %d' % \
- (len(self._indent), len(self.startIndent))
- return '\n'.join(self.l)
+ def indent(self):
+ self._indent += " "
- def indent(self):
- self._indent += ' '
+ def outdent(self):
+ assert self._indent != self.startIndent
+ self._indent = self._indent[:-2]
- def outdent(self):
- assert self._indent != self.startIndent
- self._indent = self._indent[:-2]
def charVarNumber(charVar):
- """
- Maps binary number (eg [1, 0, 1]) to its decimal value (5).
- """
-
- p = 1
- sum = 0
- downTo = len(charVar) - 1
- while downTo >= 0:
- sum += p * int(charVar[downTo])
- p *= 2
- downTo -= 1
- return sum
-
-def main():
-
- if len(sys.argv) != 4:
- print()
- print('Usage: python -u %s N <True/False> path_to_moman_dir' % sys.argv[0])
- print()
- print('NOTE: the resulting .java file is created in the current working dir!')
- print()
- sys.exit(1)
-
- n = int(sys.argv[1])
-
- transpose = (sys.argv[2] == "True")
-
- sys.path.insert(0, sys.argv[3])
-
- try:
- from possibleStates import genTransitions
- except ImportError:
- from finenight.possibleStates import genTransitions
-
-
- tables = genTransitions(n, transpose)
-
- stateMap = {}
-
- # init null state
- stateMap['[]'] = -1
-
- # init start state
- stateMap['[(0, 0)]'] = 0
-
- w = LineOutput()
-
- w('/*')
- w(' * Licensed to the Apache Software Foundation (ASF) under one or more')
- w(' * contributor license agreements. See the NOTICE file distributed with')
- w(' * this work for additional information regarding copyright ownership.')
- w(' * The ASF licenses this file to You under the Apache License, Version 2.0')
- w(' * (the "License"); you may not use this file except in compliance with')
- w(' * the License. You may obtain a copy of the License at')
- w(' *')
- w(' * http://www.apache.org/licenses/LICENSE-2.0')
- w(' *')
- w(' * Unless required by applicable law or agreed to in writing, software')
- w(' * distributed under the License is distributed on an "AS IS" BASIS,')
- w(' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.')
- w(' * See the License for the specific language governing permissions and')
- w(' * limitations under the License.')
- w(' */')
- w('package org.apache.lucene.util.automaton;')
- w('')
- w('// The following code was generated with the moman/finenight pkg')
- w('// This package is available under the MIT License, see NOTICE.txt')
- w('// for more details.')
- w('// This source file is auto-generated, Please do not modify it directly.')
- w('// You should modify the gradle/generation/moman/createAutomata.py instead.')
- w('')
- w('import org.apache.lucene.util.automaton.LevenshteinAutomata.ParametricDescription;')
- w('')
- if not transpose and n == 1:
- w(HEADER_COMMENT)
- w('')
- if transpose:
- w('/** Parametric description for generating a Levenshtein automaton of degree %s, ' % n)
- w(' with transpositions as primitive edits.')
- className = 'Lev%dTParametricDescription' % n
- else:
- w('/** Parametric description for generating a Levenshtein automaton of degree %s.' % n)
- className = 'Lev%dParametricDescription' % n
- if not transpose and n == 1:
- w('*/')
- else:
- w(' The comment in Lev1ParametricDescription may be helpful for you to understand this class.')
- w(' @see Lev1ParametricDescription')
- w('*/')
-
- w('class %s extends ParametricDescription {' % className)
-
- w('')
- w('@Override')
- w('int transition(int absState, int position, int vector) {')
-
- w(' // null absState should never be passed in')
- w(' assert absState != -1;')
-
- w('')
- w(' // decode absState -> state, offset')
- w(' int state = absState/(w+1);')
- w(' int offset = absState%(w+1);')
- w(' assert offset >= 0;')
- w('')
-
- machines = []
-
- for i, map in enumerate(tables):
- if i == 0:
- w('if (position == w) {')
- elif i == len(tables) - 1:
- w('} else {')
- else:
- w('} else if (position == w-%d) {' % i)
-
- if i != 0 and MODE == 'switch':
- w('switch(vector) {')
-
- l = list(map.items())
- l.sort()
-
- numCasesPerVector = None
- numVectors = len(l)
-
- if MODE == 'array':
- toStateArray = []
- toOffsetIncrArray = []
+ """
+ Maps binary number (eg [1, 0, 1]) to its decimal value (5).
+ """
- for charVar, states in l:
+ p = 1
+ sum = 0
+ downTo = len(charVar) - 1
+ while downTo >= 0:
+ sum += p * int(charVar[downTo])
+ p *= 2
+ downTo -= 1
+ return sum
- # somehow it's a string:
- charVar = eval(charVar)
- if i != 0 and MODE == 'switch':
- w('case %s: // <%s>' % (charVarNumber(charVar), ','.join([str(x) for x in charVar])))
+def main():
+ if len(sys.argv) != 4:
+ print()
+ print("Usage: python -u %s N <True/False> path_to_moman_dir" % sys.argv[0])
+ print()
+ print("NOTE: the resulting .java file is created in the current working dir!")
+ print()
+ sys.exit(1)
+
+ n = int(sys.argv[1])
+
+ transpose = sys.argv[2] == "True"
+
+ sys.path.insert(0, sys.argv[3])
+
+ try:
+ from possibleStates import genTransitions
+ except ImportError:
+ from finenight.possibleStates import genTransitions
+
+ tables = genTransitions(n, transpose)
+
+ stateMap = {}
+
+ # init null state
+ stateMap["[]"] = -1
+
+ # init start state
+ stateMap["[(0, 0)]"] = 0
+
+ w = LineOutput()
+
+ w("/*")
+ w(" * Licensed to the Apache Software Foundation (ASF) under one or more")
+ w(" * contributor license agreements. See the NOTICE file distributed with")
+ w(" * this work for additional information regarding copyright ownership.")
+ w(" * The ASF licenses this file to You under the Apache License, Version 2.0")
+ w(' * (the "License"); you may not use this file except in compliance with')
+ w(" * the License. You may obtain a copy of the License at")
+ w(" *")
+ w(" * http://www.apache.org/licenses/LICENSE-2.0")
+ w(" *")
+ w(" * Unless required by applicable law or agreed to in writing, software")
+ w(' * distributed under the License is distributed on an "AS IS" BASIS,')
+ w(" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.")
+ w(" * See the License for the specific language governing permissions and")
+ w(" * limitations under the License.")
+ w(" */")
+ w("package org.apache.lucene.util.automaton;")
+ w("")
+ w("// The following code was generated with the moman/finenight pkg")
+ w("// This package is available under the MIT License, see NOTICE.txt")
+ w("// for more details.")
+ w("// This source file is auto-generated, Please do not modify it directly.")
+ w("// You should modify the gradle/generation/moman/createAutomata.py instead.")
+ w("")
+ w(
+ "import org.apache.lucene.util.automaton.LevenshteinAutomata.ParametricDescription;"
+ )
+ w("")
+ if not transpose and n == 1:
+ w(HEADER_COMMENT)
+ w("")
+ if transpose:
+ w(
+ "/** Parametric description for generating a Levenshtein automaton of degree %s, "
+ % n
+ )
+ w(" with transpositions as primitive edits.")
+ className = "Lev%dTParametricDescription" % n
+ else:
+ w(
+ "/** Parametric description for generating a Levenshtein automaton of degree %s."
+ % n
+ )
+ className = "Lev%dParametricDescription" % n
+ if not transpose and n == 1:
+ w("*/")
+ else:
+ w(
+ " The comment in Lev1ParametricDescription may be helpful for you to understand this class."
+ )
+ w(" @see Lev1ParametricDescription")
+ w("*/")
+
+ w("class %s extends ParametricDescription {" % className)
+
+ w("")
+ w("@Override")
+ w("int transition(int absState, int position, int vector) {")
+
+ w(" // null absState should never be passed in")
+ w(" assert absState != -1;")
+
+ w("")
+ w(" // decode absState -> state, offset")
+ w(" int state = absState/(w+1);")
+ w(" int offset = absState%(w+1);")
+ w(" assert offset >= 0;")
+ w("")
+
+ machines = []
+
+ for i, map in enumerate(tables):
+ if i == 0:
+ w("if (position == w) {")
+ elif i == len(tables) - 1:
+ w("} else {")
+ else:
+ w("} else if (position == w-%d) {" % i)
+
+ if i != 0 and MODE == "switch":
+ w("switch(vector) {")
+
+ items = list(map.items())
+ items.sort()
+
+ numCasesPerVector = None
+ numVectors = len(items)
+
+ if MODE == "array":
+ toStateArray = []
+ toOffsetIncrArray = []
+
+ for charVar, states in items:
+ # somehow it's a string:
+ charVar = eval(charVar)
+
+ if i != 0 and MODE == "switch":
+ w(
+ "case %s: // <%s>"
+ % (charVarNumber(charVar), ",".join([str(x) for x in charVar]))
+ )
+ w.indent()
+
+ items = list(states.items())
+ items.sort()
+
+ byFromState = {}
+
+ # first pass to assign states
+ byAction = {}
+ for s, (toS, offset) in items:
+ state = str(s)
+
+ toState = str(toS)
+ if state not in stateMap:
+ stateMap[state] = len(stateMap) - 1
+ if toState not in stateMap:
+ stateMap[toState] = len(stateMap) - 1
+
+ byFromState[stateMap[state]] = (1 + stateMap[toState], offset)
+
+ fromStateDesc = s[1 : len(s) - 1]
+ toStateDesc = ", ".join([str(x) for x in toS])
+
+ tup = (stateMap[toState], toStateDesc, offset)
+ if tup not in byAction:
+ byAction[tup] = []
+ byAction[tup].append((fromStateDesc, stateMap[state]))
+
+ if numCasesPerVector is None:
+ numCasesPerVector = len(items)
+ else:
+ # we require this to be uniform... empirically it seems to be!
+ assert numCasesPerVector == len(items)
+
+ if MODE == "array":
+ for s in range(numCasesPerVector):
+ toState, offsetIncr = byFromState[s]
+ toStateArray.append(toState)
+ toOffsetIncrArray.append(offsetIncr)
+
+ else:
+ # render switches
+ w("switch(state) { // %s cases" % len(items))
+
+ for (toState, toStateDesc, offset), lx in byAction.items():
+ for fromStateDesc, fromState in lx:
+ w("case %s: // %s" % (fromState, fromStateDesc))
+ w.indent()
+ w(" state = %s; // %s" % (toState, toStateDesc))
+ if offset > 0:
+ w(" offset += %s;" % offset)
+ w("break;")
+ w.outdent()
+
+ w("}")
+ if i != 0:
+ w("break;")
+ w.outdent()
+
+ if MODE == "array":
+ # strangely state can come in wildly out of bounds....
+ w(" if (state < %d) {" % numCasesPerVector)
+ w(" final int loc = vector * %d + state;" % numCasesPerVector)
+ if PACKED:
+ w(" offset += unpack(offsetIncrs%d, loc, NBITSOFFSET%d);" % (i, i))
+ w(" state = unpack(toStates%d, loc, NBITSSTATES%d)-1;" % (i, i))
+ else:
+ w(" offset += offsetIncrs%d[loc];" % i)
+ w(" state = toStates%d[loc]-1;" % i)
+ w(" }")
+ elif i != 0:
+ w("}")
+
+ machines.append(
+ (toStateArray, toOffsetIncrArray, numCasesPerVector, numVectors)
+ )
+
+ # ends switch statement for machine
+ w("}")
+
+ w("")
+
+ w(" if (state == -1) {")
+ w(" // null state")
+ w(" return -1;")
+ w(" } else {")
+ w(" // translate back to abs")
+ w(" return state*(w+1)+offset;")
+ w(" }")
+
+ # ends transition method
+ w("}")
+
+ subs = []
+ if MODE == "array":
w.indent()
+ for i, (
+ toStateArray,
+ toOffsetIncrsArray,
+ numCasesPerVector,
+ numVectors,
+ ) in enumerate(machines):
+ w("")
+ w.outdent()
+ if transpose or n == 2:
+ w(
+ "// %d vectors; %d states per vector; array length = %d"
+ % (numVectors, numCasesPerVector, numVectors * numCasesPerVector)
+ )
+ else:
+ w(STATE_COMMENT[i])
+ w.indent()
+ if PACKED:
+ # pack in python
+ items, nbits = pack(toStateArray)
+ subs.append(("NBITSSTATES%d" % i, str(nbits)))
+ w(
+ " private final static long[] toStates%d = new long[] /*%d bits per value */ %s;"
+ % (i, nbits, renderList([(hex(int(x)) + "L") for x in items]))
+ )
+
+ items, nbits = pack(toOffsetIncrsArray)
+ subs.append(("NBITSOFFSET%d" % i, str(nbits)))
+ w(
+ " private final static long[] offsetIncrs%d = new long[] /*%d bits per value */ %s;"
+ % (i, nbits, renderList([(hex(int(x)) + "L") for x in items]))
+ )
+ else:
+ w(
+ " private final static int[] toStates%d = new int[] %s;"
+ % (i, renderList([str(x) for x in toStateArray]))
+ )
+ w(
+ " private final static int[] offsetIncrs%d = new int[] %s;"
+ % (i, renderList([str(x) for x in toStateArray]))
+ )
+ w.outdent()
+
+ stateMap2 = dict([[v, k] for k, v in stateMap.items()])
+ w("")
+ w("// state map")
+ sum = 0
+ minErrors = []
+ for i in range(len(stateMap2) - 1):
+ w("// %s -> %s" % (i, stateMap2[i]))
+ # we replace t-notation as it's not relevant here
+ st = stateMap2[i].replace("t", "")
+
+ v = eval(st)
+ minError = min([-i + e for i, e in v])
+ c = len(v)
+ sum += c
+ minErrors.append(minError)
+ w("")
- l = list(states.items())
- l.sort()
-
- byFromState = {}
-
- # first pass to assign states
- byAction = {}
- for s, (toS, offset) in l:
- state = str(s)
-
- toState = str(toS)
- if state not in stateMap:
- stateMap[state] = len(stateMap) - 1
- if toState not in stateMap:
- stateMap[toState] = len(stateMap) - 1
-
- byFromState[stateMap[state]] = (1 + stateMap[toState], offset)
-
- fromStateDesc = s[1:len(s) - 1]
- toStateDesc = ', '.join([str(x) for x in toS])
-
- tup = (stateMap[toState], toStateDesc, offset)
- if tup not in byAction:
- byAction[tup] = []
- byAction[tup].append((fromStateDesc, stateMap[state]))
-
- if numCasesPerVector is None:
- numCasesPerVector = len(l)
- else:
- # we require this to be uniform... empirically it seems to be!
- assert numCasesPerVector == len(l)
-
- if MODE == 'array':
-
- for s in range(numCasesPerVector):
- toState, offsetIncr = byFromState[s]
- toStateArray.append(toState)
- toOffsetIncrArray.append(offsetIncr)
-
- else:
-
- # render switches
- w('switch(state) { // %s cases' % len(l))
-
- for (toState, toStateDesc, offset), lx in byAction.items():
- for fromStateDesc, fromState in lx:
- w('case %s: // %s' % (fromState, fromStateDesc))
- w.indent()
- w(' state = %s; // %s' % (toState, toStateDesc))
- if offset > 0:
- w(' offset += %s;' % offset)
- w('break;')
- w.outdent()
-
- w('}')
- if i != 0:
- w('break;')
- w.outdent()
-
- if MODE == 'array':
- # strangely state can come in wildly out of bounds....
- w(' if (state < %d) {' % numCasesPerVector)
- w(' final int loc = vector * %d + state;' % numCasesPerVector)
- if PACKED:
- w(' offset += unpack(offsetIncrs%d, loc, NBITSOFFSET%d);' % (i, i))
- w(' state = unpack(toStates%d, loc, NBITSSTATES%d)-1;' % (i, i))
- else:
- w(' offset += offsetIncrs%d[loc];' % i)
- w(' state = toStates%d[loc]-1;' % i)
- w(' }')
- elif i != 0:
- w('}')
-
- machines.append((toStateArray, toOffsetIncrArray, numCasesPerVector, numVectors))
-
- # ends switch statement for machine
- w('}')
-
- w('')
-
- w(' if (state == -1) {')
- w(' // null state')
- w(' return -1;')
- w(' } else {')
- w(' // translate back to abs')
- w(' return state*(w+1)+offset;')
- w(' }')
-
- # ends transition method
- w('}')
-
- subs = []
- if MODE == 'array':
w.indent()
- for i, (toStateArray, toOffsetIncrsArray, numCasesPerVector, numVectors) in enumerate(machines):
- w('')
- w.outdent()
- if transpose or n == 2:
- w('// %d vectors; %d states per vector; array length = %d' % \
- (numVectors, numCasesPerVector, numVectors * numCasesPerVector))
- else:
- w(STATE_COMMENT[i])
- w.indent()
- if PACKED:
- # pack in python
- l, nbits = pack(toStateArray)
- subs.append(('NBITSSTATES%d' % i, str(nbits)))
- w(' private final static long[] toStates%d = new long[] /*%d bits per value */ %s;' % \
- (i, nbits, renderList([(hex(int(x)) + "L") for x in l])))
-
- l, nbits = pack(toOffsetIncrsArray)
- subs.append(('NBITSOFFSET%d' % i, str(nbits)))
- w(' private final static long[] offsetIncrs%d = new long[] /*%d bits per value */ %s;' % \
- (i, nbits, renderList([(hex(int(x)) + "L") for x in l])))
- else:
- w(' private final static int[] toStates%d = new int[] %s;' % \
- (i, renderList([str(x) for x in toStateArray])))
- w(' private final static int[] offsetIncrs%d = new int[] %s;' % \
- (i, renderList([str(x) for x in toStateArray])))
+ # w('private final static int[] minErrors = new int[] {%s};' % ','.join([str(x) for x in minErrors]))
+
w.outdent()
- stateMap2 = dict([[v, k] for k, v in stateMap.items()])
- w('')
- w('// state map')
- sum = 0
- minErrors = []
- for i in range(len(stateMap2) - 1):
- w('// %s -> %s' % (i, stateMap2[i]))
- # we replace t-notation as it's not relevant here
- st = stateMap2[i].replace('t', '')
-
- v = eval(st)
- minError = min([-i + e for i, e in v])
- c = len(v)
- sum += c
- minErrors.append(minError)
- w('')
-
- w.indent()
- # w('private final static int[] minErrors = new int[] {%s};' % ','.join([str(x) for x in minErrors]))
-
- w.outdent()
-
- w('')
- w(' public %s(int w) {' % className)
- w(' super(w, %d, new int[] {%s});' % (n, ','.join([str(x) for x in minErrors])), indent=1)
- w(' }')
-
- if 0:
- w('')
- w('@Override')
- w('public int size() { // this can now move up?')
- w(' return %d*(w+1);' % (len(stateMap2) - 1))
- w('}')
-
- w('')
- w('@Override')
- w('public int getPosition(int absState) { // this can now move up?')
- w(' return absState % (w+1);')
- w('}')
-
- w('')
- w('@Override')
- w('public boolean isAccept(int absState) { // this can now move up?')
- w(' // decode absState -> state, offset')
- w(' int state = absState/(w+1);')
- w(' if (true || state < minErrors.length) {')
- w(' int offset = absState%(w+1);')
- w(' assert offset >= 0;')
- w(' return w - offset + minErrors[state] <= %d;' % n)
- w(' } else {')
- w(' return false;')
- w(' }')
- w('}')
-
- if MODE == 'array' and PACKED:
-
- # we moved into super class
- if False:
- w('')
-
- v = 2
- l = []
- for i in range(63):
- l.append(hex(v - 1))
- v *= 2
-
- w('private final static long[] MASKS = new long[] {%s};' % ','.join(l), indent=1)
- w('')
-
- # unpack in java
- w('private int unpack(long[] data, int index, int bitsPerValue) {')
- w(' final long bitLoc = bitsPerValue * index;')
- w(' final int dataLoc = (int) (bitLoc >> %d);' % LOG2_WORD)
- w(' final int bitStart = (int) (bitLoc & %d);' % (WORD - 1))
- w(' //System.out.println("index=" + index + " dataLoc=" + dataLoc + " bitStart=" + bitStart + " bitsPerV=" + bitsPerValue);')
- w(' if (bitStart + bitsPerValue <= %d) {' % WORD)
- w(' // not split')
- w(' return (int) ((data[dataLoc] >> bitStart) & MASKS[bitsPerValue-1]);')
- w(' } else {')
- w(' // split')
- w(' final int part = %d-bitStart;' % WORD)
- w(' return (int) (((data[dataLoc] >> bitStart) & MASKS[part-1]) +')
- w(' ((data[1+dataLoc] & MASKS[bitsPerValue-part-1]) << part));', indent=1)
- w(' }')
- w('}')
-
- # class
- w('}')
- w('')
-
- fileOut = '%s.java' % className
-
- s = str(w)
- for sub, repl in subs:
- s = s.replace(sub, repl)
-
- open(fileOut, 'w', encoding='utf-8').write(s)
-
- print('Wrote %s [%d lines; %.1f KB]' % \
- (fileOut, len(w.l), os.path.getsize(fileOut) / 1024.))
-
-def renderList(l):
- lx = [' ']
- for i in range(len(l)):
- if i > 0:
- lx.append(',')
- if i % 4 == 0:
- lx.append('\n ')
- lx.append(l[i])
- return '{\n%s\n }' % ''.join(lx)
+ w("")
+ w(" public %s(int w) {" % className)
+ w(
+ " super(w, %d, new int[] {%s});"
+ % (n, ",".join([str(x) for x in minErrors])),
+ indent=1,
+ )
+ w(" }")
+
+ if 0:
+ w("")
+ w("@Override")
+ w("public int size() { // this can now move up?")
+ w(" return %d*(w+1);" % (len(stateMap2) - 1))
+ w("}")
+
+ w("")
+ w("@Override")
+ w("public int getPosition(int absState) { // this can now move up?")
+ w(" return absState % (w+1);")
+ w("}")
+
+ w("")
+ w("@Override")
+ w("public boolean isAccept(int absState) { // this can now move up?")
+ w(" // decode absState -> state, offset")
+ w(" int state = absState/(w+1);")
+ w(" if (true || state < minErrors.length) {")
+ w(" int offset = absState%(w+1);")
+ w(" assert offset >= 0;")
+ w(" return w - offset + minErrors[state] <= %d;" % n)
+ w(" } else {")
+ w(" return false;")
+ w(" }")
+ w("}")
+
+ if MODE == "array" and PACKED:
+ # we moved into super class
+ if False:
+ w("")
+
+ v = 2
+ items = []
+ for i in range(63):
+ items.append(hex(v - 1))
+ v *= 2
+
+ w(
+ "private final static long[] MASKS = new long[] {%s};"
+ % ",".join(items),
+ indent=1,
+ )
+ w("")
+
+ # unpack in java
+ w("private int unpack(long[] data, int index, int bitsPerValue) {")
+ w(" final long bitLoc = bitsPerValue * index;")
+ w(" final int dataLoc = (int) (bitLoc >> %d);" % LOG2_WORD)
+ w(" final int bitStart = (int) (bitLoc & %d);" % (WORD - 1))
+ w(
+ ' //System.out.println("index=" + index + " dataLoc=" + dataLoc + " bitStart=" + bitStart + " bitsPerV=" + bitsPerValue);'
+ )
+ w(" if (bitStart + bitsPerValue <= %d) {" % WORD)
+ w(" // not split")
+ w(" return (int) ((data[dataLoc] >> bitStart) & MASKS[bitsPerValue-1]);")
+ w(" } else {")
+ w(" // split")
+ w(" final int part = %d-bitStart;" % WORD)
+ w(" return (int) (((data[dataLoc] >> bitStart) & MASKS[part-1]) +")
+ w(
+ " ((data[1+dataLoc] & MASKS[bitsPerValue-part-1]) << part));",
+ indent=1,
+ )
+ w(" }")
+ w("}")
+
+ # class
+ w("}")
+ w("")
+
+ fileOut = "%s.java" % className
+
+ s = str(w)
+ for sub, repl in subs:
+ s = s.replace(sub, repl)
+
+ open(fileOut, "w", encoding="utf-8").write(s)
+
+ print(
+ "Wrote %s [%d lines; %.1f KB]"
+ % (fileOut, len(w.l), os.path.getsize(fileOut) / 1024.0)
+ )
+
+
+def renderList(items):
+ lx = [" "]
+ for i in range(len(items)):
+ if i > 0:
+ lx.append(",")
+ if i % 4 == 0:
+ lx.append("\n ")
+ lx.append(items[i])
+ return "{\n%s\n }" % "".join(lx)
+
MASKS = []
v = 2
for i in range(63):
- MASKS.append(v - 1)
- v *= 2
+ MASKS.append(v - 1)
+ v *= 2
+
# packs into longs; returns long[], numBits
-def pack(l):
- maxV = max(l)
- bitsPerValue = max(1, int(math.ceil(math.log(maxV + 1) / math.log(2.0))))
-
- bitsLeft = WORD
- pendingValue = 0
-
- packed = []
- for i in range(len(l)):
- v = l[i]
- if pendingValue > 0:
- bitsUsed = math.ceil(math.log(pendingValue) / math.log(2.0))
- assert bitsUsed <= (WORD - bitsLeft), 'bitsLeft=%s (%s-%s=%s) bitsUsed=%s' % (bitsLeft, WORD, bitsLeft, WORD - bitsLeft, bitsUsed)
-
- if bitsLeft >= bitsPerValue:
- pendingValue += v << (WORD - bitsLeft)
- bitsLeft -= bitsPerValue
- if bitsLeft == 0:
+def pack(items):
+ maxV = max(items)
+ bitsPerValue = max(1, int(math.ceil(math.log(maxV + 1) / math.log(2.0))))
+
+ bitsLeft = WORD
+ pendingValue = 0
+
+ packed = []
+ for i in range(len(items)):
+ v = items[i]
+ if pendingValue > 0:
+ bitsUsed = math.ceil(math.log(pendingValue) / math.log(2.0))
+ assert bitsUsed <= (WORD - bitsLeft), (
+ "bitsLeft=%s (%s-%s=%s) bitsUsed=%s"
+ % (bitsLeft, WORD, bitsLeft, WORD - bitsLeft, bitsUsed)
+ )
+
+ if bitsLeft >= bitsPerValue:
+ pendingValue += v << (WORD - bitsLeft)
+ bitsLeft -= bitsPerValue
+ if bitsLeft == 0:
+ packed.append(pendingValue)
+ bitsLeft = WORD
+ pendingValue = 0
+ else:
+ # split
+
+ # bottom bitsLeft go in current word:
+ pendingValue += (v & MASKS[bitsLeft - 1]) << (WORD - bitsLeft)
+ packed.append(pendingValue)
+
+ pendingValue = v >> bitsLeft
+ bitsLeft = WORD - (bitsPerValue - bitsLeft)
+
+ if bitsLeft < WORD:
packed.append(pendingValue)
- bitsLeft = WORD
- pendingValue = 0
- else:
- # split
-
- # bottom bitsLeft go in current word:
- pendingValue += (v & MASKS[bitsLeft - 1]) << (WORD - bitsLeft)
- packed.append(pendingValue)
-
- pendingValue = v >> bitsLeft
- bitsLeft = WORD - (bitsPerValue - bitsLeft)
- if bitsLeft < WORD:
- packed.append(pendingValue)
+ # verify(l, packed, bitsPerValue)
- # verify(l, packed, bitsPerValue)
+ return packed, bitsPerValue
- return packed, bitsPerValue
def verify(data, packedData, bitsPerValue):
- for i in range(len(data)):
- assert data[i] == unpack(packedData, i, bitsPerValue)
+ for i in range(len(data)):
+ assert data[i] == unpack(packedData, i, bitsPerValue)
+
def unpack(data, index, bitsPerValue):
- bitLoc = bitsPerValue * index
- dataLoc = int(bitLoc >> LOG2_WORD)
- bitStart = int(bitLoc & (WORD - 1))
- if bitStart + bitsPerValue <= WORD:
- # not split
- return int(((data[dataLoc] >> bitStart) & MASKS[bitsPerValue - 1]))
- else:
- # split
- part = WORD - bitStart;
- return int((((data[dataLoc] >> bitStart) & MASKS[part - 1]) +
- ((data[1 + dataLoc] & MASKS[bitsPerValue - part - 1]) << part)))
-
-if __name__ == '__main__':
- if not __debug__:
- print()
- print('ERROR: please run without -O')
- print()
- sys.exit(1)
- main()
+ bitLoc = bitsPerValue * index
+ dataLoc = int(bitLoc >> LOG2_WORD)
+ bitStart = int(bitLoc & (WORD - 1))
+ if bitStart + bitsPerValue <= WORD:
+ # not split
+ return int(((data[dataLoc] >> bitStart) & MASKS[bitsPerValue - 1]))
+ else:
+ # split
+ part = WORD - bitStart
+ return int(
+ (
+ ((data[dataLoc] >> bitStart) & MASKS[part - 1])
+ + ((data[1 + dataLoc] & MASKS[bitsPerValue - part - 1]) << part)
+ )
+ )
+
+
+if __name__ == "__main__":
+ if not __debug__:
+ print()
+ print("ERROR: please run without -O")
+ print()
+ sys.exit(1)
+ main()
diff --git a/gradle/regenerate/packed/gen_BulkOperation.py b/gradle/regenerate/packed/gen_BulkOperation.py
index b909a382499..c3dbbca3bfb 100644
--- a/gradle/regenerate/packed/gen_BulkOperation.py
+++ b/gradle/regenerate/packed/gen_BulkOperation.py
@@ -15,16 +15,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-try:
- # python 3.9+
- from math import gcd
-except ImportError:
- # old python
- from fractions import gcd
-
"""Code generation for bulk operations"""
-MAX_SPECIALIZED_BITS_PER_VALUE = 24;
+MAX_SPECIALIZED_BITS_PER_VALUE = 24
PACKED_64_SINGLE_BLOCK_BPV = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 21, 32]
OUTPUT_FILE = "BulkOperation.java"
HEADER = """// This file has been automatically generated, DO NOT EDIT
@@ -92,60 +85,69 @@ FOOTER = """
}
"""
+
def is_power_of_two(n):
- return n & (n - 1) == 0
+ return n & (n - 1) == 0
+
def casts(typ):
- cast_start = "(%s) (" % typ
- cast_end = ")"
- if typ == "long":
- cast_start = ""
- cast_end = ""
- return cast_start, cast_end
+ cast_start = "(%s) (" % typ
+ cast_end = ")"
+ if typ == "long":
+ cast_start = ""
+ cast_end = ""
+ return cast_start, cast_end
+
def hexNoLSuffix(n):
- # On 32 bit Python values > (1 << 31)-1 will have L appended by hex function:
- s = hex(n)
- if s.endswith('L'):
- s = s[:-1]
- return s
+ # On 32 bit Python values > (1 << 31)-1 will have L appended by hex function:
+ s = hex(n)
+ if s.endswith("L"):
+ s = s[:-1]
+ return s
+
def masks(bits):
- if bits == 64:
- return "", ""
- return "(", " & %sL)" % (hexNoLSuffix((1 << bits) - 1))
+ if bits == 64:
+ return "", ""
+ return "(", " & %sL)" % (hexNoLSuffix((1 << bits) - 1))
+
def get_type(bits):
- if bits == 8:
- return "byte"
- elif bits == 16:
- return "short"
- elif bits == 32:
- return "int"
- elif bits == 64:
- return "long"
- else:
- assert False
+ if bits == 8:
+ return "byte"
+ elif bits == 16:
+ return "short"
+ elif bits == 32:
+ return "int"
+ elif bits == 64:
+ return "long"
+ else:
+ assert False
+
def block_value_count(bpv, bits=64):
- blocks = bpv
- values = blocks * bits // bpv
- while blocks % 2 == 0 and values % 2 == 0:
- blocks //= 2
- values //= 2
- assert values * bpv == bits * blocks, "%d values, %d blocks, %d bits per value" % (values, blocks, bpv)
- return (blocks, values)
+ blocks = bpv
+ values = blocks * bits // bpv
+ while blocks % 2 == 0 and values % 2 == 0:
+ blocks //= 2
+ values //= 2
+ assert values * bpv == bits * blocks, "%d values, %d blocks, %d bits per value" % (
+ values,
+ blocks,
+ bpv,
+ )
+ return (blocks, values)
-def packed64(bpv, f):
- mask = (1 << bpv) - 1
- f.write("\n")
- f.write(" public BulkOperationPacked%d() {\n" % bpv)
- f.write(" super(%d);\n" % bpv)
- f.write(" }\n\n")
+def packed64(bpv, f):
+ f.write("\n")
+ f.write(" public BulkOperationPacked%d() {\n" % bpv)
+ f.write(" super(%d);\n" % bpv)
+ f.write(" }\n\n")
- if bpv == 64:
- f.write(""" @Override
+ if bpv == 64:
+ f.write(""" @Override
public void decode(long[] blocks, int blocksOffset, long[] values, int valuesOffset, int iterations) {
System.arraycopy(blocks, blocksOffset, values, valuesOffset, valueCount() * iterations);
}
@@ -165,175 +167,259 @@ def packed64(bpv, f):
LongBuffer.wrap(values, valuesOffset, iterations * valueCount()).put(ByteBuffer.wrap(blocks, blocksOffset, 8 * iterations * blockCount()).asLongBuffer());
}
""")
- else:
- p64_decode(bpv, f, 32)
- p64_decode(bpv, f, 64)
+ else:
+ p64_decode(bpv, f, 32)
+ p64_decode(bpv, f, 64)
+
def p64_decode(bpv, f, bits):
- blocks, values = block_value_count(bpv)
- typ = get_type(bits)
- cast_start, cast_end = casts(typ)
-
- f.write(" @Override\n")
- f.write(" public void decode(long[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n" % typ)
- if bits < bpv:
- f.write(" throw new UnsupportedOperationException();\n")
- else:
- f.write(" for (int i = 0; i < iterations; ++i) {\n")
- mask = (1 << bpv) - 1
-
- if is_power_of_two(bpv):
- f.write(" final long block = blocks[blocksOffset++];\n")
- f.write(" for (int shift = %d; shift >= 0; shift -= %d) {\n" % (64 - bpv, bpv))
- f.write(" values[valuesOffset++] = %s(block >>> shift) & %d%s;\n" % (cast_start, mask, cast_end))
- f.write(" }\n")
+ _blocks, values = block_value_count(bpv)
+ typ = get_type(bits)
+ cast_start, cast_end = casts(typ)
+
+ f.write(" @Override\n")
+ f.write(
+ " public void decode(long[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n"
+ % typ
+ )
+ if bits < bpv:
+ f.write(" throw new UnsupportedOperationException();\n")
else:
- for i in range(0, values):
- block_offset = i * bpv // 64
- bit_offset = (i * bpv) % 64
- if bit_offset == 0:
- # start of block
- f.write(" final long block%d = blocks[blocksOffset++];\n" % block_offset);
- f.write(" values[valuesOffset++] = %sblock%d >>> %d%s;\n" % (cast_start, block_offset, 64 - bpv, cast_end))
- elif bit_offset + bpv == 64:
- # end of block
- f.write(" values[valuesOffset++] = %sblock%d & %dL%s;\n" % (cast_start, block_offset, mask, cast_end))
- elif bit_offset + bpv < 64:
- # middle of block
- f.write(" values[valuesOffset++] = %s(block%d >>> %d) & %dL%s;\n" % (cast_start, block_offset, 64 - bit_offset - bpv, mask, cast_end))
+ f.write(" for (int i = 0; i < iterations; ++i) {\n")
+ mask = (1 << bpv) - 1
+
+ if is_power_of_two(bpv):
+ f.write(" final long block = blocks[blocksOffset++];\n")
+ f.write(
+ " for (int shift = %d; shift >= 0; shift -= %d) {\n"
+ % (64 - bpv, bpv)
+ )
+ f.write(
+ " values[valuesOffset++] = %s(block >>> shift) & %d%s;\n"
+ % (cast_start, mask, cast_end)
+ )
+ f.write(" }\n")
else:
- # value spans across 2 blocks
- mask1 = (1 << (64 - bit_offset)) - 1
- shift1 = bit_offset + bpv - 64
- shift2 = 64 - shift1
- f.write(" final long block%d = blocks[blocksOffset++];\n" % (block_offset + 1));
- f.write(" values[valuesOffset++] = %s((block%d & %dL) << %d) | (block%d >>> %d)%s;\n" % (cast_start, block_offset, mask1, shift1, block_offset + 1, shift2, cast_end))
- f.write(" }\n")
- f.write(" }\n\n")
-
- byte_blocks, byte_values = block_value_count(bpv, 8)
-
- f.write(" @Override\n")
- f.write(" public void decode(byte[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n" % typ)
- if bits < bpv:
- f.write(" throw new UnsupportedOperationException();\n")
- else:
- if is_power_of_two(bpv) and bpv < 8:
- f.write(" for (int j = 0; j < iterations; ++j) {\n")
- f.write(" final byte block = blocks[blocksOffset++];\n")
- for shift in range(8 - bpv, 0, -bpv):
- f.write(" values[valuesOffset++] = (block >>> %d) & %d;\n" % (shift, mask))
- f.write(" values[valuesOffset++] = block & %d;\n" % mask)
- f.write(" }\n")
- elif bpv == 8:
- f.write(" for (int j = 0; j < iterations; ++j) {\n")
- f.write(" values[valuesOffset++] = blocks[blocksOffset++] & 0xFF;\n")
- f.write(" }\n")
- elif is_power_of_two(bpv) and bpv > 8:
- f.write(" for (int j = 0; j < iterations; ++j) {\n")
- m = bits <= 32 and "0xFF" or "0xFFL"
- f.write(" values[valuesOffset++] =")
- for i in range(bpv // 8 - 1):
- f.write(" ((blocks[blocksOffset++] & %s) << %d) |" % (m, bpv - 8))
- f.write(" (blocks[blocksOffset++] & %s);\n" % m)
- f.write(" }\n")
+ for i in range(0, values):
+ block_offset = i * bpv // 64
+ bit_offset = (i * bpv) % 64
+ if bit_offset == 0:
+ # start of block
+ f.write(
+ " final long block%d = blocks[blocksOffset++];\n"
+ % block_offset
+ )
+ f.write(
+ " values[valuesOffset++] = %sblock%d >>> %d%s;\n"
+ % (cast_start, block_offset, 64 - bpv, cast_end)
+ )
+ elif bit_offset + bpv == 64:
+ # end of block
+ f.write(
+ " values[valuesOffset++] = %sblock%d & %dL%s;\n"
+ % (cast_start, block_offset, mask, cast_end)
+ )
+ elif bit_offset + bpv < 64:
+ # middle of block
+ f.write(
+ " values[valuesOffset++] = %s(block%d >>> %d) & %dL%s;\n"
+ % (
+ cast_start,
+ block_offset,
+ 64 - bit_offset - bpv,
+ mask,
+ cast_end,
+ )
+ )
+ else:
+ # value spans across 2 blocks
+ mask1 = (1 << (64 - bit_offset)) - 1
+ shift1 = bit_offset + bpv - 64
+ shift2 = 64 - shift1
+ f.write(
+ " final long block%d = blocks[blocksOffset++];\n"
+ % (block_offset + 1)
+ )
+ f.write(
+ " values[valuesOffset++] = %s((block%d & %dL) << %d) | (block%d >>> %d)%s;\n"
+ % (
+ cast_start,
+ block_offset,
+ mask1,
+ shift1,
+ block_offset + 1,
+ shift2,
+ cast_end,
+ )
+ )
+ f.write(" }\n")
+ f.write(" }\n\n")
+
+ byte_blocks, byte_values = block_value_count(bpv, 8)
+
+ f.write(" @Override\n")
+ f.write(
+ " public void decode(byte[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n"
+ % typ
+ )
+ if bits < bpv:
+ f.write(" throw new UnsupportedOperationException();\n")
else:
- f.write(" for (int i = 0; i < iterations; ++i) {\n")
- for i in range(0, byte_values):
- byte_start = i * bpv // 8
- bit_start = (i * bpv) % 8
- byte_end = ((i + 1) * bpv - 1) // 8
- bit_end = ((i + 1) * bpv - 1) % 8
- shift = lambda b: 8 * (byte_end - b - 1) + 1 + bit_end
- if bit_start == 0:
- f.write(" final %s byte%d = blocks[blocksOffset++] & 0xFF;\n" % (typ, byte_start))
- for b in range(byte_start + 1, byte_end + 1):
- f.write(" final %s byte%d = blocks[blocksOffset++] & 0xFF;\n" % (typ, b))
- f.write(" values[valuesOffset++] =")
- if byte_start == byte_end:
- if bit_start == 0:
- if bit_end == 7:
- f.write(" byte%d" % byte_start)
- else:
- f.write(" byte%d >>> %d" % (byte_start, 7 - bit_end))
- else:
- if bit_end == 7:
- f.write(" byte%d & %d" % (byte_start, 2 ** (8 - bit_start) - 1))
- else:
- f.write(" (byte%d >>> %d) & %d" % (byte_start, 7 - bit_end, 2 ** (bit_end - bit_start + 1) - 1))
+ if is_power_of_two(bpv) and bpv < 8:
+ f.write(" for (int j = 0; j < iterations; ++j) {\n")
+ f.write(" final byte block = blocks[blocksOffset++];\n")
+ for shift in range(8 - bpv, 0, -bpv):
+ f.write(
+ " values[valuesOffset++] = (block >>> %d) & %d;\n"
+ % (shift, mask)
+ )
+ f.write(" values[valuesOffset++] = block & %d;\n" % mask)
+ f.write(" }\n")
+ elif bpv == 8:
+ f.write(" for (int j = 0; j < iterations; ++j) {\n")
+ f.write(" values[valuesOffset++] = blocks[blocksOffset++] & 0xFF;\n")
+ f.write(" }\n")
+ elif is_power_of_two(bpv) and bpv > 8:
+ f.write(" for (int j = 0; j < iterations; ++j) {\n")
+ m = bits <= 32 and "0xFF" or "0xFFL"
+ f.write(" values[valuesOffset++] =")
+ for i in range(bpv // 8 - 1):
+ f.write(" ((blocks[blocksOffset++] & %s) << %d) |" % (m, bpv - 8))
+ f.write(" (blocks[blocksOffset++] & %s);\n" % m)
+ f.write(" }\n")
else:
- if bit_start == 0:
- f.write(" (byte%d << %d)" % (byte_start, shift(byte_start)))
- else:
- f.write(" ((byte%d & %d) << %d)" % (byte_start, 2 ** (8 - bit_start) - 1, shift(byte_start)))
- for b in range(byte_start + 1, byte_end):
- f.write(" | (byte%d << %d)" % (b, shift(b)))
- if bit_end == 7:
- f.write(" | byte%d" % byte_end)
- else:
- f.write(" | (byte%d >>> %d)" % (byte_end, 7 - bit_end))
- f.write(";\n")
- f.write(" }\n")
- f.write(" }\n\n")
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- f.write('\n')
- f.write('''/**
+ f.write(" for (int i = 0; i < iterations; ++i) {\n")
+ for i in range(0, byte_values):
+ byte_start = i * bpv // 8
+ bit_start = (i * bpv) % 8
+ byte_end = ((i + 1) * bpv - 1) // 8
+ bit_end = ((i + 1) * bpv - 1) % 8
+
+ def shift(b):
+ return 8 * (byte_end - b - 1) + 1 + bit_end
+
+ if bit_start == 0:
+ f.write(
+ " final %s byte%d = blocks[blocksOffset++] & 0xFF;\n"
+ % (typ, byte_start)
+ )
+ for b in range(byte_start + 1, byte_end + 1):
+ f.write(
+ " final %s byte%d = blocks[blocksOffset++] & 0xFF;\n"
+ % (typ, b)
+ )
+ f.write(" values[valuesOffset++] =")
+ if byte_start == byte_end:
+ if bit_start == 0:
+ if bit_end == 7:
+ f.write(" byte%d" % byte_start)
+ else:
+ f.write(" byte%d >>> %d" % (byte_start, 7 - bit_end))
+ else:
+ if bit_end == 7:
+ f.write(
+ " byte%d & %d" % (byte_start, 2 ** (8 - bit_start) - 1)
+ )
+ else:
+ f.write(
+ " (byte%d >>> %d) & %d"
+ % (
+ byte_start,
+ 7 - bit_end,
+ 2 ** (bit_end - bit_start + 1) - 1,
+ )
+ )
+ else:
+ if bit_start == 0:
+ f.write(" (byte%d << %d)" % (byte_start, shift(byte_start)))
+ else:
+ f.write(
+ " ((byte%d & %d) << %d)"
+ % (byte_start, 2 ** (8 - bit_start) - 1, shift(byte_start))
+ )
+ for b in range(byte_start + 1, byte_end):
+ f.write(" | (byte%d << %d)" % (b, shift(b)))
+ if bit_end == 7:
+ f.write(" | byte%d" % byte_end)
+ else:
+ f.write(" | (byte%d >>> %d)" % (byte_end, 7 - bit_end))
+ f.write(";\n")
+ f.write(" }\n")
+ f.write(" }\n\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ f.write("\n")
+ f.write("""/**
* Efficient sequential read/write of packed integers.
- */\n''')
-
- f.write('abstract class BulkOperation implements PackedInts.Decoder, PackedInts.Encoder {\n')
- f.write(' @SuppressWarnings("ClassInitializationDeadlock") // FIXME: may cause hangs!\n')
- f.write(' private static final BulkOperation[] packedBulkOps = new BulkOperation[] {\n')
-
- for bpv in range(1, 65):
- if bpv > MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write(' new BulkOperationPacked(%d),\n' % bpv)
- continue
- f2 = open('BulkOperationPacked%d.java' % bpv, 'w')
- f2.write(HEADER)
- if bpv == 64:
- f2.write('import java.nio.LongBuffer;\n')
- f2.write('import java.nio.ByteBuffer;\n')
- f2.write('\n')
- f2.write('''/**
+ */\n""")
+
+ f.write(
+ "abstract class BulkOperation implements PackedInts.Decoder, PackedInts.Encoder {\n"
+ )
+ f.write(
+ ' @SuppressWarnings("ClassInitializationDeadlock") // FIXME: may cause hangs!\n'
+ )
+ f.write(
+ " private static final BulkOperation[] packedBulkOps = new BulkOperation[] {\n"
+ )
+
+ for bpv in range(1, 65):
+ if bpv > MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write(" new BulkOperationPacked(%d),\n" % bpv)
+ continue
+ f2 = open("BulkOperationPacked%d.java" % bpv, "w")
+ f2.write(HEADER)
+ if bpv == 64:
+ f2.write("import java.nio.LongBuffer;\n")
+ f2.write("import java.nio.ByteBuffer;\n")
+ f2.write("\n")
+ f2.write("""/**
* Efficient sequential read/write of packed integers.
- */\n''')
- f2.write('final class BulkOperationPacked%d extends BulkOperationPacked {\n' % bpv)
- packed64(bpv, f2)
- f2.write('}\n')
- f2.close()
- f.write(' new BulkOperationPacked%d(),\n' % bpv)
-
- f.write(' };\n')
- f.write('\n')
-
- f.write(' // NOTE: this is sparse (some entries are null):\n')
- f.write(' @SuppressWarnings("ClassInitializationDeadlock") // FIXME: may cause hangs!\n')
- f.write(' private static final BulkOperation[] packedSingleBlockBulkOps = new BulkOperation[] {\n')
- for bpv in range(1, max(PACKED_64_SINGLE_BLOCK_BPV) + 1):
- if bpv in PACKED_64_SINGLE_BLOCK_BPV:
- f.write(' new BulkOperationPackedSingleBlock(%d),\n' % bpv)
- else:
- f.write(' null,\n')
- f.write(' };\n')
- f.write('\n')
-
- f.write("\n")
- f.write(" public static BulkOperation of(PackedInts.Format format, int bitsPerValue) {\n")
- f.write(" switch (format) {\n")
-
- f.write(" case PACKED:\n")
- f.write(" assert packedBulkOps[bitsPerValue - 1] != null;\n")
- f.write(" return packedBulkOps[bitsPerValue - 1];\n")
- f.write(" case PACKED_SINGLE_BLOCK:\n")
- f.write(" assert packedSingleBlockBulkOps[bitsPerValue - 1] != null;\n")
- f.write(" return packedSingleBlockBulkOps[bitsPerValue - 1];\n")
- f.write(" default:\n")
- f.write(" throw new AssertionError();\n")
- f.write(" }\n")
- f.write(" }\n")
- f.write(FOOTER)
- f.close()
+ */\n""")
+ f2.write(
+ "final class BulkOperationPacked%d extends BulkOperationPacked {\n" % bpv
+ )
+ packed64(bpv, f2)
+ f2.write("}\n")
+ f2.close()
+ f.write(" new BulkOperationPacked%d(),\n" % bpv)
+
+ f.write(" };\n")
+ f.write("\n")
+
+ f.write(" // NOTE: this is sparse (some entries are null):\n")
+ f.write(
+ ' @SuppressWarnings("ClassInitializationDeadlock") // FIXME: may cause hangs!\n'
+ )
+ f.write(
+ " private static final BulkOperation[] packedSingleBlockBulkOps = new BulkOperation[] {\n"
+ )
+ for bpv in range(1, max(PACKED_64_SINGLE_BLOCK_BPV) + 1):
+ if bpv in PACKED_64_SINGLE_BLOCK_BPV:
+ f.write(" new BulkOperationPackedSingleBlock(%d),\n" % bpv)
+ else:
+ f.write(" null,\n")
+ f.write(" };\n")
+ f.write("\n")
+
+ f.write("\n")
+ f.write(
+ " public static BulkOperation of(PackedInts.Format format, int bitsPerValue) {\n"
+ )
+ f.write(" switch (format) {\n")
+
+ f.write(" case PACKED:\n")
+ f.write(" assert packedBulkOps[bitsPerValue - 1] != null;\n")
+ f.write(" return packedBulkOps[bitsPerValue - 1];\n")
+ f.write(" case PACKED_SINGLE_BLOCK:\n")
+ f.write(" assert packedSingleBlockBulkOps[bitsPerValue - 1] != null;\n")
+ f.write(" return packedSingleBlockBulkOps[bitsPerValue - 1];\n")
+ f.write(" default:\n")
+ f.write(" throw new AssertionError();\n")
+ f.write(" }\n")
+ f.write(" }\n")
+ f.write(FOOTER)
+ f.close()
diff --git a/gradle/regenerate/packed/gen_Packed64SingleBlock.py b/gradle/regenerate/packed/gen_Packed64SingleBlock.py
index 808935cb952..bb19a940b0b 100644
--- a/gradle/regenerate/packed/gen_Packed64SingleBlock.py
+++ b/gradle/regenerate/packed/gen_Packed64SingleBlock.py
@@ -222,59 +222,69 @@ abstract class Packed64SingleBlock extends PackedInts.MutableImpl {
FOOTER = "}"
-if __name__ == '__main__':
-
- f = open("Packed64SingleBlock.java", 'w')
- f.write(HEADER)
- f.write(" public static Packed64SingleBlock create(int valueCount, int bitsPerValue) {\n")
- f.write(" switch (bitsPerValue) {\n")
- for bpv in SUPPORTED_BITS_PER_VALUE:
- f.write(" case %d:\n" % bpv)
- f.write(" return new Packed64SingleBlock%d(valueCount);\n" % bpv)
- f.write(" default:\n")
- f.write(" throw new IllegalArgumentException(\"Unsupported number of bits per value: \" + %d);\n" % bpv)
- f.write(" }\n")
- f.write(" }\n\n")
-
- for bpv in SUPPORTED_BITS_PER_VALUE:
- log_2 = 0
- while (1 << log_2) < bpv:
- log_2 = log_2 + 1
- if (1 << log_2) != bpv:
- log_2 = None
-
- f.write(" static class Packed64SingleBlock%d extends Packed64SingleBlock {\n\n" % bpv)
-
- f.write(" Packed64SingleBlock%d(int valueCount) {\n" % bpv)
- f.write(" super(valueCount, %d);\n" % bpv)
- f.write(" }\n\n")
-
- f.write(" @Override\n")
- f.write(" public long get(int index) {\n")
- if log_2 is not None:
- f.write(" final int o = index >>> %d;\n" % (6 - log_2))
- f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
- f.write(" final int shift = b << %d;\n" % log_2)
- else:
- f.write(" final int o = index / %d;\n" % (64 / bpv))
- f.write(" final int b = index %% %d;\n" % (64 / bpv))
- f.write(" final int shift = b * %d;\n" % bpv)
- f.write(" return (blocks[o] >>> shift) & %dL;\n" % ((1 << bpv) - 1))
- f.write(" }\n\n")
-
- f.write(" @Override\n")
- f.write(" public void set(int index, long value) {\n")
- if log_2 is not None:
- f.write(" final int o = index >>> %d;\n" % (6 - log_2))
- f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
- f.write(" final int shift = b << %d;\n" % log_2)
- else:
- f.write(" final int o = index / %d;\n" % (64 / bpv))
- f.write(" final int b = index %% %d;\n" % (64 / bpv))
- f.write(" final int shift = b * %d;\n" % bpv)
- f.write(" blocks[o] = (blocks[o] & ~(%dL << shift)) | (value << shift);\n" % ((1 << bpv) - 1))
- f.write(" }\n\n")
+if __name__ == "__main__":
+ f = open("Packed64SingleBlock.java", "w")
+ f.write(HEADER)
+ f.write(
+ " public static Packed64SingleBlock create(int valueCount, int bitsPerValue) {\n"
+ )
+ f.write(" switch (bitsPerValue) {\n")
+ for bpv in SUPPORTED_BITS_PER_VALUE:
+ f.write(" case %d:\n" % bpv)
+ f.write(" return new Packed64SingleBlock%d(valueCount);\n" % bpv)
+ f.write(" default:\n")
+ f.write(
+ ' throw new IllegalArgumentException("Unsupported number of bits per value: " + %d);\n'
+ % bpv
+ )
+ f.write(" }\n")
f.write(" }\n\n")
- f.write(FOOTER)
- f.close()
+ for bpv in SUPPORTED_BITS_PER_VALUE:
+ log_2 = 0
+ while (1 << log_2) < bpv:
+ log_2 = log_2 + 1
+ if (1 << log_2) != bpv:
+ log_2 = None
+
+ f.write(
+ " static class Packed64SingleBlock%d extends Packed64SingleBlock {\n\n"
+ % bpv
+ )
+
+ f.write(" Packed64SingleBlock%d(int valueCount) {\n" % bpv)
+ f.write(" super(valueCount, %d);\n" % bpv)
+ f.write(" }\n\n")
+
+ f.write(" @Override\n")
+ f.write(" public long get(int index) {\n")
+ if log_2 is not None:
+ f.write(" final int o = index >>> %d;\n" % (6 - log_2))
+ f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
+ f.write(" final int shift = b << %d;\n" % log_2)
+ else:
+ f.write(" final int o = index / %d;\n" % (64 / bpv))
+ f.write(" final int b = index %% %d;\n" % (64 / bpv))
+ f.write(" final int shift = b * %d;\n" % bpv)
+ f.write(" return (blocks[o] >>> shift) & %dL;\n" % ((1 << bpv) - 1))
+ f.write(" }\n\n")
+
+ f.write(" @Override\n")
+ f.write(" public void set(int index, long value) {\n")
+ if log_2 is not None:
+ f.write(" final int o = index >>> %d;\n" % (6 - log_2))
+ f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
+ f.write(" final int shift = b << %d;\n" % log_2)
+ else:
+ f.write(" final int o = index / %d;\n" % (64 / bpv))
+ f.write(" final int b = index %% %d;\n" % (64 / bpv))
+ f.write(" final int shift = b * %d;\n" % bpv)
+ f.write(
+ " blocks[o] = (blocks[o] & ~(%dL << shift)) | (value << shift);\n"
+ % ((1 << bpv) - 1)
+ )
+ f.write(" }\n\n")
+ f.write(" }\n\n")
+
+ f.write(FOOTER)
+ f.close()
diff --git a/lucene/analysis/common/src/generated/checksums/regenerateHTMLCharacterEntities.json b/lucene/analysis/common/src/generated/checksums/regenerateHTMLCharacterEntities.json
index 2c1c655a486..88a5e99c126 100644
--- a/lucene/analysis/common/src/generated/checksums/regenerateHTMLCharacterEntities.json
+++ b/lucene/analysis/common/src/generated/checksums/regenerateHTMLCharacterEntities.json
@@ -1,4 +1,4 @@
{
- "gradle/regenerate/jflex/htmlentity.py": "b3b4675343514614af7c543319833abe4eb3835d",
+ "gradle/regenerate/jflex/htmlentity.py": "4df967200499b92e9353a4af28ec9c291c72acd9",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/HTMLCharacterEntities.jflex": "d1aa75b9b37646efe31731394f84a063eb7eed9d"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil101.json b/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil101.json
index b08480a3eda..d35f030383a 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil101.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil101.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/ForDeltaUtil.java": "29fd59e9847d3012497c3079fa7ebc4f68fa6a94",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForDeltaUtil.py": "147b81236bc0373fe97e808c0ae7a2cb6276ae5a"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForDeltaUtil.py": "d9f10e4f3cf0e0c620eba4fa3083652234ba6cd9"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil103.json b/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil103.json
index abe1d457c93..ebf222af283 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil103.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil103.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/ForDeltaUtil.java": "4cd0564cb34801443d050065ab7ae8d93e2dca92",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForDeltaUtil.py": "8d656f27945b5a679babc41ac47afbd351359aa8"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForDeltaUtil.py": "b275bd4d4b2b0439f2a16ac84929e3657b780216"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil912.json b/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil912.json
index cf9daeb045a..bc6f7c41dd4 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil912.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForDeltaUtil912.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/ForDeltaUtil.java": "3ba9d988a0c295bf71829b8a2e4d0c23fe01ad6e",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForDeltaUtil.py": "cc8a431724673c0c31915f1c4dd9d01514ef5cad"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForDeltaUtil.py": "59f6ddb29ee38d35a76158a857cbe0f36d01fefd"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil101.json b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil101.json
index 7ed8dc3da57..f1d76aeef8d 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil101.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil101.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/ForUtil.java": "5a7c2e1e09780a2ccd31c22a1e1fa47443cf2a32",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForUtil.py": "50425669816e038573cabf373a2b68a12d1a5339"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForUtil.py": "7abbcbc5700dca2c934fbc4d355c6d06b2f83222"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil103.json b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil103.json
index cc5f05caa51..bb2defbfa16 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil103.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil103.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/ForUtil.java": "10904a43be9537b6c52ec13a1139c71c11345c97",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForUtil.py": "61a6c7d73b0e8b166ebf7344fc24e95873240e9f"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForUtil.py": "fc25d57f23adc350a7e9f89c8896cc571bce09f5"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil84.json b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil84.json
index ce2933706a6..7e3eacb2c29 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil84.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil84.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene84/ForUtil.java": "c3bff5677f7d98fbb362018a4c1dbad4d670610f",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene84/gen_ForUtil.py": "04fff02ed744b3f4efe0d7a7ff9faa06a2de6a6d"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene84/gen_ForUtil.py": "008d3e60b303fbb7c0e8c21f18748a6f384fbbc6"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil90.json b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil90.json
index afc40a39b01..019cd99e36a 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil90.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil90.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/ForUtil.java": "861cab516c7424e6323831c16f0f521499391a90",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/gen_ForUtil.py": "eec54fabbd5c580dbe2bc131b1954c95a2b1ff3c"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/gen_ForUtil.py": "d3cda28c6c1ca0c482b2f364be6e2fbf6cec0eac"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil912.json b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil912.json
index b5a92b5abfc..6b922679ceb 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil912.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil912.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/ForUtil.java": "e6db3c665dfebca8b93eb6b4651d2eb3af637b02",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForUtil.py": "22f64aeeebd3c4e6ed411204a6cda3f6f5e73031"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForUtil.py": "32e1b667b7ca6f422dfef7e9f706a5a44fa42f8e"
}
diff --git a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil99.json b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil99.json
index e35d41f68bf..9dabe9a678d 100644
--- a/lucene/backward-codecs/src/generated/checksums/regenerateForUtil99.json
+++ b/lucene/backward-codecs/src/generated/checksums/regenerateForUtil99.json
@@ -1,4 +1,4 @@
{
"lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/ForUtil.java": "f31797842f047626df6a1a6b97167bec60269fec",
- "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/gen_ForUtil.py": "b8fd3de65c18767522003fe430fa505747cce60e"
+ "lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/gen_ForUtil.py": "0a7138f8bfdde4997a3b5e67fbb62da43c0927ff"
}
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForDeltaUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForDeltaUtil.py
index a120969ef30..df32affc393 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForDeltaUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForDeltaUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForDeltaUtil.java"""
@@ -271,115 +270,164 @@ public final class ForDeltaUtil {
"""
+
def primitive_size_for_bpv(bpv):
- if bpv <= 3:
- # If we have 4 bits per value or less then we can compute the prefix sum of 32 ints that store 4 8-bit values each without overflowing.
- return 8
- elif bpv <= 10:
- # If we have 10 bits per value or less then we can compute the prefix sum of 64 ints that store 2 16-bit values each without overflowing.
- return 16
- else:
- # No risk of overflow with 32 bits per value
- return 32
+ if bpv <= 3:
+ # If we have 4 bits per value or less then we can compute the prefix sum of 32 ints that store 4 8-bit values each without overflowing.
+ return 8
+ elif bpv <= 10:
+ # If we have 10 bits per value or less then we can compute the prefix sum of 64 ints that store 2 16-bit values each without overflowing.
+ return 16
+ else:
+ # No risk of overflow with 32 bits per value
+ return 32
+
def next_primitive(bpv):
- if bpv <= 8:
- return 8
- elif bpv <= 16:
- return 16
- else:
- return 32
+ if bpv <= 8:
+ return 8
+ elif bpv <= 16:
+ return 16
+ else:
+ return 32
+
def writeRemainder(bpv, next_primitive, remaining_bits_per_int, o, num_values, f):
- iteration = 1
- num_ints = bpv * num_values / remaining_bits_per_int
- while num_ints % 2 == 0 and num_values % 2 == 0:
- num_ints /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n' %(o, iteration, num_ints, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_int
- f.write(' int l%d = tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- else:
- b -= remaining_bits
- f.write(' int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_int:
- b -= remaining_bits_per_int
- f.write(' l%d |= tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_int-b, next_primitive, b))
- remaining_bits = remaining_bits_per_int-b
- f.write(' ints[intsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_ints = bpv * num_values / remaining_bits_per_int
+ while num_ints % 2 == 0 and num_values % 2 == 0:
+ num_ints /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n"
+ % (o, iteration, num_ints, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_int
+ f.write(" int l%d = tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ else:
+ b -= remaining_bits
+ f.write(
+ " int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_int:
+ b -= remaining_bits_per_int
+ f.write(" l%d |= tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_int - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_int - b
+ f.write(" ints[intsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
+
def writeDecode(bpv, f):
- next_primitive = primitive_size_for_bpv(bpv)
- if next_primitive % bpv == 0:
- f.write(' private static void decode%dTo%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %(bpv, next_primitive))
- else:
- f.write(' private static void decode%dTo%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n' %(bpv, next_primitive))
- if bpv == next_primitive:
- f.write(' pdu.in.readInts(ints, 0, %d);\n' %(bpv*4))
- else:
- num_values_per_int = 32 / next_primitive
- remaining_bits = next_primitive % bpv
- num_iters = (next_primitive - 1) // bpv
- o = 4 * bpv * num_iters
- if remaining_bits == 0:
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, o, next_primitive, next_primitive - num_iters * bpv))
+ next_primitive = primitive_size_for_bpv(bpv)
+ if next_primitive % bpv == 0:
+ f.write(
+ " private static void decode%dTo%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % (bpv, next_primitive)
+ )
+ else:
+ f.write(
+ " private static void decode%dTo%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n"
+ % (bpv, next_primitive)
+ )
+ if bpv == next_primitive:
+ f.write(" pdu.in.readInts(ints, 0, %d);\n" % (bpv * 4))
else:
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, next_primitive, next_primitive - num_iters * bpv))
- writeRemainder(bpv, next_primitive, remaining_bits, o, 128/num_values_per_int - o, f)
- f.write(' }\n')
+ num_values_per_int = 32 / next_primitive
+ remaining_bits = next_primitive % bpv
+ num_iters = (next_primitive - 1) // bpv
+ o = 4 * bpv * num_iters
+ if remaining_bits == 0:
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ o,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ else:
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ writeRemainder(
+ bpv, next_primitive, remaining_bits, o, 128 / num_values_per_int - o, f
+ )
+ f.write(" }\n")
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- f.write("""
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ f.write("""
/**
* Delta-decode 128 integers into {@code ints}.
*/
void decodeAndPrefixSum(int bitsPerValue, PostingDecodingUtil pdu, int base, int[] ints) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- primitive_size = primitive_size_for_bpv(bpv)
- f.write(' case %d:\n' %bpv)
- if next_primitive(bpv) == primitive_size:
- if primitive_size % bpv == 0:
- f.write(' decode%d(pdu, ints);\n' %bpv)
- else:
- f.write(' decode%d(pdu, tmp, ints);\n' %bpv)
- else:
- if primitive_size % bpv == 0:
- f.write(' decode%dTo%d(pdu, ints);\n' %(bpv, primitive_size))
- else:
- f.write(' decode%dTo%d(pdu, tmp, ints);\n' %(bpv, primitive_size))
- f.write(' prefixSum%d(ints, base);\n' %primitive_size)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' if (bitsPerValue < 1 || bitsPerValue > Integer.SIZE) {\n')
- f.write(' throw new IllegalStateException("Illegal number of bits per value: " + bitsPerValue);\n')
- f.write(' }\n')
- f.write(' decodeSlow(bitsPerValue, pdu, tmp, ints);\n')
- f.write(' prefixSum32(ints, base);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ primitive_size = primitive_size_for_bpv(bpv)
+ f.write(" case %d:\n" % bpv)
+ if next_primitive(bpv) == primitive_size:
+ if primitive_size % bpv == 0:
+ f.write(" decode%d(pdu, ints);\n" % bpv)
+ else:
+ f.write(" decode%d(pdu, tmp, ints);\n" % bpv)
+ else:
+ if primitive_size % bpv == 0:
+ f.write(" decode%dTo%d(pdu, ints);\n" % (bpv, primitive_size))
+ else:
+ f.write(
+ " decode%dTo%d(pdu, tmp, ints);\n" % (bpv, primitive_size)
+ )
+ f.write(" prefixSum%d(ints, base);\n" % primitive_size)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" if (bitsPerValue < 1 || bitsPerValue > Integer.SIZE) {\n")
+ f.write(
+ ' throw new IllegalStateException("Illegal number of bits per value: " + bitsPerValue);\n'
+ )
+ f.write(" }\n")
+ f.write(" decodeSlow(bitsPerValue, pdu, tmp, ints);\n")
+ f.write(" prefixSum32(ints, base);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
- f.write('\n')
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- if next_primitive(bpv) != primitive_size_for_bpv(bpv):
- writeDecode(bpv, f)
- if bpv < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
+ f.write("\n")
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ if next_primitive(bpv) != primitive_size_for_bpv(bpv):
+ writeDecode(bpv, f)
+ if bpv < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
- f.write('}\n')
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForUtil.py
index 85751f46bfd..333e6d8b2a8 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene101/gen_ForUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForUtil.java"""
@@ -219,108 +218,159 @@ public final class ForUtil {
"""
+
def writeRemainder(bpv, next_primitive, remaining_bits_per_int, o, num_values, f):
- iteration = 1
- num_ints = bpv * num_values / remaining_bits_per_int
- while num_ints % 2 == 0 and num_values % 2 == 0:
- num_ints /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n' %(o, iteration, num_ints, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_int
- f.write(' int l%d = tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- else:
- b -= remaining_bits
- f.write(' int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_int:
- b -= remaining_bits_per_int
- f.write(' l%d |= tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_int-b, next_primitive, b))
- remaining_bits = remaining_bits_per_int-b
- f.write(' ints[intsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_ints = bpv * num_values / remaining_bits_per_int
+ while num_ints % 2 == 0 and num_values % 2 == 0:
+ num_ints /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n"
+ % (o, iteration, num_ints, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_int
+ f.write(" int l%d = tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ else:
+ b -= remaining_bits
+ f.write(
+ " int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_int:
+ b -= remaining_bits_per_int
+ f.write(" l%d |= tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_int - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_int - b
+ f.write(" ints[intsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
def writeDecode(bpv, f):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- if bpv == next_primitive:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.in.readInts(ints, 0, %d);\n' %(bpv*4))
- else:
- num_values_per_int = 32 / next_primitive
- remaining_bits = next_primitive % bpv
- num_iters = (next_primitive - 1) // bpv
- o = 4 * bpv * num_iters
- if remaining_bits == 0:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, o, next_primitive, next_primitive - num_iters * bpv))
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ if bpv == next_primitive:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(" pdu.in.readInts(ints, 0, %d);\n" % (bpv * 4))
else:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, next_primitive, next_primitive - num_iters * bpv))
- writeRemainder(bpv, next_primitive, remaining_bits, o, 128/num_values_per_int - o, f)
- f.write(' }\n')
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' static final int[] MASKS%d = new int[%d];\n' %(primitive_size, primitive_size))
- f.write('\n')
- f.write(' static {\n')
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' for (int i = 0; i < %d; ++i) {\n' %primitive_size)
- f.write(' MASKS%d[i] = mask%d(i);\n' %(primitive_size, primitive_size))
- f.write(' }\n')
- f.write(' }')
- f.write("""
+ num_values_per_int = 32 / next_primitive
+ remaining_bits = next_primitive % bpv
+ num_iters = (next_primitive - 1) // bpv
+ o = 4 * bpv * num_iters
+ if remaining_bits == 0:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ o,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ else:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ writeRemainder(
+ bpv, next_primitive, remaining_bits, o, 128 / num_values_per_int - o, f
+ )
+ f.write(" }\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(
+ " static final int[] MASKS%d = new int[%d];\n"
+ % (primitive_size, primitive_size)
+ )
+ f.write("\n")
+ f.write(" static {\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(" for (int i = 0; i < %d; ++i) {\n" % primitive_size)
+ f.write(" MASKS%d[i] = mask%d(i);\n" % (primitive_size, primitive_size))
+ f.write(" }\n")
+ f.write(" }")
+ f.write("""
// mark values in array as final ints to avoid the cost of reading array, arrays should only be
// used when the idx is a variable
""")
- for primitive_size in PRIMITIVE_SIZE:
- for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
- f.write(' static final int MASK%d_%d = MASKS%d[%d];\n' %(primitive_size, bpv, primitive_size, bpv))
-
- f.write("""
+ for primitive_size in PRIMITIVE_SIZE:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ f.write(
+ " static final int MASK%d_%d = MASKS%d[%d];\n"
+ % (primitive_size, bpv, primitive_size, bpv)
+ )
+
+ f.write("""
/** Decode 128 integers into {@code ints}. */
void decode(int bitsPerValue, PostingDecodingUtil pdu, int[] ints) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- if next_primitive % bpv == 0:
- f.write(' decode%d(pdu, ints);\n' %bpv)
- else:
- f.write(' decode%d(pdu, tmp, ints);\n' %bpv)
- if next_primitive != 32:
- f.write(' expand%d(ints);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, pdu, tmp, ints);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- writeDecode(i, f)
- if i < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ if next_primitive % bpv == 0:
+ f.write(" decode%d(pdu, ints);\n" % bpv)
+ else:
+ f.write(" decode%d(pdu, tmp, ints);\n" % bpv)
+ if next_primitive != 32:
+ f.write(" expand%d(ints);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, pdu, tmp, ints);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ writeDecode(i, f)
+ if i < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
+
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForDeltaUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForDeltaUtil.py
index 912f18e6ce7..e1e334016e6 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForDeltaUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForDeltaUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForDeltaUtil.java"""
@@ -174,115 +173,164 @@ public final class ForDeltaUtil {
"""
+
def primitive_size_for_bpv(bpv):
- if bpv <= 3:
- # If we have 4 bits per value or less then we can compute the prefix sum of 32 ints that store 4 8-bit values each without overflowing.
- return 8
- elif bpv <= 10:
- # If we have 10 bits per value or less then we can compute the prefix sum of 64 ints that store 2 16-bit values each without overflowing.
- return 16
- else:
- # No risk of overflow with 32 bits per value
- return 32
+ if bpv <= 3:
+ # If we have 4 bits per value or less then we can compute the prefix sum of 32 ints that store 4 8-bit values each without overflowing.
+ return 8
+ elif bpv <= 10:
+ # If we have 10 bits per value or less then we can compute the prefix sum of 64 ints that store 2 16-bit values each without overflowing.
+ return 16
+ else:
+ # No risk of overflow with 32 bits per value
+ return 32
+
def next_primitive(bpv):
- if bpv <= 8:
- return 8
- elif bpv <= 16:
- return 16
- else:
- return 32
+ if bpv <= 8:
+ return 8
+ elif bpv <= 16:
+ return 16
+ else:
+ return 32
+
def writeRemainder(bpv, next_primitive, remaining_bits_per_int, o, num_values, f):
- iteration = 1
- num_ints = bpv * num_values / remaining_bits_per_int
- while num_ints % 2 == 0 and num_values % 2 == 0:
- num_ints /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n' %(o, iteration, num_ints, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_int
- f.write(' int l%d = tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- else:
- b -= remaining_bits
- f.write(' int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_int:
- b -= remaining_bits_per_int
- f.write(' l%d |= tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_int-b, next_primitive, b))
- remaining_bits = remaining_bits_per_int-b
- f.write(' ints[intsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_ints = bpv * num_values / remaining_bits_per_int
+ while num_ints % 2 == 0 and num_values % 2 == 0:
+ num_ints /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n"
+ % (o, iteration, num_ints, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_int
+ f.write(" int l%d = tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ else:
+ b -= remaining_bits
+ f.write(
+ " int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_int:
+ b -= remaining_bits_per_int
+ f.write(" l%d |= tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_int - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_int - b
+ f.write(" ints[intsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
+
def writeDecode(bpv, f):
- next_primitive = primitive_size_for_bpv(bpv)
- if next_primitive % bpv == 0:
- f.write(' private static void decode%dTo%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %(bpv, next_primitive))
- else:
- f.write(' private static void decode%dTo%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n' %(bpv, next_primitive))
- if bpv == next_primitive:
- f.write(' pdu.in.readInts(ints, 0, %d);\n' %(bpv*4))
- else:
- num_values_per_int = 32 / next_primitive
- remaining_bits = next_primitive % bpv
- num_iters = (next_primitive - 1) // bpv
- o = 4 * bpv * num_iters
- if remaining_bits == 0:
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, o, next_primitive, next_primitive - num_iters * bpv))
+ next_primitive = primitive_size_for_bpv(bpv)
+ if next_primitive % bpv == 0:
+ f.write(
+ " private static void decode%dTo%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % (bpv, next_primitive)
+ )
+ else:
+ f.write(
+ " private static void decode%dTo%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n"
+ % (bpv, next_primitive)
+ )
+ if bpv == next_primitive:
+ f.write(" pdu.in.readInts(ints, 0, %d);\n" % (bpv * 4))
else:
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, next_primitive, next_primitive - num_iters * bpv))
- writeRemainder(bpv, next_primitive, remaining_bits, o, 128/num_values_per_int - o, f)
- f.write(' }\n')
+ num_values_per_int = 32 / next_primitive
+ remaining_bits = next_primitive % bpv
+ num_iters = (next_primitive - 1) // bpv
+ o = 4 * bpv * num_iters
+ if remaining_bits == 0:
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ o,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ else:
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ writeRemainder(
+ bpv, next_primitive, remaining_bits, o, 128 / num_values_per_int - o, f
+ )
+ f.write(" }\n")
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- f.write("""
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ f.write("""
/**
* Delta-decode 128 integers into {@code ints}.
*/
void decodeAndPrefixSum(int bitsPerValue, PostingDecodingUtil pdu, int base, int[] ints) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- primitive_size = primitive_size_for_bpv(bpv)
- f.write(' case %d:\n' %bpv)
- if next_primitive(bpv) == primitive_size:
- if primitive_size % bpv == 0:
- f.write(' decode%d(pdu, ints);\n' %bpv)
- else:
- f.write(' decode%d(pdu, tmp, ints);\n' %bpv)
- else:
- if primitive_size % bpv == 0:
- f.write(' decode%dTo%d(pdu, ints);\n' %(bpv, primitive_size))
- else:
- f.write(' decode%dTo%d(pdu, tmp, ints);\n' %(bpv, primitive_size))
- f.write(' prefixSum%d(ints, base);\n' %primitive_size)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' if (bitsPerValue < 1 || bitsPerValue > Integer.SIZE) {\n')
- f.write(' throw new IllegalStateException("Illegal number of bits per value: " + bitsPerValue);\n')
- f.write(' }\n')
- f.write(' decodeSlow(bitsPerValue, pdu, tmp, ints);\n')
- f.write(' prefixSum32(ints, base);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ primitive_size = primitive_size_for_bpv(bpv)
+ f.write(" case %d:\n" % bpv)
+ if next_primitive(bpv) == primitive_size:
+ if primitive_size % bpv == 0:
+ f.write(" decode%d(pdu, ints);\n" % bpv)
+ else:
+ f.write(" decode%d(pdu, tmp, ints);\n" % bpv)
+ else:
+ if primitive_size % bpv == 0:
+ f.write(" decode%dTo%d(pdu, ints);\n" % (bpv, primitive_size))
+ else:
+ f.write(
+ " decode%dTo%d(pdu, tmp, ints);\n" % (bpv, primitive_size)
+ )
+ f.write(" prefixSum%d(ints, base);\n" % primitive_size)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" if (bitsPerValue < 1 || bitsPerValue > Integer.SIZE) {\n")
+ f.write(
+ ' throw new IllegalStateException("Illegal number of bits per value: " + bitsPerValue);\n'
+ )
+ f.write(" }\n")
+ f.write(" decodeSlow(bitsPerValue, pdu, tmp, ints);\n")
+ f.write(" prefixSum32(ints, base);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
- f.write('\n')
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- if next_primitive(bpv) != primitive_size_for_bpv(bpv):
- writeDecode(bpv, f)
- if bpv < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
+ f.write("\n")
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ if next_primitive(bpv) != primitive_size_for_bpv(bpv):
+ writeDecode(bpv, f)
+ if bpv < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
- f.write('}\n')
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForUtil.py
index 6ecfeee16d0..e8498c32c59 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene103/gen_ForUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForUtil.java"""
@@ -220,108 +219,159 @@ public final class ForUtil {
"""
+
def writeRemainder(bpv, next_primitive, remaining_bits_per_int, o, num_values, f):
- iteration = 1
- num_ints = bpv * num_values / remaining_bits_per_int
- while num_ints % 2 == 0 and num_values % 2 == 0:
- num_ints /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n' %(o, iteration, num_ints, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_int
- f.write(' int l%d = tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- else:
- b -= remaining_bits
- f.write(' int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_int:
- b -= remaining_bits_per_int
- f.write(' l%d |= tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_int-b, next_primitive, b))
- remaining_bits = remaining_bits_per_int-b
- f.write(' ints[intsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_ints = bpv * num_values / remaining_bits_per_int
+ while num_ints % 2 == 0 and num_values % 2 == 0:
+ num_ints /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n"
+ % (o, iteration, num_ints, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_int
+ f.write(" int l%d = tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ else:
+ b -= remaining_bits
+ f.write(
+ " int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_int:
+ b -= remaining_bits_per_int
+ f.write(" l%d |= tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_int - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_int - b
+ f.write(" ints[intsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
def writeDecode(bpv, f):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- if bpv == next_primitive:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.in.readInts(ints, 0, %d);\n' %(bpv*4))
- else:
- num_values_per_int = 32 / next_primitive
- remaining_bits = next_primitive % bpv
- num_iters = (next_primitive - 1) // bpv
- o = 4 * bpv * num_iters
- if remaining_bits == 0:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, o, next_primitive, next_primitive - num_iters * bpv))
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ if bpv == next_primitive:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(" pdu.in.readInts(ints, 0, %d);\n" % (bpv * 4))
else:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n' %(bpv*4, next_primitive - bpv, bpv, next_primitive, bpv, next_primitive, next_primitive - num_iters * bpv))
- writeRemainder(bpv, next_primitive, remaining_bits, o, 128/num_values_per_int - o, f)
- f.write(' }\n')
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' static final int[] MASKS%d = new int[%d];\n' %(primitive_size, primitive_size))
- f.write('\n')
- f.write(' static {\n')
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' for (int i = 0; i < %d; ++i) {\n' %primitive_size)
- f.write(' MASKS%d[i] = mask%d(i);\n' %(primitive_size, primitive_size))
- f.write(' }\n')
- f.write(' }')
- f.write("""
+ num_values_per_int = 32 / next_primitive
+ remaining_bits = next_primitive % bpv
+ num_iters = (next_primitive - 1) // bpv
+ o = 4 * bpv * num_iters
+ if remaining_bits == 0:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ o,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ else:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n"
+ % (
+ bpv * 4,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ writeRemainder(
+ bpv, next_primitive, remaining_bits, o, 128 / num_values_per_int - o, f
+ )
+ f.write(" }\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(
+ " static final int[] MASKS%d = new int[%d];\n"
+ % (primitive_size, primitive_size)
+ )
+ f.write("\n")
+ f.write(" static {\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(" for (int i = 0; i < %d; ++i) {\n" % primitive_size)
+ f.write(" MASKS%d[i] = mask%d(i);\n" % (primitive_size, primitive_size))
+ f.write(" }\n")
+ f.write(" }")
+ f.write("""
// mark values in array as final ints to avoid the cost of reading array, arrays should only be
// used when the idx is a variable
""")
- for primitive_size in PRIMITIVE_SIZE:
- for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
- f.write(' static final int MASK%d_%d = MASKS%d[%d];\n' %(primitive_size, bpv, primitive_size, bpv))
-
- f.write("""
+ for primitive_size in PRIMITIVE_SIZE:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ f.write(
+ " static final int MASK%d_%d = MASKS%d[%d];\n"
+ % (primitive_size, bpv, primitive_size, bpv)
+ )
+
+ f.write("""
/** Decode 128 integers into {@code ints}. */
void decode(int bitsPerValue, PostingDecodingUtil pdu, int[] ints) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- if next_primitive % bpv == 0:
- f.write(' decode%d(pdu, ints);\n' %bpv)
- else:
- f.write(' decode%d(pdu, tmp, ints);\n' %bpv)
- if next_primitive != 32:
- f.write(' expand%d(ints);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, pdu, tmp, ints);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- writeDecode(i, f)
- if i < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ if next_primitive % bpv == 0:
+ f.write(" decode%d(pdu, ints);\n" % bpv)
+ else:
+ f.write(" decode%d(pdu, tmp, ints);\n" % bpv)
+ if next_primitive != 32:
+ f.write(" expand%d(ints);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, pdu, tmp, ints);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ writeDecode(i, f)
+ if i < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
+
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene84/gen_ForUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene84/gen_ForUtil.py
index d9fb80c5677..a4531203ea5 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene84/gen_ForUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene84/gen_ForUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForUtil.java"""
@@ -379,154 +378,205 @@ final class ForUtil {
"""
-def writeRemainderWithSIMDOptimize(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
-
-
- f.write(' shiftLongs(tmp, %d, tmp, 0, 0, MASK%d_%d);\n' % (iteration * num_longs, next_primitive, remaining_bits_per_long))
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- tmp_idx = 0
- b = bpv
- b -= remaining_bits_per_long
- f.write(' long l0 = tmp[tmpIdx + %d] << %d;\n' %(tmp_idx, b))
- tmp_idx += 1
- while b >= remaining_bits_per_long:
- b -= remaining_bits_per_long
- f.write(' l0 |= tmp[tmpIdx + %d] << %d;\n' %(tmp_idx, b))
- tmp_idx += 1
- f.write(' longs[longsIdx + 0] = l0;\n')
- f.write(' }\n')
-
-def writeRemainder(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
+def writeRemainderWithSIMDOptimize(
+ bpv, next_primitive, remaining_bits_per_long, o, num_values, f
+):
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+
+ f.write(
+ " shiftLongs(tmp, %d, tmp, 0, 0, MASK%d_%d);\n"
+ % (iteration * num_longs, next_primitive, remaining_bits_per_long)
+ )
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ tmp_idx = 0
b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_long
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
- else:
- b -= remaining_bits
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
+ b -= remaining_bits_per_long
+ f.write(" long l0 = tmp[tmpIdx + %d] << %d;\n" % (tmp_idx, b))
tmp_idx += 1
while b >= remaining_bits_per_long:
- b -= remaining_bits_per_long
- f.write(' l%d |= (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_long-b, next_primitive, b))
- remaining_bits = remaining_bits_per_long-b
- f.write(' longs[longsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ b -= remaining_bits_per_long
+ f.write(" l0 |= tmp[tmpIdx + %d] << %d;\n" % (tmp_idx, b))
+ tmp_idx += 1
+ f.write(" longs[longsIdx + 0] = l0;\n")
+ f.write(" }\n")
+
+def writeRemainder(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_long
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits_per_long, b)
+ )
+ else:
+ b -= remaining_bits
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits_per_long, b)
+ )
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_long - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_long - b
+ f.write(" longs[longsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
def writeDecode(bpv, f):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' private static void decode%d(DataInput in, long[] tmp, long[] longs) throws IOException {\n' %bpv)
- num_values_per_long = 64 / next_primitive
- if bpv == next_primitive:
- f.write(' readLELongs(in, longs, 0, %d);\n' %(bpv*2))
- else:
- f.write(' readLELongs(in, tmp, 0, %d);\n' %(bpv*2))
- shift = next_primitive - bpv
- o = 0
- while shift >= 0:
- f.write(' shiftLongs(tmp, %d, longs, %d, %d, MASK%d_%d);\n' %(bpv*2, o, shift, next_primitive, bpv))
- o += bpv*2
- shift -= bpv
- if shift + bpv > 0:
- if bpv % (next_primitive % bpv) == 0:
- writeRemainderWithSIMDOptimize(bpv, next_primitive, shift + bpv, o, 128/num_values_per_long - o, f)
- else:
- writeRemainder(bpv, next_primitive, shift + bpv, o, 128/num_values_per_long - o, f)
- f.write(' }\n')
- f.write('\n')
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' private static final long[] MASKS%d = new long[%d];\n' %(primitive_size, primitive_size))
- f.write('\n')
- f.write(' static {\n')
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' for (int i = 0; i < %d; ++i) {\n' %primitive_size)
- f.write(' MASKS%d[i] = mask%d(i);\n' %(primitive_size, primitive_size))
- f.write(' }\n')
- f.write(' }\n')
- f.write(' // mark values in array as final longs to avoid the cost of reading array, arrays should only be\n')
- f.write(' // used when the idx is a variable\n')
- for primitive_size in PRIMITIVE_SIZE:
- for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
- if bpv * 2 != primitive_size or primitive_size == 8:
- f.write(' private static final long MASK%d_%d = MASKS%d[%d];\n' %(primitive_size, bpv, primitive_size, bpv))
-
- f.write("""
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(
+ " private static void decode%d(DataInput in, long[] tmp, long[] longs) throws IOException {\n"
+ % bpv
+ )
+ num_values_per_long = 64 / next_primitive
+ if bpv == next_primitive:
+ f.write(" readLELongs(in, longs, 0, %d);\n" % (bpv * 2))
+ else:
+ f.write(" readLELongs(in, tmp, 0, %d);\n" % (bpv * 2))
+ shift = next_primitive - bpv
+ o = 0
+ while shift >= 0:
+ f.write(
+ " shiftLongs(tmp, %d, longs, %d, %d, MASK%d_%d);\n"
+ % (bpv * 2, o, shift, next_primitive, bpv)
+ )
+ o += bpv * 2
+ shift -= bpv
+ if shift + bpv > 0:
+ if bpv % (next_primitive % bpv) == 0:
+ writeRemainderWithSIMDOptimize(
+ bpv,
+ next_primitive,
+ shift + bpv,
+ o,
+ 128 / num_values_per_long - o,
+ f,
+ )
+ else:
+ writeRemainder(
+ bpv,
+ next_primitive,
+ shift + bpv,
+ o,
+ 128 / num_values_per_long - o,
+ f,
+ )
+ f.write(" }\n")
+ f.write("\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(
+ " private static final long[] MASKS%d = new long[%d];\n"
+ % (primitive_size, primitive_size)
+ )
+ f.write("\n")
+ f.write(" static {\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(" for (int i = 0; i < %d; ++i) {\n" % primitive_size)
+ f.write(" MASKS%d[i] = mask%d(i);\n" % (primitive_size, primitive_size))
+ f.write(" }\n")
+ f.write(" }\n")
+ f.write(
+ " // mark values in array as final longs to avoid the cost of reading array, arrays should only be\n"
+ )
+ f.write(" // used when the idx is a variable\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ if bpv * 2 != primitive_size or primitive_size == 8:
+ f.write(
+ " private static final long MASK%d_%d = MASKS%d[%d];\n"
+ % (primitive_size, bpv, primitive_size, bpv)
+ )
+
+ f.write("""
/** Decode 128 integers into {@code longs}. */
void decode(int bitsPerValue, DataInput in, long[] longs) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- f.write(' expand%d(longs);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' expand32(longs);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- f.write("""
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ f.write(" expand%d(longs);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" expand32(longs);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ f.write("""
/** Delta-decode 128 integers into {@code longs}. */
void decodeAndPrefixSum(int bitsPerValue, DataInput in, long base, long[] longs)
throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- f.write(' prefixSum%d(longs, base);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' prefixSum32(longs, base);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- f.write('\n')
- for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- writeDecode(i, f)
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ f.write(" prefixSum%d(longs, base);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" prefixSum32(longs, base);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ f.write("\n")
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ writeDecode(i, f)
+
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/gen_ForUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/gen_ForUtil.py
index 714dc8c14a1..f91c7789710 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/gen_ForUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/gen_ForUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForUtil.java"""
@@ -280,130 +279,180 @@ final class ForUtil {
"""
-def writeRemainderWithSIMDOptimize(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
-
- f.write(' shiftLongs(tmp, %d, tmp, 0, 0, MASK%d_%d);\n' % (iteration * num_longs, next_primitive, remaining_bits_per_long))
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- tmp_idx = 0
- b = bpv
- b -= remaining_bits_per_long
- f.write(' long l0 = tmp[tmpIdx + %d] << %d;\n' %(tmp_idx, b))
- tmp_idx += 1
- while b >= remaining_bits_per_long:
+
+def writeRemainderWithSIMDOptimize(
+ bpv, next_primitive, remaining_bits_per_long, o, num_values, f
+):
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+
+ f.write(
+ " shiftLongs(tmp, %d, tmp, 0, 0, MASK%d_%d);\n"
+ % (iteration * num_longs, next_primitive, remaining_bits_per_long)
+ )
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ tmp_idx = 0
+ b = bpv
b -= remaining_bits_per_long
- f.write(' l0 |= tmp[tmpIdx + %d] << %d;\n' %(tmp_idx, b))
+ f.write(" long l0 = tmp[tmpIdx + %d] << %d;\n" % (tmp_idx, b))
tmp_idx += 1
- f.write(' longs[longsIdx + 0] = l0;\n')
- f.write(' }\n')
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(" l0 |= tmp[tmpIdx + %d] << %d;\n" % (tmp_idx, b))
+ tmp_idx += 1
+ f.write(" longs[longsIdx + 0] = l0;\n")
+ f.write(" }\n")
def writeRemainder(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_long
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
- else:
- b -= remaining_bits
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_long:
- b -= remaining_bits_per_long
- f.write(' l%d |= (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_long-b, next_primitive, b))
- remaining_bits = remaining_bits_per_long-b
- f.write(' longs[longsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_long
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits_per_long, b)
+ )
+ else:
+ b -= remaining_bits
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits_per_long, b)
+ )
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_long - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_long - b
+ f.write(" longs[longsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
def writeDecode(bpv, f):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' private static void decode%d(DataInput in, long[] tmp, long[] longs) throws IOException {\n' %bpv)
- num_values_per_long = 64 / next_primitive
- if bpv == next_primitive:
- f.write(' in.readLongs(longs, 0, %d);\n' %(bpv*2))
- else:
- f.write(' in.readLongs(tmp, 0, %d);\n' %(bpv*2))
- shift = next_primitive - bpv
- o = 0
- while shift >= 0:
- f.write(' shiftLongs(tmp, %d, longs, %d, %d, MASK%d_%d);\n' %(bpv*2, o, shift, next_primitive, bpv))
- o += bpv*2
- shift -= bpv
- if shift + bpv > 0:
- if bpv % (next_primitive % bpv) == 0:
- writeRemainderWithSIMDOptimize(bpv, next_primitive, shift + bpv, o, 128/num_values_per_long - o, f)
- else:
- writeRemainder(bpv, next_primitive, shift + bpv, o, 128/num_values_per_long - o, f)
- f.write(' }\n')
-
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' private static final long[] MASKS%d = new long[%d];\n' %(primitive_size, primitive_size))
- f.write('\n')
- f.write(' static {\n')
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' for (int i = 0; i < %d; ++i) {\n' %primitive_size)
- f.write(' MASKS%d[i] = mask%d(i);\n' %(primitive_size, primitive_size))
- f.write(' }\n')
- f.write(' }')
- f.write("""
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(
+ " private static void decode%d(DataInput in, long[] tmp, long[] longs) throws IOException {\n"
+ % bpv
+ )
+ num_values_per_long = 64 / next_primitive
+ if bpv == next_primitive:
+ f.write(" in.readLongs(longs, 0, %d);\n" % (bpv * 2))
+ else:
+ f.write(" in.readLongs(tmp, 0, %d);\n" % (bpv * 2))
+ shift = next_primitive - bpv
+ o = 0
+ while shift >= 0:
+ f.write(
+ " shiftLongs(tmp, %d, longs, %d, %d, MASK%d_%d);\n"
+ % (bpv * 2, o, shift, next_primitive, bpv)
+ )
+ o += bpv * 2
+ shift -= bpv
+ if shift + bpv > 0:
+ if bpv % (next_primitive % bpv) == 0:
+ writeRemainderWithSIMDOptimize(
+ bpv,
+ next_primitive,
+ shift + bpv,
+ o,
+ 128 / num_values_per_long - o,
+ f,
+ )
+ else:
+ writeRemainder(
+ bpv,
+ next_primitive,
+ shift + bpv,
+ o,
+ 128 / num_values_per_long - o,
+ f,
+ )
+ f.write(" }\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(
+ " private static final long[] MASKS%d = new long[%d];\n"
+ % (primitive_size, primitive_size)
+ )
+ f.write("\n")
+ f.write(" static {\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(" for (int i = 0; i < %d; ++i) {\n" % primitive_size)
+ f.write(" MASKS%d[i] = mask%d(i);\n" % (primitive_size, primitive_size))
+ f.write(" }\n")
+ f.write(" }")
+ f.write("""
// mark values in array as final longs to avoid the cost of reading array, arrays should only be
// used when the idx is a variable
""")
- for primitive_size in PRIMITIVE_SIZE:
- for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
- if bpv * 2 != primitive_size or primitive_size == 8:
- f.write(' private static final long MASK%d_%d = MASKS%d[%d];\n' %(primitive_size, bpv, primitive_size, bpv))
-
- f.write("""
+ for primitive_size in PRIMITIVE_SIZE:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ if bpv * 2 != primitive_size or primitive_size == 8:
+ f.write(
+ " private static final long MASK%d_%d = MASKS%d[%d];\n"
+ % (primitive_size, bpv, primitive_size, bpv)
+ )
+
+ f.write("""
/** Decode 128 integers into {@code longs}. */
void decode(int bitsPerValue, DataInput in, long[] longs) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- f.write(' expand%d(longs);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' expand32(longs);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- f.write("""
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ f.write(" expand%d(longs);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" expand32(longs);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ f.write("""
/**
* Decodes 128 integers into 64 {@code longs} such that each long contains two values, each
* represented with 32 bits. Values [0..63] are encoded in the high-order bits of {@code longs}
@@ -413,27 +462,27 @@ if __name__ == '__main__':
void decodeTo32(int bitsPerValue, DataInput in, long[] longs) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- if next_primitive <= 16:
- f.write(' expand%dTo32(longs);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- f.write('\n')
- for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- writeDecode(i, f)
- if i < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ if next_primitive <= 16:
+ f.write(" expand%dTo32(longs);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ f.write("\n")
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ writeDecode(i, f)
+ if i < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
+
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForDeltaUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForDeltaUtil.py
index 4d71bfce196..43946203874 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForDeltaUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForDeltaUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForDeltaUtil.java"""
@@ -352,112 +351,159 @@ final class ForDeltaUtil {
"""
+
def primitive_size_for_bpv(bpv):
- if bpv <= 4:
- # If we have 4 bits per value or less then we can compute the prefix sum of 16 longs that store 8 4-bit values each without overflowing.
- return 8
- elif bpv <= 11:
- # If we have 11 bits per value or less then we can compute the prefix sum of 32 longs that store 4 16-bit values each without overflowing.
- return 16
- else:
- # No risk of overflow with 32 bits per value
- return 32
+ if bpv <= 4:
+ # If we have 4 bits per value or less then we can compute the prefix sum of 16 longs that store 8 4-bit values each without overflowing.
+ return 8
+ elif bpv <= 11:
+ # If we have 11 bits per value or less then we can compute the prefix sum of 32 longs that store 4 16-bit values each without overflowing.
+ return 16
+ else:
+ # No risk of overflow with 32 bits per value
+ return 32
+
def next_primitive(bpv):
- if bpv <= 8:
- return 8
- elif bpv <= 16:
- return 16
- else:
- return 32
+ if bpv <= 8:
+ return 8
+ elif bpv <= 16:
+ return 16
+ else:
+ return 32
+
def writeRemainder(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_long
- f.write(' long l%d = tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- else:
- b -= remaining_bits
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_long:
- b -= remaining_bits_per_long
- f.write(' l%d |= tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_long-b, next_primitive, b))
- remaining_bits = remaining_bits_per_long-b
- f.write(' longs[longsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_long
+ f.write(" long l%d = tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ else:
+ b -= remaining_bits
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(" l%d |= tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_long - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_long - b
+ f.write(" longs[longsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
+
def writeDecode(bpv, f):
- next_primitive = primitive_size_for_bpv(bpv)
- if next_primitive % bpv == 0:
- f.write(' private static void decode%dTo%d(IndexInput in, long[] longs) throws IOException {\n' %(bpv, next_primitive))
- else:
- f.write(' private static void decode%dTo%d(IndexInput in, long[] tmp, long[] longs) throws IOException {\n' %(bpv, next_primitive))
- if bpv == next_primitive:
- f.write(' in.readLongs(longs, 0, %d);\n' %(bpv*2))
- else:
- num_values_per_long = 64 / next_primitive
- remaining_bits = next_primitive % bpv
- num_iters = (next_primitive - 1) // bpv
- o = 2 * bpv * num_iters
- if remaining_bits == 0:
- f.write(' splitLongs(in, %d, longs, %d, %d, MASK%d_%d, longs, %d, MASK%d_%d);\n' %(bpv*2, next_primitive - bpv, bpv, next_primitive, bpv, o, next_primitive, next_primitive - num_iters * bpv))
+ next_primitive = primitive_size_for_bpv(bpv)
+ if next_primitive % bpv == 0:
+ f.write(
+ " private static void decode%dTo%d(IndexInput in, long[] longs) throws IOException {\n"
+ % (bpv, next_primitive)
+ )
else:
- f.write(' splitLongs(in, %d, longs, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n' %(bpv*2, next_primitive - bpv, bpv, next_primitive, bpv, next_primitive, next_primitive - num_iters * bpv))
- writeRemainder(bpv, next_primitive, remaining_bits, o, 128/num_values_per_long - o, f)
- f.write(' }\n')
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- f.write("""
+ f.write(
+ " private static void decode%dTo%d(IndexInput in, long[] tmp, long[] longs) throws IOException {\n"
+ % (bpv, next_primitive)
+ )
+ if bpv == next_primitive:
+ f.write(" in.readLongs(longs, 0, %d);\n" % (bpv * 2))
+ else:
+ num_values_per_long = 64 / next_primitive
+ remaining_bits = next_primitive % bpv
+ num_iters = (next_primitive - 1) // bpv
+ o = 2 * bpv * num_iters
+ if remaining_bits == 0:
+ f.write(
+ " splitLongs(in, %d, longs, %d, %d, MASK%d_%d, longs, %d, MASK%d_%d);\n"
+ % (
+ bpv * 2,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ o,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ else:
+ f.write(
+ " splitLongs(in, %d, longs, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n"
+ % (
+ bpv * 2,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ writeRemainder(
+ bpv, next_primitive, remaining_bits, o, 128 / num_values_per_long - o, f
+ )
+ f.write(" }\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ f.write("""
/**
* Delta-decode 128 integers into {@code longs}.
*/
void decodeAndPrefixSum(int bitsPerValue, IndexInput in, long base, long[] longs) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- primitive_size = primitive_size_for_bpv(bpv)
- f.write(' case %d:\n' %bpv)
- if next_primitive(bpv) == primitive_size:
- if primitive_size % bpv == 0:
- f.write(' decode%d(in, longs);\n' %bpv)
- else:
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- else:
- if primitive_size % bpv == 0:
- f.write(' decode%dTo%d(in, longs);\n' %(bpv, primitive_size))
- else:
- f.write(' decode%dTo%d(in, tmp, longs);\n' %(bpv, primitive_size))
- f.write(' prefixSum%d(longs, base);\n' %primitive_size)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' prefixSum32(longs, base);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- f.write('\n')
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- if next_primitive(bpv) != primitive_size_for_bpv(bpv):
- writeDecode(bpv, f)
- if bpv < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ primitive_size = primitive_size_for_bpv(bpv)
+ f.write(" case %d:\n" % bpv)
+ if next_primitive(bpv) == primitive_size:
+ if primitive_size % bpv == 0:
+ f.write(" decode%d(in, longs);\n" % bpv)
+ else:
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ else:
+ if primitive_size % bpv == 0:
+ f.write(" decode%dTo%d(in, longs);\n" % (bpv, primitive_size))
+ else:
+ f.write(
+ " decode%dTo%d(in, tmp, longs);\n" % (bpv, primitive_size)
+ )
+ f.write(" prefixSum%d(longs, base);\n" % primitive_size)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" prefixSum32(longs, base);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ f.write("\n")
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ if next_primitive(bpv) != primitive_size_for_bpv(bpv):
+ writeDecode(bpv, f)
+ if bpv < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
+
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForUtil.py
index 5f9fc431b19..0e296442275 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene912/gen_ForUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForUtil.java"""
@@ -263,108 +262,159 @@ final class ForUtil {
"""
+
def writeRemainder(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_long
- f.write(' long l%d = tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- else:
- b -= remaining_bits
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_long:
- b -= remaining_bits_per_long
- f.write(' l%d |= tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_long-b, next_primitive, b))
- remaining_bits = remaining_bits_per_long-b
- f.write(' longs[longsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_long
+ f.write(" long l%d = tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ else:
+ b -= remaining_bits
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(" l%d |= tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_long - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_long - b
+ f.write(" longs[longsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
def writeDecode(bpv, f):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- if bpv == next_primitive:
- f.write(' static void decode%d(IndexInput in, long[] longs) throws IOException {\n' %bpv)
- f.write(' in.readLongs(longs, 0, %d);\n' %(bpv*2))
- else:
- num_values_per_long = 64 / next_primitive
- remaining_bits = next_primitive % bpv
- num_iters = (next_primitive - 1) // bpv
- o = 2 * bpv * num_iters
- if remaining_bits == 0:
- f.write(' static void decode%d(IndexInput in, long[] longs) throws IOException {\n' %bpv)
- f.write(' splitLongs(in, %d, longs, %d, %d, MASK%d_%d, longs, %d, MASK%d_%d);\n' %(bpv*2, next_primitive - bpv, bpv, next_primitive, bpv, o, next_primitive, next_primitive - num_iters * bpv))
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ if bpv == next_primitive:
+ f.write(
+ " static void decode%d(IndexInput in, long[] longs) throws IOException {\n"
+ % bpv
+ )
+ f.write(" in.readLongs(longs, 0, %d);\n" % (bpv * 2))
else:
- f.write(' static void decode%d(IndexInput in, long[] tmp, long[] longs) throws IOException {\n' %bpv)
- f.write(' splitLongs(in, %d, longs, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n' %(bpv*2, next_primitive - bpv, bpv, next_primitive, bpv, next_primitive, next_primitive - num_iters * bpv))
- writeRemainder(bpv, next_primitive, remaining_bits, o, 128/num_values_per_long - o, f)
- f.write(' }\n')
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' static final long[] MASKS%d = new long[%d];\n' %(primitive_size, primitive_size))
- f.write('\n')
- f.write(' static {\n')
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' for (int i = 0; i < %d; ++i) {\n' %primitive_size)
- f.write(' MASKS%d[i] = mask%d(i);\n' %(primitive_size, primitive_size))
- f.write(' }\n')
- f.write(' }')
- f.write("""
+ num_values_per_long = 64 / next_primitive
+ remaining_bits = next_primitive % bpv
+ num_iters = (next_primitive - 1) // bpv
+ o = 2 * bpv * num_iters
+ if remaining_bits == 0:
+ f.write(
+ " static void decode%d(IndexInput in, long[] longs) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " splitLongs(in, %d, longs, %d, %d, MASK%d_%d, longs, %d, MASK%d_%d);\n"
+ % (
+ bpv * 2,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ o,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ else:
+ f.write(
+ " static void decode%d(IndexInput in, long[] tmp, long[] longs) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " splitLongs(in, %d, longs, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n"
+ % (
+ bpv * 2,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ writeRemainder(
+ bpv, next_primitive, remaining_bits, o, 128 / num_values_per_long - o, f
+ )
+ f.write(" }\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(
+ " static final long[] MASKS%d = new long[%d];\n"
+ % (primitive_size, primitive_size)
+ )
+ f.write("\n")
+ f.write(" static {\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(" for (int i = 0; i < %d; ++i) {\n" % primitive_size)
+ f.write(" MASKS%d[i] = mask%d(i);\n" % (primitive_size, primitive_size))
+ f.write(" }\n")
+ f.write(" }")
+ f.write("""
// mark values in array as final longs to avoid the cost of reading array, arrays should only be
// used when the idx is a variable
""")
- for primitive_size in PRIMITIVE_SIZE:
- for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
- f.write(' static final long MASK%d_%d = MASKS%d[%d];\n' %(primitive_size, bpv, primitive_size, bpv))
-
- f.write("""
+ for primitive_size in PRIMITIVE_SIZE:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ f.write(
+ " static final long MASK%d_%d = MASKS%d[%d];\n"
+ % (primitive_size, bpv, primitive_size, bpv)
+ )
+
+ f.write("""
/** Decode 128 integers into {@code longs}. */
void decode(int bitsPerValue, IndexInput in, long[] longs) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- if next_primitive % bpv == 0:
- f.write(' decode%d(in, longs);\n' %bpv)
- else:
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- f.write(' expand%d(longs);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' expand32(longs);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- writeDecode(i, f)
- if i < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ if next_primitive % bpv == 0:
+ f.write(" decode%d(in, longs);\n" % bpv)
+ else:
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ f.write(" expand%d(longs);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" expand32(longs);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ writeDecode(i, f)
+ if i < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
+
+ f.write("}\n")
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/gen_ForUtil.py b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/gen_ForUtil.py
index 9a2b563efe8..da914ae31ea 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/gen_ForUtil.py
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/gen_ForUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForUtil.java"""
@@ -368,157 +367,207 @@ final class ForUtil {
"""
-def writeRemainderWithSIMDOptimize(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
-
- f.write(' shiftLongs(tmp, %d, tmp, 0, 0, MASK%d_%d);\n' % (iteration * num_longs, next_primitive, remaining_bits_per_long))
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- tmp_idx = 0
- b = bpv
- b -= remaining_bits_per_long
- f.write(' long l0 = tmp[tmpIdx + %d] << %d;\n' %(tmp_idx, b))
- tmp_idx += 1
- while b >= remaining_bits_per_long:
+
+def writeRemainderWithSIMDOptimize(
+ bpv, next_primitive, remaining_bits_per_long, o, num_values, f
+):
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+
+ f.write(
+ " shiftLongs(tmp, %d, tmp, 0, 0, MASK%d_%d);\n"
+ % (iteration * num_longs, next_primitive, remaining_bits_per_long)
+ )
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ tmp_idx = 0
+ b = bpv
b -= remaining_bits_per_long
- f.write(' l0 |= tmp[tmpIdx + %d] << %d;\n' %(tmp_idx, b))
+ f.write(" long l0 = tmp[tmpIdx + %d] << %d;\n" % (tmp_idx, b))
tmp_idx += 1
- f.write(' longs[longsIdx + 0] = l0;\n')
- f.write(' }\n')
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(" l0 |= tmp[tmpIdx + %d] << %d;\n" % (tmp_idx, b))
+ tmp_idx += 1
+ f.write(" longs[longsIdx + 0] = l0;\n")
+ f.write(" }\n")
def writeRemainder(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
- iteration = 1
- num_longs = bpv * num_values / remaining_bits_per_long
- while num_longs % 2 == 0 and num_values % 2 == 0:
- num_longs /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_long
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
- else:
- b -= remaining_bits
- f.write(' long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_long:
- b -= remaining_bits_per_long
- f.write(' l%d |= (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_long-b, next_primitive, b))
- remaining_bits = remaining_bits_per_long-b
- f.write(' longs[longsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n"
+ % (o, iteration, num_longs, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_long
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits_per_long, b)
+ )
+ else:
+ b -= remaining_bits
+ f.write(
+ " long l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits_per_long, b)
+ )
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_long - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_long - b
+ f.write(" longs[longsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
def writeDecode(bpv, f):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' private static void decode%d(DataInput in, long[] tmp, long[] longs) throws IOException {\n' %bpv)
- num_values_per_long = 64 / next_primitive
- if bpv == next_primitive:
- f.write(' in.readLongs(longs, 0, %d);\n' %(bpv*2))
- else:
- f.write(' in.readLongs(tmp, 0, %d);\n' %(bpv*2))
- shift = next_primitive - bpv
- o = 0
- while shift >= 0:
- f.write(' shiftLongs(tmp, %d, longs, %d, %d, MASK%d_%d);\n' %(bpv*2, o, shift, next_primitive, bpv))
- o += bpv*2
- shift -= bpv
- if shift + bpv > 0:
- if bpv % (next_primitive % bpv) == 0:
- writeRemainderWithSIMDOptimize(bpv, next_primitive, shift + bpv, o, 128/num_values_per_long - o, f)
- else:
- writeRemainder(bpv, next_primitive, shift + bpv, o, 128/num_values_per_long - o, f)
- f.write(' }\n')
-
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' private static final long[] MASKS%d = new long[%d];\n' %(primitive_size, primitive_size))
- f.write('\n')
- f.write(' static {\n')
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' for (int i = 0; i < %d; ++i) {\n' %primitive_size)
- f.write(' MASKS%d[i] = mask%d(i);\n' %(primitive_size, primitive_size))
- f.write(' }\n')
- f.write(' }')
- f.write("""
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(
+ " private static void decode%d(DataInput in, long[] tmp, long[] longs) throws IOException {\n"
+ % bpv
+ )
+ num_values_per_long = 64 / next_primitive
+ if bpv == next_primitive:
+ f.write(" in.readLongs(longs, 0, %d);\n" % (bpv * 2))
+ else:
+ f.write(" in.readLongs(tmp, 0, %d);\n" % (bpv * 2))
+ shift = next_primitive - bpv
+ o = 0
+ while shift >= 0:
+ f.write(
+ " shiftLongs(tmp, %d, longs, %d, %d, MASK%d_%d);\n"
+ % (bpv * 2, o, shift, next_primitive, bpv)
+ )
+ o += bpv * 2
+ shift -= bpv
+ if shift + bpv > 0:
+ if bpv % (next_primitive % bpv) == 0:
+ writeRemainderWithSIMDOptimize(
+ bpv,
+ next_primitive,
+ shift + bpv,
+ o,
+ 128 / num_values_per_long - o,
+ f,
+ )
+ else:
+ writeRemainder(
+ bpv,
+ next_primitive,
+ shift + bpv,
+ o,
+ 128 / num_values_per_long - o,
+ f,
+ )
+ f.write(" }\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(
+ " private static final long[] MASKS%d = new long[%d];\n"
+ % (primitive_size, primitive_size)
+ )
+ f.write("\n")
+ f.write(" static {\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(" for (int i = 0; i < %d; ++i) {\n" % primitive_size)
+ f.write(" MASKS%d[i] = mask%d(i);\n" % (primitive_size, primitive_size))
+ f.write(" }\n")
+ f.write(" }")
+ f.write("""
// mark values in array as final longs to avoid the cost of reading array, arrays should only be
// used when the idx is a variable
""")
- for primitive_size in PRIMITIVE_SIZE:
- for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
- if bpv * 2 != primitive_size or primitive_size == 8:
- f.write(' private static final long MASK%d_%d = MASKS%d[%d];\n' %(primitive_size, bpv, primitive_size, bpv))
-
- f.write("""
+ for primitive_size in PRIMITIVE_SIZE:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ if bpv * 2 != primitive_size or primitive_size == 8:
+ f.write(
+ " private static final long MASK%d_%d = MASKS%d[%d];\n"
+ % (primitive_size, bpv, primitive_size, bpv)
+ )
+
+ f.write("""
/** Decode 128 integers into {@code longs}. */
void decode(int bitsPerValue, DataInput in, long[] longs) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- f.write(' expand%d(longs);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' expand32(longs);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- f.write("""
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ f.write(" expand%d(longs);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" expand32(longs);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ f.write("""
/**
* Delta-decode 128 integers into {@code longs}.
*/
void decodeAndPrefixSum(int bitsPerValue, DataInput in, long base, long[] longs) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- f.write(' decode%d(in, tmp, longs);\n' %bpv)
- f.write(' prefixSum%d(longs, base);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
- f.write(' prefixSum32(longs, base);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- f.write('\n')
- for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- writeDecode(i, f)
- if i < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ f.write(" decode%d(in, tmp, longs);\n" % bpv)
+ f.write(" prefixSum%d(longs, base);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, in, tmp, longs);\n")
+ f.write(" prefixSum32(longs, base);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ f.write("\n")
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ writeDecode(i, f)
+ if i < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
+
+ f.write("}\n")
diff --git a/lucene/core/src/generated/checksums/regenerateForUtil.json b/lucene/core/src/generated/checksums/regenerateForUtil.json
index 424079d0982..73bb170c894 100644
--- a/lucene/core/src/generated/checksums/regenerateForUtil.json
+++ b/lucene/core/src/generated/checksums/regenerateForUtil.json
@@ -1,4 +1,4 @@
{
"lucene/core/src/java/org/apache/lucene/codecs/lucene104/ForUtil.java": "bf1168dbc05311c2e49b652391e01cb01d3f9133",
- "lucene/core/src/java/org/apache/lucene/codecs/lucene104/gen_ForUtil.py": "e87e420e633601f6f751b6777d7c094ebc66c3e7"
+ "lucene/core/src/java/org/apache/lucene/codecs/lucene104/gen_ForUtil.py": "d3c570210f69dcf2f1e242197b27c8915252e0a0"
}
diff --git a/lucene/core/src/generated/checksums/regeneratePacked64SingleBlock.json b/lucene/core/src/generated/checksums/regeneratePacked64SingleBlock.json
index 0127428f6ed..4426f1d28f8 100644
--- a/lucene/core/src/generated/checksums/regeneratePacked64SingleBlock.json
+++ b/lucene/core/src/generated/checksums/regeneratePacked64SingleBlock.json
@@ -1,6 +1,6 @@
{
- "gradle/regenerate/packed/gen_BulkOperation.py": "da9eccf0c8dd33325df5f1e76a1de74226035734",
- "gradle/regenerate/packed/gen_Packed64SingleBlock.py": "0fd2a498c3edbd195a68c2d1d686be0aed51a104",
+ "gradle/regenerate/packed/gen_BulkOperation.py": "019d9b67256558b36cbe1d7c8ac96d146fc082c3",
+ "gradle/regenerate/packed/gen_Packed64SingleBlock.py": "5a071648201ddd91bf931989c23da99dcfd052eb",
"lucene/core/src/java/org/apache/lucene/util/packed/BulkOperation.java": "35a89e4f3dd37084cc059a784bcbeb384256773b",
"lucene/core/src/java/org/apache/lucene/util/packed/BulkOperationPacked.java": "2b0d9226bae8a07ce4970bcaa9d4d0cd4fe2c79a",
"lucene/core/src/java/org/apache/lucene/util/packed/BulkOperationPacked1.java": "c483aa35c275bacc1f3a010c5b879441be502108",
diff --git a/lucene/core/src/generated/checksums/regenerateParametricDescription.json b/lucene/core/src/generated/checksums/regenerateParametricDescription.json
index 7abe6aacfb4..72c475aafbe 100644
--- a/lucene/core/src/generated/checksums/regenerateParametricDescription.json
+++ b/lucene/core/src/generated/checksums/regenerateParametricDescription.json
@@ -1,5 +1,5 @@
{
- "gradle/regenerate/moman/createLevAutomata.py": "1098cbdb05c05b9f669fc5f7edce24b553cbf719",
+ "gradle/regenerate/moman/createLevAutomata.py": "51ed96d37a469c87414983d1c92eea205c7e836a",
"lucene/core/src/java/org/apache/lucene/util/automaton/Lev1ParametricDescription.java": "efa1e1aff2c75f32d5f6b35adb5cb346c50c9fe5",
"lucene/core/src/java/org/apache/lucene/util/automaton/Lev1TParametricDescription.java": "cda745cca726a46ec66b5a4ce1c983414d075f7d",
"lucene/core/src/java/org/apache/lucene/util/automaton/Lev2ParametricDescription.java": "6e0c90405874800d65e8344b4549cd749e009e90",
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/gen_ForUtil.py b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/gen_ForUtil.py
index cacec01e0a0..f3a5098ec3f 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/gen_ForUtil.py
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/gen_ForUtil.py
@@ -15,7 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from math import gcd
"""Code generation for ForUtil.java"""
@@ -216,108 +215,159 @@ public final class ForUtil {
"""
+
def writeRemainder(bpv, next_primitive, remaining_bits_per_int, o, num_values, f):
- iteration = 1
- num_ints = bpv * num_values / remaining_bits_per_int
- while num_ints % 2 == 0 and num_values % 2 == 0:
- num_ints /= 2
- num_values /= 2
- iteration *= 2
- f.write(' for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n' %(o, iteration, num_ints, num_values))
- i = 0
- remaining_bits = 0
- tmp_idx = 0
- for i in range(int(num_values)):
- b = bpv
- if remaining_bits == 0:
- b -= remaining_bits_per_int
- f.write(' int l%d = tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- else:
- b -= remaining_bits
- f.write(' int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
- tmp_idx += 1
- while b >= remaining_bits_per_int:
- b -= remaining_bits_per_int
- f.write(' l%d |= tmp[tmpIdx + %d] << %d;\n' %(i, tmp_idx, b))
- tmp_idx += 1
- if b > 0:
- f.write(' l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_int-b, next_primitive, b))
- remaining_bits = remaining_bits_per_int-b
- f.write(' ints[intsIdx + %d] = l%d;\n' %(i, i))
- f.write(' }\n')
+ iteration = 1
+ num_ints = bpv * num_values / remaining_bits_per_int
+ while num_ints % 2 == 0 and num_values % 2 == 0:
+ num_ints /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(
+ " for (int iter = 0, tmpIdx = 0, intsIdx = %d; iter < %d; ++iter, tmpIdx += %d, intsIdx += %d) {\n"
+ % (o, iteration, num_ints, num_values)
+ )
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(int(num_values)):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_int
+ f.write(" int l%d = tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ else:
+ b -= remaining_bits
+ f.write(
+ " int l%d = (tmp[tmpIdx + %d] & MASK%d_%d) << %d;\n"
+ % (i, tmp_idx, next_primitive, remaining_bits, b)
+ )
+ tmp_idx += 1
+ while b >= remaining_bits_per_int:
+ b -= remaining_bits_per_int
+ f.write(" l%d |= tmp[tmpIdx + %d] << %d;\n" % (i, tmp_idx, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(
+ " l%d |= (tmp[tmpIdx + %d] >>> %d) & MASK%d_%d;\n"
+ % (i, tmp_idx, remaining_bits_per_int - b, next_primitive, b)
+ )
+ remaining_bits = remaining_bits_per_int - b
+ f.write(" ints[intsIdx + %d] = l%d;\n" % (i, i))
+ f.write(" }\n")
def writeDecode(bpv, f):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- if bpv == next_primitive:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.in.readInts(ints, 0, %d);\n' %(bpv*8))
- else:
- num_values_per_int = 32 / next_primitive
- remaining_bits = next_primitive % bpv
- num_iters = (next_primitive - 1) // bpv
- o = 8 * bpv * num_iters
- if remaining_bits == 0:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n' %(bpv*8, next_primitive - bpv, bpv, next_primitive, bpv, o, next_primitive, next_primitive - num_iters * bpv))
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ if bpv == next_primitive:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(" pdu.in.readInts(ints, 0, %d);\n" % (bpv * 8))
else:
- f.write(' static void decode%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n' %bpv)
- f.write(' pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n' %(bpv*8, next_primitive - bpv, bpv, next_primitive, bpv, next_primitive, next_primitive - num_iters * bpv))
- writeRemainder(bpv, next_primitive, remaining_bits, o, 256/num_values_per_int - o, f)
- f.write(' }\n')
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' static final int[] MASKS%d = new int[%d];\n' %(primitive_size, primitive_size))
- f.write('\n')
- f.write(' static {\n')
- for primitive_size in PRIMITIVE_SIZE:
- f.write(' for (int i = 0; i < %d; ++i) {\n' %primitive_size)
- f.write(' MASKS%d[i] = mask%d(i);\n' %(primitive_size, primitive_size))
- f.write(' }\n')
- f.write(' }')
- f.write("""
+ num_values_per_int = 32 / next_primitive
+ remaining_bits = next_primitive % bpv
+ num_iters = (next_primitive - 1) // bpv
+ o = 8 * bpv * num_iters
+ if remaining_bits == 0:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, ints, %d, MASK%d_%d);\n"
+ % (
+ bpv * 8,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ o,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ else:
+ f.write(
+ " static void decode%d(PostingDecodingUtil pdu, int[] tmp, int[] ints) throws IOException {\n"
+ % bpv
+ )
+ f.write(
+ " pdu.splitInts(%d, ints, %d, %d, MASK%d_%d, tmp, 0, MASK%d_%d);\n"
+ % (
+ bpv * 8,
+ next_primitive - bpv,
+ bpv,
+ next_primitive,
+ bpv,
+ next_primitive,
+ next_primitive - num_iters * bpv,
+ )
+ )
+ writeRemainder(
+ bpv, next_primitive, remaining_bits, o, 256 / num_values_per_int - o, f
+ )
+ f.write(" }\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(
+ " static final int[] MASKS%d = new int[%d];\n"
+ % (primitive_size, primitive_size)
+ )
+ f.write("\n")
+ f.write(" static {\n")
+ for primitive_size in PRIMITIVE_SIZE:
+ f.write(" for (int i = 0; i < %d; ++i) {\n" % primitive_size)
+ f.write(" MASKS%d[i] = mask%d(i);\n" % (primitive_size, primitive_size))
+ f.write(" }\n")
+ f.write(" }")
+ f.write("""
// mark values in array as final ints to avoid the cost of reading array, arrays should only be
// used when the idx is a variable
""")
- for primitive_size in PRIMITIVE_SIZE:
- for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
- f.write(' static final int MASK%d_%d = MASKS%d[%d];\n' %(primitive_size, bpv, primitive_size, bpv))
-
- f.write("""
+ for primitive_size in PRIMITIVE_SIZE:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ f.write(
+ " static final int MASK%d_%d = MASKS%d[%d];\n"
+ % (primitive_size, bpv, primitive_size, bpv)
+ )
+
+ f.write("""
/** Decode 256 integers into {@code ints}. */
void decode(int bitsPerValue, PostingDecodingUtil pdu, int[] ints) throws IOException {
switch (bitsPerValue) {
""")
- for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- next_primitive = 32
- if bpv <= 8:
- next_primitive = 8
- elif bpv <= 16:
- next_primitive = 16
- f.write(' case %d:\n' %bpv)
- if next_primitive % bpv == 0:
- f.write(' decode%d(pdu, ints);\n' %bpv)
- else:
- f.write(' decode%d(pdu, tmp, ints);\n' %bpv)
- if next_primitive != 32:
- f.write(' expand%d(ints);\n' %next_primitive)
- f.write(' break;\n')
- f.write(' default:\n')
- f.write(' decodeSlow(bitsPerValue, pdu, tmp, ints);\n')
- f.write(' break;\n')
- f.write(' }\n')
- f.write(' }\n')
-
- for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
- writeDecode(i, f)
- if i < MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write('\n')
-
- f.write('}\n')
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(" case %d:\n" % bpv)
+ if next_primitive % bpv == 0:
+ f.write(" decode%d(pdu, ints);\n" % bpv)
+ else:
+ f.write(" decode%d(pdu, tmp, ints);\n" % bpv)
+ if next_primitive != 32:
+ f.write(" expand%d(ints);\n" % next_primitive)
+ f.write(" break;\n")
+ f.write(" default:\n")
+ f.write(" decodeSlow(bitsPerValue, pdu, tmp, ints);\n")
+ f.write(" break;\n")
+ f.write(" }\n")
+ f.write(" }\n")
+
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE + 1):
+ writeDecode(i, f)
+ if i < MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write("\n")
+
+ f.write("}\n")
diff --git a/lucene/core/src/java/org/apache/lucene/util/automaton/UTF32ToUTF8.py b/lucene/core/src/java/org/apache/lucene/util/automaton/UTF32ToUTF8.py
index d8ae4b93e43..d789ca5d427 100644
--- a/lucene/core/src/java/org/apache/lucene/util/automaton/UTF32ToUTF8.py
+++ b/lucene/core/src/java/org/apache/lucene/util/automaton/UTF32ToUTF8.py
@@ -29,338 +29,355 @@ MAX_UNICODE = 0x10FFFF
# MASKS[1] is bottom 2-bits
# ...
-utf8Ranges = [(0, 127),
- (128, 2047),
- (2048, 65535),
- (65536, 1114111)]
+utf8Ranges = [(0, 127), (128, 2047), (2048, 65535), (65536, 1114111)]
-typeToColor = {'startend': 'purple',
- 'start': 'blue',
- 'end': 'red'}
+typeToColor = {"startend": "purple", "start": "blue", "end": "red"}
-class FSA:
-
- def __init__(self):
- # maps fromNode -> (startUTF8, endUTF8, endNode)
- self.states = {}
- self.nodeUpto = 0
-
- def run(self, bytes):
- state = self.start
- for b in bytes:
- found = False
- oldState = state
- for label, s, e, n in self.states[state][1:]:
- if b >= s and b <= e:
- if found:
- raise RuntimeError('state %s has ambiguous output for byte %s' % (oldState, b))
- state = n
- found = True
- if not found:
- return -1
-
- return state
-
- def addEdge(self, n1, n2, v1, v2, label):
- """
- Adds edge from n1-n2, utf8 byte range v1-v2.
- """
- assert n1 in self.states
- assert type(v1) is types.IntType
- assert type(v2) is types.IntType
- self.states[n1].append((label, v1, v2, n2))
-
- def addNode(self, label=None):
- try:
- self.states[self.nodeUpto] = [label]
- return self.nodeUpto
- finally:
- self.nodeUpto += 1
-
- def toDOT(self, label):
- __l = []
- w = __l.append
- endNode = startNode = None
- for id, details in self.states.items():
- name = details[0]
- if name == 'end':
- endNode = id
- elif name == 'start':
- startNode = id
-
- w('digraph %s {' % label)
- w(' rankdir=LR;')
- w(' size="8,5";')
- w(' node [color=white label=""]; Ns;')
-
- w(' node [color=black];')
- w(' node [shape=doublecircle, label=""]; N%s [label="%s"];' % (endNode, endNode))
- w(' node [shape=circle];')
-
- w(' N%s [label="%s"];' % (startNode, startNode))
- w(' Ns -> N%s;' % startNode)
- for id, details in self.states.items():
- edges = details[1:]
- w(' N%s [label="%s"];' % (id, id))
- for type, s, e, dest in edges:
- c = typeToColor.get(type, 'black')
- if type == 'all*':
- # special case -- matches any utf8 byte at this point
- label = '*'
- elif s == e:
- label = '%s' % binary(s)
- else:
- label = '%s-%s' % (binary(s), binary(e))
- w(' N%s -> N%s [label="%s" color="%s"];' % (id, dest, label, c))
- if name == 'end':
- endNode = id
- elif name == 'start':
- startNode = id
- w('}')
- return '\n'.join(__l)
- def toPNG(self, label, pngOut):
- open('tmp.dot', 'wb').write(self.toDOT(label))
- if os.system('dot -Tpng tmp.dot -o %s' % pngOut):
- raise RuntimeException('dot failed')
+class FSA:
+ def __init__(self):
+ # maps fromNode -> (startUTF8, endUTF8, endNode)
+ self.states = {}
+ self.nodeUpto = 0
+
+ def run(self, bytes):
+ state = self.start
+ for b in bytes:
+ found = False
+ oldState = state
+ for label, s, e, n in self.states[state][1:]:
+ if b >= s and b <= e:
+ if found:
+ raise RuntimeError(
+ "state %s has ambiguous output for byte %s" % (oldState, b)
+ )
+ state = n
+ found = True
+ if not found:
+ return -1
+
+ return state
+
+ def addEdge(self, n1, n2, v1, v2, label):
+ """
+ Adds edge from n1-n2, utf8 byte range v1-v2.
+ """
+ assert n1 in self.states
+ assert type(v1) is types.IntType
+ assert type(v2) is types.IntType
+ self.states[n1].append((label, v1, v2, n2))
+
+ def addNode(self, label=None):
+ try:
+ self.states[self.nodeUpto] = [label]
+ return self.nodeUpto
+ finally:
+ self.nodeUpto += 1
+
+ def toDOT(self, label):
+ __l = []
+ w = __l.append
+ endNode = startNode = None
+ for id, details in self.states.items():
+ name = details[0]
+ if name == "end":
+ endNode = id
+ elif name == "start":
+ startNode = id
+
+ w("digraph %s {" % label)
+ w(" rankdir=LR;")
+ w(' size="8,5";')
+ w(' node [color=white label=""]; Ns;')
+
+ w(" node [color=black];")
+ w(
+ ' node [shape=doublecircle, label=""]; N%s [label="%s"];'
+ % (endNode, endNode)
+ )
+ w(" node [shape=circle];")
+
+ w(' N%s [label="%s"];' % (startNode, startNode))
+ w(" Ns -> N%s;" % startNode)
+ for id, details in self.states.items():
+ edges = details[1:]
+ w(' N%s [label="%s"];' % (id, id))
+ for type, s, e, dest in edges:
+ c = typeToColor.get(type, "black")
+ if type == "all*":
+ # special case -- matches any utf8 byte at this point
+ label = "*"
+ elif s == e:
+ label = "%s" % binary(s)
+ else:
+ label = "%s-%s" % (binary(s), binary(e))
+ w(' N%s -> N%s [label="%s" color="%s"];' % (id, dest, label, c))
+ if name == "end":
+ endNode = id
+ elif name == "start":
+ startNode = id
+ w("}")
+ return "\n".join(__l)
+
+ def toPNG(self, label, pngOut):
+ open("tmp.dot", "wb").write(self.toDOT(label))
+ if os.system("dot -Tpng tmp.dot -o %s" % pngOut):
+ raise RuntimeError("dot failed")
MASKS = []
v = 2
for i in range(32):
- MASKS.append(v-1)
- v *= 2
+ MASKS.append(v - 1)
+ v *= 2
+
def binary(x):
- if x == 0:
- return '00000000'
+ if x == 0:
+ return "00000000"
- l = []
- while x > 0:
- if x & 1 == 1:
- l.append('1')
- else:
- l.append('0')
- x = x >> 1
+ binary = []
+ while x > 0:
+ if x & 1 == 1:
+ binary.append("1")
+ else:
+ binary.append("0")
+ x = x >> 1
+
+ # big endian!
+ binary.reverse()
- # big endian!
- l.reverse()
+ l2 = []
+ while len(binary) > 0:
+ s = "".join(binary[-8:])
+ if len(s) < 8:
+ s = "0" * (8 - len(s)) + s
+ l2.append(s)
+ del binary[-8:]
- l2 = []
- while len(l) > 0:
- s = ''.join(l[-8:])
- if len(s) < 8:
- s = '0'*(8-len(s)) + s
- l2.append(s)
- del l[-8:]
+ return " ".join(l2)
- return ' '.join(l2)
def getUTF8Rest(code, numBytes):
- l = []
- for i in range(numBytes):
- l.append((128 | (code & MASKS[5]), 6))
- code = code >> 6
- l.reverse()
- return tuple(l)
+ rest = []
+ for i in range(numBytes):
+ rest.append((128 | (code & MASKS[5]), 6))
+ code = code >> 6
+ rest.reverse()
+ return tuple(rest)
+
def toUTF8(code):
- # code = Unicode code point
- assert code >= 0
- assert code <= MAX_UNICODE
-
- if code < 128:
- # 0xxxxxxx
- bytes = ((code, 7),)
- elif code < 2048:
- # 110yyyxx 10xxxxxx
- byte1 = (6 << 5) | (code >> 6)
- bytes = ((byte1, 5),) + getUTF8Rest(code, 1)
- elif code < 65536:
- # 1110yyyy 10yyyyxx 10xxxxxx
- len = 3
- byte1 = (14 << 4) | (code >> 12)
- bytes = ((byte1, 4),) + getUTF8Rest(code, 2)
- else:
- # 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
- len = 4
- byte1 = (30 << 3) | (code >> 18)
- bytes = ((byte1, 3),) + getUTF8Rest(code, 3)
-
- return bytes
+ # code = Unicode code point
+ assert code >= 0
+ assert code <= MAX_UNICODE
+
+ if code < 128:
+ # 0xxxxxxx
+ bytes = ((code, 7),)
+ elif code < 2048:
+ # 110yyyxx 10xxxxxx
+ byte1 = (6 << 5) | (code >> 6)
+ bytes = ((byte1, 5),) + getUTF8Rest(code, 1)
+ elif code < 65536:
+ # 1110yyyy 10yyyyxx 10xxxxxx
+ byte1 = (14 << 4) | (code >> 12)
+ bytes = ((byte1, 4),) + getUTF8Rest(code, 2)
+ else:
+ # 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
+ byte1 = (30 << 3) | (code >> 18)
+ bytes = ((byte1, 3),) + getUTF8Rest(code, 3)
+
+ return bytes
+
def all(fsa, startNode, endNode, startCode, endCode, left):
- if len(left) == 0:
- fsa.addEdge(startNode, endNode, startCode, endCode, 'all')
- else:
- lastN = fsa.addNode()
- fsa.addEdge(startNode, lastN, startCode, endCode, 'all')
- while len(left) > 1:
- n = fsa.addNode()
- fsa.addEdge(lastN, n, 128, 191, 'all*')
- left = left[1:]
- lastN = n
- fsa.addEdge(lastN, endNode, 128, 191, 'all*')
+ if len(left) == 0:
+ fsa.addEdge(startNode, endNode, startCode, endCode, "all")
+ else:
+ lastN = fsa.addNode()
+ fsa.addEdge(startNode, lastN, startCode, endCode, "all")
+ while len(left) > 1:
+ n = fsa.addNode()
+ fsa.addEdge(lastN, n, 128, 191, "all*")
+ left = left[1:]
+ lastN = n
+ fsa.addEdge(lastN, endNode, 128, 191, "all*")
+
def start(fsa, startNode, endNode, utf8, doAll):
- if len(utf8) == 1:
- fsa.addEdge(startNode, endNode, utf8[0][0], utf8[0][0] | MASKS[utf8[0][1]-1], 'start')
- else:
- n = fsa.addNode()
- fsa.addEdge(startNode, n, utf8[0][0], utf8[0][0], 'start')
- start(fsa, n, endNode, utf8[1:], True)
- end = utf8[0][0] | MASKS[utf8[0][1]-1]
- if doAll and utf8[0][0] != end:
- all(fsa, startNode, endNode, utf8[0][0]+1, end, utf8[1:])
+ if len(utf8) == 1:
+ fsa.addEdge(
+ startNode, endNode, utf8[0][0], utf8[0][0] | MASKS[utf8[0][1] - 1], "start"
+ )
+ else:
+ n = fsa.addNode()
+ fsa.addEdge(startNode, n, utf8[0][0], utf8[0][0], "start")
+ start(fsa, n, endNode, utf8[1:], True)
+ end = utf8[0][0] | MASKS[utf8[0][1] - 1]
+ if doAll and utf8[0][0] != end:
+ all(fsa, startNode, endNode, utf8[0][0] + 1, end, utf8[1:])
+
def end(fsa, startNode, endNode, utf8, doAll):
- if len(utf8) == 1:
- fsa.addEdge(startNode, endNode, utf8[0][0] & ~MASKS[utf8[0][1]-1], utf8[0][0], 'end')
- else:
- if utf8[0][1] == 5:
- # special case -- avoid created unused edges (utf8 doesn't accept certain byte sequences):
- start = 194
- else:
- start = utf8[0][0] & (~MASKS[utf8[0][1]-1])
- if doAll and utf8[0][0] != start:
- all(fsa, startNode, endNode, start, utf8[0][0]-1, utf8[1:])
- n = fsa.addNode()
- fsa.addEdge(startNode, n, utf8[0][0], utf8[0][0], 'end')
- end(fsa, n, endNode, utf8[1:], True)
-
-def build(fsa,
- startNode, endNode,
- startUTF8, endUTF8):
-
- # Break into start, middle, end:
- if startUTF8[0][0] == endUTF8[0][0]:
- # Degen case: lead with the same byte:
- if len(startUTF8) == 1 and len(endUTF8) == 1:
- fsa.addEdge(startNode, endNode, startUTF8[0][0], endUTF8[0][0], 'startend')
- return
+ if len(utf8) == 1:
+ fsa.addEdge(
+ startNode, endNode, utf8[0][0] & ~MASKS[utf8[0][1] - 1], utf8[0][0], "end"
+ )
else:
- assert len(startUTF8) != 1
- assert len(endUTF8) != 1
- n = fsa.addNode()
- # single value edge
- fsa.addEdge(startNode, n, startUTF8[0][0], startUTF8[0][0], 'single')
- build(fsa, n, endNode, startUTF8[1:], endUTF8[1:])
- elif len(startUTF8) == len(endUTF8):
- if len(startUTF8) == 1:
- fsa.addEdge(startNode, endNode, startUTF8[0][0], endUTF8[0][0], 'startend')
+ if utf8[0][1] == 5:
+ # special case -- avoid created unused edges (utf8 doesn't accept certain byte sequences):
+ start = 194
+ else:
+ start = utf8[0][0] & (~MASKS[utf8[0][1] - 1])
+ if doAll and utf8[0][0] != start:
+ all(fsa, startNode, endNode, start, utf8[0][0] - 1, utf8[1:])
+ n = fsa.addNode()
+ fsa.addEdge(startNode, n, utf8[0][0], utf8[0][0], "end")
+ end(fsa, n, endNode, utf8[1:], True)
+
+
+def build(fsa, startNode, endNode, startUTF8, endUTF8):
+ # Break into start, middle, end:
+ if startUTF8[0][0] == endUTF8[0][0]:
+ # Degen case: lead with the same byte:
+ if len(startUTF8) == 1 and len(endUTF8) == 1:
+ fsa.addEdge(startNode, endNode, startUTF8[0][0], endUTF8[0][0], "startend")
+ return
+ else:
+ assert len(startUTF8) != 1
+ assert len(endUTF8) != 1
+ n = fsa.addNode()
+ # single value edge
+ fsa.addEdge(startNode, n, startUTF8[0][0], startUTF8[0][0], "single")
+ build(fsa, n, endNode, startUTF8[1:], endUTF8[1:])
+ elif len(startUTF8) == len(endUTF8):
+ if len(startUTF8) == 1:
+ fsa.addEdge(startNode, endNode, startUTF8[0][0], endUTF8[0][0], "startend")
+ else:
+ start(fsa, startNode, endNode, startUTF8, False)
+ if endUTF8[0][0] - startUTF8[0][0] > 1:
+ all(
+ fsa,
+ startNode,
+ endNode,
+ startUTF8[0][0] + 1,
+ endUTF8[0][0] - 1,
+ startUTF8[1:],
+ )
+ end(fsa, startNode, endNode, endUTF8, False)
else:
- start(fsa, startNode, endNode, startUTF8, False)
- if endUTF8[0][0] - startUTF8[0][0] > 1:
- all(fsa, startNode, endNode, startUTF8[0][0]+1, endUTF8[0][0]-1, startUTF8[1:])
- end(fsa, startNode, endNode, endUTF8, False)
- else:
- # start
- start(fsa, startNode, endNode, startUTF8, True)
-
- # possibly middle
- byteCount = 1+len(startUTF8)
- while byteCount < len(endUTF8):
- s = toUTF8(utf8Ranges[byteCount-1][0])
- e = toUTF8(utf8Ranges[byteCount-1][1])
- all(fsa, startNode, endNode,
- s[0][0],
- e[0][0],
- s[1:])
- byteCount += 1
-
- # end
- end(fsa, startNode, endNode, endUTF8, True)
+ # start
+ start(fsa, startNode, endNode, startUTF8, True)
+
+ # possibly middle
+ byteCount = 1 + len(startUTF8)
+ while byteCount < len(endUTF8):
+ s = toUTF8(utf8Ranges[byteCount - 1][0])
+ e = toUTF8(utf8Ranges[byteCount - 1][1])
+ all(fsa, startNode, endNode, s[0][0], e[0][0], s[1:])
+ byteCount += 1
+
+ # end
+ end(fsa, startNode, endNode, endUTF8, True)
+
def main():
+ if len(sys.argv) not in (3, 4):
+ print()
+ print("Usage: python %s startUTF32 endUTF32 [testCode]" % sys.argv[0])
+ print()
+ sys.exit(1)
- if len(sys.argv) not in (3, 4):
- print
- print 'Usage: python %s startUTF32 endUTF32 [testCode]' % sys.argv[0]
- print
- sys.exit(1)
+ utf32Start = int(sys.argv[1])
+ utf32End = int(sys.argv[2])
- utf32Start = int(sys.argv[1])
- utf32End = int(sys.argv[2])
+ if utf32Start > utf32End:
+ print("ERROR: start must be <= end")
+ sys.exit(1)
- if utf32Start > utf32End:
- print 'ERROR: start must be <= end'
- sys.exit(1)
+ fsa = FSA()
+ fsa.start = fsa.addNode("start")
+ fsa.end = fsa.addNode("end")
- fsa = FSA()
- fsa.start = fsa.addNode('start')
- fsa.end = fsa.addNode('end')
+ print("s=%s" % " ".join([binary(x[0]) for x in toUTF8(utf32Start)]))
+ print("e=%s" % " ".join([binary(x[0]) for x in toUTF8(utf32End)]))
- print 's=%s' % ' '.join([binary(x[0]) for x in toUTF8(utf32Start)])
- print 'e=%s' % ' '.join([binary(x[0]) for x in toUTF8(utf32End)])
+ if len(sys.argv) == 4:
+ print(
+ "t=%s [%s]"
+ % (
+ " ".join([binary(x[0]) for x in toUTF8(int(sys.argv[3]))]),
+ " ".join(["%2x" % x[0] for x in toUTF8(int(sys.argv[3]))]),
+ )
+ )
- if len(sys.argv) == 4:
- print 't=%s [%s]' % \
- (' '.join([binary(x[0]) for x in toUTF8(int(sys.argv[3]))]),
- ' '.join(['%2x' % x[0] for x in toUTF8(int(sys.argv[3]))]))
+ build(fsa, fsa.start, fsa.end, toUTF8(utf32Start), toUTF8(utf32End))
- build(fsa, fsa.start, fsa.end,
- toUTF8(utf32Start),
- toUTF8(utf32End))
+ fsa.toPNG("test", "/tmp/outpy.png")
+ print("Saved to /tmp/outpy.png...")
- fsa.toPNG('test', '/tmp/outpy.png')
- print 'Saved to /tmp/outpy.png...'
+ test(fsa, utf32Start, utf32End, 100000)
- test(fsa, utf32Start, utf32End, 100000);
def test(fsa, utf32Start, utf32End, count):
-
- # verify correct ints are accepted
- for i in range(count):
- r = random.randint(utf32Start, utf32End)
- dest = fsa.run([tup[0] for tup in toUTF8(r)])
- if dest != fsa.end:
- print 'FAILED: valid %s (%s) is not accepted' % (r, ' '.join([binary(x[0]) for x in toUTF8(r)]))
- return False
-
- invalidRange = MAX_UNICODE - (utf32End - utf32Start + 1)
- if invalidRange >= 0:
- # verify invalid ints are not accepted
+ # verify correct ints are accepted
for i in range(count):
- r = random.randint(0, invalidRange-1)
- if r >= utf32Start:
- r = utf32End + 1 + r - utf32Start
- dest = fsa.run([tup[0] for tup in toUTF8(r)])
- if dest != -1:
- print 'FAILED: invalid %s (%s) is accepted' % (r, ' '.join([binary(x[0]) for x in toUTF8(r)]))
- return False
+ r = random.randint(utf32Start, utf32End)
+ dest = fsa.run([tup[0] for tup in toUTF8(r)])
+ if dest != fsa.end:
+ print(
+ "FAILED: valid %s (%s) is not accepted"
+ % (r, " ".join([binary(x[0]) for x in toUTF8(r)]))
+ )
+ return False
+
+ invalidRange = MAX_UNICODE - (utf32End - utf32Start + 1)
+ if invalidRange >= 0:
+ # verify invalid ints are not accepted
+ for i in range(count):
+ r = random.randint(0, invalidRange - 1)
+ if r >= utf32Start:
+ r = utf32End + 1 + r - utf32Start
+ dest = fsa.run([tup[0] for tup in toUTF8(r)])
+ if dest != -1:
+ print(
+ "FAILED: invalid %s (%s) is accepted"
+ % (r, " ".join([binary(x[0]) for x in toUTF8(r)]))
+ )
+ return False
+
+ return True
- return True
def stress():
+ print("Testing...")
- print 'Testing...'
+ iter = 0
+ while True:
+ if iter % 10 == 0:
+ print("%s..." % iter)
+ iter += 1
- iter = 0
- while True:
- if iter % 10 == 0:
- print '%s...' % iter
- iter += 1
+ v1 = random.randint(0, MAX_UNICODE)
+ v2 = random.randint(0, MAX_UNICODE)
+ if v2 < v1:
+ v1, v2 = v2, v1
- v1 = random.randint(0, MAX_UNICODE)
- v2 = random.randint(0, MAX_UNICODE)
- if v2 < v1:
- v1, v2 = v2, v1
+ utf32Start = v1
+ utf32End = v2
- utf32Start = v1
- utf32End = v2
+ fsa = FSA()
+ fsa.start = fsa.addNode("start")
+ fsa.end = fsa.addNode("end")
+ build(fsa, fsa.start, fsa.end, toUTF8(utf32Start), toUTF8(utf32End))
- fsa = FSA()
- fsa.start = fsa.addNode('start')
- fsa.end = fsa.addNode('end')
- build(fsa, fsa.start, fsa.end,
- toUTF8(utf32Start),
- toUTF8(utf32End))
-
- if not test(fsa, utf32Start, utf32End, 10000):
- print 'FAILED on utf32Start=%s utf32End=%s' % (utf32Start, utf32End)
-
-if __name__ == '__main__':
- if len(sys.argv) > 1:
- main()
- else:
- stress()
+ if not test(fsa, utf32Start, utf32End, 10000):
+ print("FAILED on utf32Start=%s utf32End=%s" % (utf32Start, utf32End))
+
+
+if __name__ == "__main__":
+ if len(sys.argv) > 1:
+ main()
+ else:
+ stress()
diff --git a/lucene/core/src/java/org/apache/lucene/util/packed/gen_BulkOperation.py b/lucene/core/src/java/org/apache/lucene/util/packed/gen_BulkOperation.py
index ddb79cb2993..b4130322b6f 100644
--- a/lucene/core/src/java/org/apache/lucene/util/packed/gen_BulkOperation.py
+++ b/lucene/core/src/java/org/apache/lucene/util/packed/gen_BulkOperation.py
@@ -15,16 +15,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-try:
- # python 3.9+
- from math import gcd
-except ImportError:
- # old python
- from fractions import gcd
-
"""Code generation for bulk operations"""
-MAX_SPECIALIZED_BITS_PER_VALUE = 24;
+MAX_SPECIALIZED_BITS_PER_VALUE = 24
PACKED_64_SINGLE_BLOCK_BPV = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 21, 32]
OUTPUT_FILE = "BulkOperation.java"
HEADER = """// This file has been automatically generated, DO NOT EDIT
@@ -92,60 +85,69 @@ FOOTER = """
}
"""
+
def is_power_of_two(n):
- return n & (n - 1) == 0
+ return n & (n - 1) == 0
+
def casts(typ):
- cast_start = "(%s) (" % typ
- cast_end = ")"
- if typ == "long":
- cast_start = ""
- cast_end = ""
- return cast_start, cast_end
+ cast_start = "(%s) (" % typ
+ cast_end = ")"
+ if typ == "long":
+ cast_start = ""
+ cast_end = ""
+ return cast_start, cast_end
+
def hexNoLSuffix(n):
- # On 32 bit Python values > (1 << 31)-1 will have L appended by hex function:
- s = hex(n)
- if s.endswith('L'):
- s = s[:-1]
- return s
+ # On 32 bit Python values > (1 << 31)-1 will have L appended by hex function:
+ s = hex(n)
+ if s.endswith("L"):
+ s = s[:-1]
+ return s
+
def masks(bits):
- if bits == 64:
- return "", ""
- return "(", " & %sL)" % (hexNoLSuffix((1 << bits) - 1))
+ if bits == 64:
+ return "", ""
+ return "(", " & %sL)" % (hexNoLSuffix((1 << bits) - 1))
+
def get_type(bits):
- if bits == 8:
- return "byte"
- elif bits == 16:
- return "short"
- elif bits == 32:
- return "int"
- elif bits == 64:
- return "long"
- else:
- assert False
+ if bits == 8:
+ return "byte"
+ elif bits == 16:
+ return "short"
+ elif bits == 32:
+ return "int"
+ elif bits == 64:
+ return "long"
+ else:
+ assert False
+
def block_value_count(bpv, bits=64):
- blocks = bpv
- values = blocks * bits // bpv
- while blocks % 2 == 0 and values % 2 == 0:
- blocks //= 2
- values //= 2
- assert values * bpv == bits * blocks, "%d values, %d blocks, %d bits per value" % (values, blocks, bpv)
- return (blocks, values)
+ blocks = bpv
+ values = blocks * bits // bpv
+ while blocks % 2 == 0 and values % 2 == 0:
+ blocks //= 2
+ values //= 2
+ assert values * bpv == bits * blocks, "%d values, %d blocks, %d bits per value" % (
+ values,
+ blocks,
+ bpv,
+ )
+ return (blocks, values)
-def packed64(bpv, f):
- mask = (1 << bpv) - 1
- f.write("\n")
- f.write(" public BulkOperationPacked%d() {\n" % bpv)
- f.write(" super(%d);\n" % bpv)
- f.write(" }\n\n")
+def packed64(bpv, f):
+ f.write("\n")
+ f.write(" public BulkOperationPacked%d() {\n" % bpv)
+ f.write(" super(%d);\n" % bpv)
+ f.write(" }\n\n")
- if bpv == 64:
- f.write(""" @Override
+ if bpv == 64:
+ f.write(""" @Override
public void decode(long[] blocks, int blocksOffset, long[] values, int valuesOffset, int iterations) {
System.arraycopy(blocks, blocksOffset, values, valuesOffset, valueCount() * iterations);
}
@@ -165,173 +167,253 @@ def packed64(bpv, f):
LongBuffer.wrap(values, valuesOffset, iterations * valueCount()).put(ByteBuffer.wrap(blocks, blocksOffset, 8 * iterations * blockCount()).asLongBuffer());
}
""")
- else:
- p64_decode(bpv, f, 32)
- p64_decode(bpv, f, 64)
+ else:
+ p64_decode(bpv, f, 32)
+ p64_decode(bpv, f, 64)
+
def p64_decode(bpv, f, bits):
- blocks, values = block_value_count(bpv)
- typ = get_type(bits)
- cast_start, cast_end = casts(typ)
-
- f.write(" @Override\n")
- f.write(" public void decode(long[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n" % typ)
- if bits < bpv:
- f.write(" throw new UnsupportedOperationException();\n")
- else:
- f.write(" for (int i = 0; i < iterations; ++i) {\n")
- mask = (1 << bpv) - 1
-
- if is_power_of_two(bpv):
- f.write(" final long block = blocks[blocksOffset++];\n")
- f.write(" for (int shift = %d; shift >= 0; shift -= %d) {\n" % (64 - bpv, bpv))
- f.write(" values[valuesOffset++] = %s(block >>> shift) & %d%s;\n" % (cast_start, mask, cast_end))
- f.write(" }\n")
+ blocks, values = block_value_count(bpv)
+ typ = get_type(bits)
+ cast_start, cast_end = casts(typ)
+
+ f.write(" @Override\n")
+ f.write(
+ " public void decode(long[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n"
+ % typ
+ )
+ if bits < bpv:
+ f.write(" throw new UnsupportedOperationException();\n")
else:
- for i in range(0, values):
- block_offset = i * bpv // 64
- bit_offset = (i * bpv) % 64
- if bit_offset == 0:
- # start of block
- f.write(" final long block%d = blocks[blocksOffset++];\n" % block_offset);
- f.write(" values[valuesOffset++] = %sblock%d >>> %d%s;\n" % (cast_start, block_offset, 64 - bpv, cast_end))
- elif bit_offset + bpv == 64:
- # end of block
- f.write(" values[valuesOffset++] = %sblock%d & %dL%s;\n" % (cast_start, block_offset, mask, cast_end))
- elif bit_offset + bpv < 64:
- # middle of block
- f.write(" values[valuesOffset++] = %s(block%d >>> %d) & %dL%s;\n" % (cast_start, block_offset, 64 - bit_offset - bpv, mask, cast_end))
+ f.write(" for (int i = 0; i < iterations; ++i) {\n")
+ mask = (1 << bpv) - 1
+
+ if is_power_of_two(bpv):
+ f.write(" final long block = blocks[blocksOffset++];\n")
+ f.write(
+ " for (int shift = %d; shift >= 0; shift -= %d) {\n"
+ % (64 - bpv, bpv)
+ )
+ f.write(
+ " values[valuesOffset++] = %s(block >>> shift) & %d%s;\n"
+ % (cast_start, mask, cast_end)
+ )
+ f.write(" }\n")
else:
- # value spans across 2 blocks
- mask1 = (1 << (64 - bit_offset)) - 1
- shift1 = bit_offset + bpv - 64
- shift2 = 64 - shift1
- f.write(" final long block%d = blocks[blocksOffset++];\n" % (block_offset + 1));
- f.write(" values[valuesOffset++] = %s((block%d & %dL) << %d) | (block%d >>> %d)%s;\n" % (cast_start, block_offset, mask1, shift1, block_offset + 1, shift2, cast_end))
- f.write(" }\n")
- f.write(" }\n\n")
-
- byte_blocks, byte_values = block_value_count(bpv, 8)
-
- f.write(" @Override\n")
- f.write(" public void decode(byte[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n" % typ)
- if bits < bpv:
- f.write(" throw new UnsupportedOperationException();\n")
- else:
- if is_power_of_two(bpv) and bpv < 8:
- f.write(" for (int j = 0; j < iterations; ++j) {\n")
- f.write(" final byte block = blocks[blocksOffset++];\n")
- for shift in range(8 - bpv, 0, -bpv):
- f.write(" values[valuesOffset++] = (block >>> %d) & %d;\n" % (shift, mask))
- f.write(" values[valuesOffset++] = block & %d;\n" % mask)
- f.write(" }\n")
- elif bpv == 8:
- f.write(" for (int j = 0; j < iterations; ++j) {\n")
- f.write(" values[valuesOffset++] = blocks[blocksOffset++] & 0xFF;\n")
- f.write(" }\n")
- elif is_power_of_two(bpv) and bpv > 8:
- f.write(" for (int j = 0; j < iterations; ++j) {\n")
- m = bits <= 32 and "0xFF" or "0xFFL"
- f.write(" values[valuesOffset++] =")
- for i in range(bpv // 8 - 1):
- f.write(" ((blocks[blocksOffset++] & %s) << %d) |" % (m, bpv - 8))
- f.write(" (blocks[blocksOffset++] & %s);\n" % m)
- f.write(" }\n")
+ for i in range(0, values):
+ block_offset = i * bpv // 64
+ bit_offset = (i * bpv) % 64
+ if bit_offset == 0:
+ # start of block
+ f.write(
+ " final long block%d = blocks[blocksOffset++];\n"
+ % block_offset
+ )
+ f.write(
+ " values[valuesOffset++] = %sblock%d >>> %d%s;\n"
+ % (cast_start, block_offset, 64 - bpv, cast_end)
+ )
+ elif bit_offset + bpv == 64:
+ # end of block
+ f.write(
+ " values[valuesOffset++] = %sblock%d & %dL%s;\n"
+ % (cast_start, block_offset, mask, cast_end)
+ )
+ elif bit_offset + bpv < 64:
+ # middle of block
+ f.write(
+ " values[valuesOffset++] = %s(block%d >>> %d) & %dL%s;\n"
+ % (
+ cast_start,
+ block_offset,
+ 64 - bit_offset - bpv,
+ mask,
+ cast_end,
+ )
+ )
+ else:
+ # value spans across 2 blocks
+ mask1 = (1 << (64 - bit_offset)) - 1
+ shift1 = bit_offset + bpv - 64
+ shift2 = 64 - shift1
+ f.write(
+ " final long block%d = blocks[blocksOffset++];\n"
+ % (block_offset + 1)
+ )
+ f.write(
+ " values[valuesOffset++] = %s((block%d & %dL) << %d) | (block%d >>> %d)%s;\n"
+ % (
+ cast_start,
+ block_offset,
+ mask1,
+ shift1,
+ block_offset + 1,
+ shift2,
+ cast_end,
+ )
+ )
+ f.write(" }\n")
+ f.write(" }\n\n")
+
+ byte_blocks, byte_values = block_value_count(bpv, 8)
+
+ f.write(" @Override\n")
+ f.write(
+ " public void decode(byte[] blocks, int blocksOffset, %s[] values, int valuesOffset, int iterations) {\n"
+ % typ
+ )
+ if bits < bpv:
+ f.write(" throw new UnsupportedOperationException();\n")
else:
- f.write(" for (int i = 0; i < iterations; ++i) {\n")
- for i in range(0, byte_values):
- byte_start = i * bpv // 8
- bit_start = (i * bpv) % 8
- byte_end = ((i + 1) * bpv - 1) // 8
- bit_end = ((i + 1) * bpv - 1) % 8
- shift = lambda b: 8 * (byte_end - b - 1) + 1 + bit_end
- if bit_start == 0:
- f.write(" final %s byte%d = blocks[blocksOffset++] & 0xFF;\n" % (typ, byte_start))
- for b in range(byte_start + 1, byte_end + 1):
- f.write(" final %s byte%d = blocks[blocksOffset++] & 0xFF;\n" % (typ, b))
- f.write(" values[valuesOffset++] =")
- if byte_start == byte_end:
- if bit_start == 0:
- if bit_end == 7:
- f.write(" byte%d" % byte_start)
- else:
- f.write(" byte%d >>> %d" % (byte_start, 7 - bit_end))
- else:
- if bit_end == 7:
- f.write(" byte%d & %d" % (byte_start, 2 ** (8 - bit_start) - 1))
- else:
- f.write(" (byte%d >>> %d) & %d" % (byte_start, 7 - bit_end, 2 ** (bit_end - bit_start + 1) - 1))
+ if is_power_of_two(bpv) and bpv < 8:
+ f.write(" for (int j = 0; j < iterations; ++j) {\n")
+ f.write(" final byte block = blocks[blocksOffset++];\n")
+ for shift in range(8 - bpv, 0, -bpv):
+ f.write(
+ " values[valuesOffset++] = (block >>> %d) & %d;\n"
+ % (shift, mask)
+ )
+ f.write(" values[valuesOffset++] = block & %d;\n" % mask)
+ f.write(" }\n")
+ elif bpv == 8:
+ f.write(" for (int j = 0; j < iterations; ++j) {\n")
+ f.write(" values[valuesOffset++] = blocks[blocksOffset++] & 0xFF;\n")
+ f.write(" }\n")
+ elif is_power_of_two(bpv) and bpv > 8:
+ f.write(" for (int j = 0; j < iterations; ++j) {\n")
+ m = bits <= 32 and "0xFF" or "0xFFL"
+ f.write(" values[valuesOffset++] =")
+ for i in range(bpv // 8 - 1):
+ f.write(" ((blocks[blocksOffset++] & %s) << %d) |" % (m, bpv - 8))
+ f.write(" (blocks[blocksOffset++] & %s);\n" % m)
+ f.write(" }\n")
else:
- if bit_start == 0:
- f.write(" (byte%d << %d)" % (byte_start, shift(byte_start)))
- else:
- f.write(" ((byte%d & %d) << %d)" % (byte_start, 2 ** (8 - bit_start) - 1, shift(byte_start)))
- for b in range(byte_start + 1, byte_end):
- f.write(" | (byte%d << %d)" % (b, shift(b)))
- if bit_end == 7:
- f.write(" | byte%d" % byte_end)
- else:
- f.write(" | (byte%d >>> %d)" % (byte_end, 7 - bit_end))
- f.write(";\n")
- f.write(" }\n")
- f.write(" }\n\n")
-
-if __name__ == '__main__':
- f = open(OUTPUT_FILE, 'w')
- f.write(HEADER)
- f.write('\n')
- f.write('''/**
+ f.write(" for (int i = 0; i < iterations; ++i) {\n")
+ for i in range(0, byte_values):
+ byte_start = i * bpv // 8
+ bit_start = (i * bpv) % 8
+ byte_end = ((i + 1) * bpv - 1) // 8
+ bit_end = ((i + 1) * bpv - 1) % 8
+
+ def shift(b):
+ return 8 * (byte_end - b - 1) + 1 + bit_end
+
+ if bit_start == 0:
+ f.write(
+ " final %s byte%d = blocks[blocksOffset++] & 0xFF;\n"
+ % (typ, byte_start)
+ )
+ for b in range(byte_start + 1, byte_end + 1):
+ f.write(
+ " final %s byte%d = blocks[blocksOffset++] & 0xFF;\n"
+ % (typ, b)
+ )
+ f.write(" values[valuesOffset++] =")
+ if byte_start == byte_end:
+ if bit_start == 0:
+ if bit_end == 7:
+ f.write(" byte%d" % byte_start)
+ else:
+ f.write(" byte%d >>> %d" % (byte_start, 7 - bit_end))
+ else:
+ if bit_end == 7:
+ f.write(
+ " byte%d & %d" % (byte_start, 2 ** (8 - bit_start) - 1)
+ )
+ else:
+ f.write(
+ " (byte%d >>> %d) & %d"
+ % (
+ byte_start,
+ 7 - bit_end,
+ 2 ** (bit_end - bit_start + 1) - 1,
+ )
+ )
+ else:
+ if bit_start == 0:
+ f.write(" (byte%d << %d)" % (byte_start, shift(byte_start)))
+ else:
+ f.write(
+ " ((byte%d & %d) << %d)"
+ % (byte_start, 2 ** (8 - bit_start) - 1, shift(byte_start))
+ )
+ for b in range(byte_start + 1, byte_end):
+ f.write(" | (byte%d << %d)" % (b, shift(b)))
+ if bit_end == 7:
+ f.write(" | byte%d" % byte_end)
+ else:
+ f.write(" | (byte%d >>> %d)" % (byte_end, 7 - bit_end))
+ f.write(";\n")
+ f.write(" }\n")
+ f.write(" }\n\n")
+
+
+if __name__ == "__main__":
+ f = open(OUTPUT_FILE, "w")
+ f.write(HEADER)
+ f.write("\n")
+ f.write("""/**
* Efficient sequential read/write of packed integers.
- */\n''')
-
- f.write('abstract class BulkOperation implements PackedInts.Decoder, PackedInts.Encoder {\n')
- f.write(' private static final BulkOperation[] packedBulkOps = new BulkOperation[] {\n')
-
- for bpv in range(1, 65):
- if bpv > MAX_SPECIALIZED_BITS_PER_VALUE:
- f.write(' new BulkOperationPacked(%d),\n' % bpv)
- continue
- f2 = open('BulkOperationPacked%d.java' % bpv, 'w')
- f2.write(HEADER)
- if bpv == 64:
- f2.write('import java.nio.LongBuffer;\n')
- f2.write('import java.nio.ByteBuffer;\n')
- f2.write('\n')
- f2.write('''/**
+ */\n""")
+
+ f.write(
+ "abstract class BulkOperation implements PackedInts.Decoder, PackedInts.Encoder {\n"
+ )
+ f.write(
+ " private static final BulkOperation[] packedBulkOps = new BulkOperation[] {\n"
+ )
+
+ for bpv in range(1, 65):
+ if bpv > MAX_SPECIALIZED_BITS_PER_VALUE:
+ f.write(" new BulkOperationPacked(%d),\n" % bpv)
+ continue
+ f2 = open("BulkOperationPacked%d.java" % bpv, "w")
+ f2.write(HEADER)
+ if bpv == 64:
+ f2.write("import java.nio.LongBuffer;\n")
+ f2.write("import java.nio.ByteBuffer;\n")
+ f2.write("\n")
+ f2.write("""/**
* Efficient sequential read/write of packed integers.
- */\n''')
- f2.write('final class BulkOperationPacked%d extends BulkOperationPacked {\n' % bpv)
- packed64(bpv, f2)
- f2.write('}\n')
- f2.close()
- f.write(' new BulkOperationPacked%d(),\n' % bpv)
-
- f.write(' };\n')
- f.write('\n')
-
- f.write(' // NOTE: this is sparse (some entries are null):\n')
- f.write(' private static final BulkOperation[] packedSingleBlockBulkOps = new BulkOperation[] {\n')
- for bpv in range(1, max(PACKED_64_SINGLE_BLOCK_BPV) + 1):
- if bpv in PACKED_64_SINGLE_BLOCK_BPV:
- f.write(' new BulkOperationPackedSingleBlock(%d),\n' % bpv)
- else:
- f.write(' null,\n')
- f.write(' };\n')
- f.write('\n')
-
- f.write("\n")
- f.write(" public static BulkOperation of(PackedInts.Format format, int bitsPerValue) {\n")
- f.write(" switch (format) {\n")
-
- f.write(" case PACKED:\n")
- f.write(" assert packedBulkOps[bitsPerValue - 1] != null;\n")
- f.write(" return packedBulkOps[bitsPerValue - 1];\n")
- f.write(" case PACKED_SINGLE_BLOCK:\n")
- f.write(" assert packedSingleBlockBulkOps[bitsPerValue - 1] != null;\n")
- f.write(" return packedSingleBlockBulkOps[bitsPerValue - 1];\n")
- f.write(" default:\n")
- f.write(" throw new AssertionError();\n")
- f.write(" }\n")
- f.write(" }\n")
- f.write(FOOTER)
- f.close()
+ */\n""")
+ f2.write(
+ "final class BulkOperationPacked%d extends BulkOperationPacked {\n" % bpv
+ )
+ packed64(bpv, f2)
+ f2.write("}\n")
+ f2.close()
+ f.write(" new BulkOperationPacked%d(),\n" % bpv)
+
+ f.write(" };\n")
+ f.write("\n")
+
+ f.write(" // NOTE: this is sparse (some entries are null):\n")
+ f.write(
+ " private static final BulkOperation[] packedSingleBlockBulkOps = new BulkOperation[] {\n"
+ )
+ for bpv in range(1, max(PACKED_64_SINGLE_BLOCK_BPV) + 1):
+ if bpv in PACKED_64_SINGLE_BLOCK_BPV:
+ f.write(" new BulkOperationPackedSingleBlock(%d),\n" % bpv)
+ else:
+ f.write(" null,\n")
+ f.write(" };\n")
+ f.write("\n")
+
+ f.write("\n")
+ f.write(
+ " public static BulkOperation of(PackedInts.Format format, int bitsPerValue) {\n"
+ )
+ f.write(" switch (format) {\n")
+
+ f.write(" case PACKED:\n")
+ f.write(" assert packedBulkOps[bitsPerValue - 1] != null;\n")
+ f.write(" return packedBulkOps[bitsPerValue - 1];\n")
+ f.write(" case PACKED_SINGLE_BLOCK:\n")
+ f.write(" assert packedSingleBlockBulkOps[bitsPerValue - 1] != null;\n")
+ f.write(" return packedSingleBlockBulkOps[bitsPerValue - 1];\n")
+ f.write(" default:\n")
+ f.write(" throw new AssertionError();\n")
+ f.write(" }\n")
+ f.write(" }\n")
+ f.write(FOOTER)
+ f.close()
diff --git a/lucene/core/src/java/org/apache/lucene/util/packed/gen_Packed64SingleBlock.py b/lucene/core/src/java/org/apache/lucene/util/packed/gen_Packed64SingleBlock.py
index 808935cb952..bb19a940b0b 100644
--- a/lucene/core/src/java/org/apache/lucene/util/packed/gen_Packed64SingleBlock.py
+++ b/lucene/core/src/java/org/apache/lucene/util/packed/gen_Packed64SingleBlock.py
@@ -222,59 +222,69 @@ abstract class Packed64SingleBlock extends PackedInts.MutableImpl {
FOOTER = "}"
-if __name__ == '__main__':
-
- f = open("Packed64SingleBlock.java", 'w')
- f.write(HEADER)
- f.write(" public static Packed64SingleBlock create(int valueCount, int bitsPerValue) {\n")
- f.write(" switch (bitsPerValue) {\n")
- for bpv in SUPPORTED_BITS_PER_VALUE:
- f.write(" case %d:\n" % bpv)
- f.write(" return new Packed64SingleBlock%d(valueCount);\n" % bpv)
- f.write(" default:\n")
- f.write(" throw new IllegalArgumentException(\"Unsupported number of bits per value: \" + %d);\n" % bpv)
- f.write(" }\n")
- f.write(" }\n\n")
-
- for bpv in SUPPORTED_BITS_PER_VALUE:
- log_2 = 0
- while (1 << log_2) < bpv:
- log_2 = log_2 + 1
- if (1 << log_2) != bpv:
- log_2 = None
-
- f.write(" static class Packed64SingleBlock%d extends Packed64SingleBlock {\n\n" % bpv)
-
- f.write(" Packed64SingleBlock%d(int valueCount) {\n" % bpv)
- f.write(" super(valueCount, %d);\n" % bpv)
- f.write(" }\n\n")
-
- f.write(" @Override\n")
- f.write(" public long get(int index) {\n")
- if log_2 is not None:
- f.write(" final int o = index >>> %d;\n" % (6 - log_2))
- f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
- f.write(" final int shift = b << %d;\n" % log_2)
- else:
- f.write(" final int o = index / %d;\n" % (64 / bpv))
- f.write(" final int b = index %% %d;\n" % (64 / bpv))
- f.write(" final int shift = b * %d;\n" % bpv)
- f.write(" return (blocks[o] >>> shift) & %dL;\n" % ((1 << bpv) - 1))
- f.write(" }\n\n")
-
- f.write(" @Override\n")
- f.write(" public void set(int index, long value) {\n")
- if log_2 is not None:
- f.write(" final int o = index >>> %d;\n" % (6 - log_2))
- f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
- f.write(" final int shift = b << %d;\n" % log_2)
- else:
- f.write(" final int o = index / %d;\n" % (64 / bpv))
- f.write(" final int b = index %% %d;\n" % (64 / bpv))
- f.write(" final int shift = b * %d;\n" % bpv)
- f.write(" blocks[o] = (blocks[o] & ~(%dL << shift)) | (value << shift);\n" % ((1 << bpv) - 1))
- f.write(" }\n\n")
+if __name__ == "__main__":
+ f = open("Packed64SingleBlock.java", "w")
+ f.write(HEADER)
+ f.write(
+ " public static Packed64SingleBlock create(int valueCount, int bitsPerValue) {\n"
+ )
+ f.write(" switch (bitsPerValue) {\n")
+ for bpv in SUPPORTED_BITS_PER_VALUE:
+ f.write(" case %d:\n" % bpv)
+ f.write(" return new Packed64SingleBlock%d(valueCount);\n" % bpv)
+ f.write(" default:\n")
+ f.write(
+ ' throw new IllegalArgumentException("Unsupported number of bits per value: " + %d);\n'
+ % bpv
+ )
+ f.write(" }\n")
f.write(" }\n\n")
- f.write(FOOTER)
- f.close()
+ for bpv in SUPPORTED_BITS_PER_VALUE:
+ log_2 = 0
+ while (1 << log_2) < bpv:
+ log_2 = log_2 + 1
+ if (1 << log_2) != bpv:
+ log_2 = None
+
+ f.write(
+ " static class Packed64SingleBlock%d extends Packed64SingleBlock {\n\n"
+ % bpv
+ )
+
+ f.write(" Packed64SingleBlock%d(int valueCount) {\n" % bpv)
+ f.write(" super(valueCount, %d);\n" % bpv)
+ f.write(" }\n\n")
+
+ f.write(" @Override\n")
+ f.write(" public long get(int index) {\n")
+ if log_2 is not None:
+ f.write(" final int o = index >>> %d;\n" % (6 - log_2))
+ f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
+ f.write(" final int shift = b << %d;\n" % log_2)
+ else:
+ f.write(" final int o = index / %d;\n" % (64 / bpv))
+ f.write(" final int b = index %% %d;\n" % (64 / bpv))
+ f.write(" final int shift = b * %d;\n" % bpv)
+ f.write(" return (blocks[o] >>> shift) & %dL;\n" % ((1 << bpv) - 1))
+ f.write(" }\n\n")
+
+ f.write(" @Override\n")
+ f.write(" public void set(int index, long value) {\n")
+ if log_2 is not None:
+ f.write(" final int o = index >>> %d;\n" % (6 - log_2))
+ f.write(" final int b = index & %d;\n" % ((1 << (6 - log_2)) - 1))
+ f.write(" final int shift = b << %d;\n" % log_2)
+ else:
+ f.write(" final int o = index / %d;\n" % (64 / bpv))
+ f.write(" final int b = index %% %d;\n" % (64 / bpv))
+ f.write(" final int shift = b * %d;\n" % bpv)
+ f.write(
+ " blocks[o] = (blocks[o] & ~(%dL << shift)) | (value << shift);\n"
+ % ((1 << bpv) - 1)
+ )
+ f.write(" }\n\n")
+ f.write(" }\n\n")
+
+ f.write(FOOTER)
+ f.close()
diff --git a/lucene/core/src/test/org/apache/lucene/util/makeEuroparlLineFile.py b/lucene/core/src/test/org/apache/lucene/util/makeEuroparlLineFile.py
index b8718e85ec3..41dc3c5b89c 100644
--- a/lucene/core/src/test/org/apache/lucene/util/makeEuroparlLineFile.py
+++ b/lucene/core/src/test/org/apache/lucene/util/makeEuroparlLineFile.py
@@ -20,101 +20,102 @@ import tarfile
import re
try:
- sys.argv.remove('-verbose')
- VERBOSE = True
+ sys.argv.remove("-verbose")
+ VERBOSE = True
except ValueError:
- VERBOSE = False
+ VERBOSE = False
try:
- sys.argv.remove('-docPerParagraph')
- docPerParagraph = True
+ sys.argv.remove("-docPerParagraph")
+ docPerParagraph = True
except ValueError:
- docPerParagraph = False
+ docPerParagraph = False
-reChapterOnly = re.compile('^<CHAPTER ID=.*?>$')
-reTagOnly = re.compile('^<.*?>$')
-reNumberOnly = re.compile(r'^\d+\.?$')
+reChapterOnly = re.compile("^<CHAPTER ID=.*?>$")
+reTagOnly = re.compile("^<.*?>$")
+reNumberOnly = re.compile(r"^\d+\.?$")
maxDoc = 0
didEnglish = False
+
def write(date, title, pending, fOut):
- global maxDoc
- body = ' '.join(pending).replace('\t', ' ').strip()
- if len(body) > 0:
- line = '%s\t%s\t%s\n' % (title, date, body)
- fOut.write(line)
- maxDoc += 1
- del pending[:]
- if VERBOSE:
- print len(body)
+ global maxDoc
+ body = " ".join(pending).replace("\t", " ").strip()
+ if len(body) > 0:
+ line = "%s\t%s\t%s\n" % (title, date, body)
+ fOut.write(line)
+ maxDoc += 1
+ del pending[:]
+ if VERBOSE:
+ print(len(body))
+
def processTar(fileName, fOut):
+ global didEnglish
+
+ t = tarfile.open(fileName, "r:gz")
+ for ti in t:
+ if ti.isfile() and (not didEnglish or ti.name.find("/en/") == -1):
+ tup = ti.name.split("/")
+ _lang = tup[1]
+ year = int(tup[2][3:5])
+ if year < 20:
+ year += 2000
+ else:
+ year += 1900
+
+ month = int(tup[2][6:8])
+ day = int(tup[2][9:11])
+ date = datetime.date(year=year, month=month, day=day)
- global didEnglish
-
- t = tarfile.open(fileName, 'r:gz')
- for ti in t:
- if ti.isfile() and (not didEnglish or ti.name.find('/en/') == -1):
-
- tup = ti.name.split('/')
- lang = tup[1]
- year = int(tup[2][3:5])
- if year < 20:
- year += 2000
- else:
- year += 1900
-
- month = int(tup[2][6:8])
- day = int(tup[2][9:11])
- date = datetime.date(year=year, month=month, day=day)
-
- if VERBOSE:
- print
- print '%s: %s' % (ti.name, date)
- nextIsTitle = False
- title = None
- pending = []
- for line in t.extractfile(ti).readlines():
- line = line.strip()
- if reChapterOnly.match(line) is not None:
- if title is not None:
- write(date, title, pending, fOut)
- nextIsTitle = True
- continue
- if nextIsTitle:
- if not reNumberOnly.match(line) and not reTagOnly.match(line):
- title = line
- nextIsTitle = False
if VERBOSE:
- print ' title %s' % line
- continue
- if line.lower() == '<p>':
- if docPerParagraph:
- write(date, title, pending, fOut)
- else:
- pending.append('PARSEP')
- elif not reTagOnly.match(line):
- pending.append(line)
- if title is not None and len(pending) > 0:
- write(date, title, pending, fOut)
-
- didEnglish = True
+ print()
+ print("%s: %s" % (ti.name, date))
+ nextIsTitle = False
+ title = None
+ pending = []
+ for line in t.extractfile(ti).readlines():
+ line = line.strip()
+ if reChapterOnly.match(line) is not None:
+ if title is not None:
+ write(date, title, pending, fOut)
+ nextIsTitle = True
+ continue
+ if nextIsTitle:
+ if not reNumberOnly.match(line) and not reTagOnly.match(line):
+ title = line
+ nextIsTitle = False
+ if VERBOSE:
+ print(" title %s" % line)
+ continue
+ if line.lower() == "<p>":
+ if docPerParagraph:
+ write(date, title, pending, fOut)
+ else:
+ pending.append("PARSEP")
+ elif not reTagOnly.match(line):
+ pending.append(line)
+ if title is not None and len(pending) > 0:
+ write(date, title, pending, fOut)
+
+ didEnglish = True
+
# '/x/lucene/data/europarl/all.lines.txt'
dirIn = sys.argv[1]
fileOut = sys.argv[2]
-fOut = open(fileOut, 'wb')
+fOut = open(fileOut, "wb")
-for fileName in glob.glob('%s/??-??.tgz' % dirIn):
- if fileName.endswith('.tgz'):
- print 'process %s; %d docs so far...' % (fileName, maxDoc)
- processTar(fileName, fOut)
+for fileName in glob.glob("%s/??-??.tgz" % dirIn):
+ if fileName.endswith(".tgz"):
+ print("process %s; %d docs so far..." % (fileName, maxDoc))
+ processTar(fileName, fOut)
-print 'TOTAL: %s' % maxDoc
+print("TOTAL: %s" % maxDoc)
-#run something like this:
+# run something like this:
"""
# Europarl V5 makes 76,917 docs, avg 38.6 KB per