magibney commented on a change in pull request #892: LUCENE-8972: Add 
ICUTransformCharFilter, to support pre-tokenizer ICU text transformation
URL: https://github.com/apache/lucene-solr/pull/892#discussion_r341740602
 
 

 ##########
 File path: 
lucene/analysis/icu/src/java/org/apache/lucene/analysis/icu/ICUTransformCharFilter.java
 ##########
 @@ -0,0 +1,384 @@
+/*
+ * 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.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.lucene.analysis.icu;
+
+import java.io.IOException;
+import java.io.Reader;
+
+import com.ibm.icu.text.ReplaceableString;
+import com.ibm.icu.text.Transliterator;
+import com.ibm.icu.text.Transliterator.Position;
+import com.ibm.icu.text.UTF16;
+
+import org.apache.lucene.analysis.CharFilter;
+import org.apache.lucene.analysis.charfilter.BaseCharFilter;
+import org.apache.lucene.util.ArrayUtil;
+
+/**
+ * A {@link CharFilter} that transforms text with ICU.
+ * <p>
+ * ICU provides text-transformation functionality via its Transliteration API.
+ * Although script conversion is its most common use, a Transliterator can
+ * actually perform a more general class of tasks. In fact, Transliterator
+ * defines a very general API which specifies only that a segment of the input
+ * text is replaced by new text. The particulars of this conversion are
+ * determined entirely by subclasses of Transliterator.
+ * </p>
+ * <p>
+ * Some useful transformations for search are built-in:
+ * <ul>
+ * <li>Conversion from Traditional to Simplified Chinese characters
+ * <li>Conversion from Hiragana to Katakana
+ * <li>Conversion from Fullwidth to Halfwidth forms.
+ * <li>Script conversions, for example Serbian Cyrillic to Latin
+ * </ul>
+ * <p>
+ * Example usage: <blockquote>stream = new ICUTransformCharFilter(reader,
+ * Transliterator.getInstance("Traditional-Simplified"));</blockquote>
+ * <br>
+ * For more details, see the <a
+ * href="http://userguide.icu-project.org/transforms/general";>ICU User
+ * Guide</a>.
+ */
+public final class ICUTransformCharFilter extends BaseCharFilter {
+
+  // Transliterator to transform the text
+  private final Transliterator transform;
+
+  // Reusable position object
+  private final Position position = new Position();
+
+  private static final int READ_BUFFER_SIZE = 1024;
+  private final char[] tmpBuffer = new char[READ_BUFFER_SIZE];
+
+  private static final int INITIAL_TRANSLITERATE_BUFFER_SIZE = 1024;
+  private final StringBuffer buffer = new 
StringBuffer(INITIAL_TRANSLITERATE_BUFFER_SIZE);
+  private final ReplaceableString replaceable = new ReplaceableString(buffer);
+
+  private static final int BUFFER_PRUNE_THRESHOLD = 1024;
+
+  private int outputCursor = 0;
+  private boolean inputFinished = false;
+  private int charCount = 0;
+  private int offsetDiffAdjust = 0;
+
+  private static final int HARD_MAX_ROLLBACK_BUFFER_CAPACITY = 
Integer.highestOneBit(Integer.MAX_VALUE);
+  static final int DEFAULT_MAX_ROLLBACK_BUFFER_CAPACITY = 8192;
+  private final int maxRollbackBufferCapacity;
+
+  private static final int DEFAULT_INITIAL_ROLLBACK_BUFFER_CAPACITY = 4; // 
must be power of 2
+  private char[] rollbackBuffer;
+  private int rollbackBufferSize = 0;
+
+  ICUTransformCharFilter(Reader in, Transliterator transform) {
+    this(in, transform, DEFAULT_MAX_ROLLBACK_BUFFER_CAPACITY);
+  }
+
+  /**
+   * Construct new {@link ICUTransformCharFilter} with the specified {@link 
Transliterator}, backed by
+   * the specified {@link Reader}.
+   * @param in input source
+   * @param transform used to perform transliteration
+   * @param maxRollbackBufferCapacityHint used to control the maximum size to 
which this
+   * {@link ICUTransformCharFilter} will buffer and rollback partial 
transliteration of input sequences.
+   * The provided hint will be converted to an enforced limit of "the greatest 
power of 2 (excluding '1')
+   * less than or equal to the specified value". It is illegal to specify a 
negative value. There is no
+   * power of 2 greater than 
<code>Integer.highestOneBit(Integer.MAX_VALUE))</code>, so to prevent overflow, 
values
+   * in this range will resolve to an enforced limit of 
<code>Integer.highestOneBit(Integer.MAX_VALUE))</code>.
+   * Specifying "0" (or "1", in practice) disables rollback. Larger values can 
in some cases yield more accurate
+   * transliteration, at the cost of performance and resolution/accuracy of 
offset correction.
+   * This is intended primarily as a failsafe, with a relatively large default 
value of {@value ICUTransformCharFilter#DEFAULT_MAX_ROLLBACK_BUFFER_CAPACITY}.
+   * See comments "To understand the need for rollback" in private method:
+   * {@link Transliterator#filteredTransliterate(com.ibm.icu.text.Replaceable, 
Position, boolean, boolean)}
+   */
+  ICUTransformCharFilter(Reader in, Transliterator transform, int 
maxRollbackBufferCapacityHint) {
+    super(in);
+    this.transform = ICUTransformFilter.optimizeForCommonCase(transform);
+    if (maxRollbackBufferCapacityHint < 0) {
+      throw new IllegalArgumentException("It is illegal to request negative 
rollback buffer max capacity");
+    } else if (maxRollbackBufferCapacityHint >= 
HARD_MAX_ROLLBACK_BUFFER_CAPACITY) {
+      // arg is positive, so user wants the largest possible buffer capacity 
limit
+      // we know what that is (static), protecting for overflow.
+      this.maxRollbackBufferCapacity = HARD_MAX_ROLLBACK_BUFFER_CAPACITY;
+      this.rollbackBuffer = new char[DEFAULT_INITIAL_ROLLBACK_BUFFER_CAPACITY];
+    } else {
+      // greatest power of 2 (excluding "1") less than or equal to the 
specified hint
+      this.maxRollbackBufferCapacity = 
Integer.highestOneBit(maxRollbackBufferCapacityHint - 1) << 1;
+      if (this.maxRollbackBufferCapacity == 0) {
+        this.rollbackBuffer = null;
+      } else {
+        this.rollbackBuffer = new 
char[DEFAULT_INITIAL_ROLLBACK_BUFFER_CAPACITY];
+      }
+    }
+  }
+
+  /**
+   * Reads characters into a portion of an array. This method will block until 
some input is available, an I/O error
+   * occurs, or the end of the stream is reached.
+   *
+   * @param cbuf
+   *          Destination buffer
+   * @param off
+   *          Offset at which to start storing characters
+   * @param len
+   *          Maximum number of characters to read
+   * @return The number of characters read, or -1 if the end of the stream has 
been reached
+   * @throws IOException
+   *           If an I/O error occurs
+   */
+  @Override
+  public int read(char[] cbuf, int off, int len) throws IOException {
+    if (off < 0) throw new IndexOutOfBoundsException("specified negative array 
offset");
+    if (off >= cbuf.length) throw new IndexOutOfBoundsException("specified 
offset exceeds buffer length");
+    if (len <= 0) throw new IndexOutOfBoundsException("non-positive length 
specified");
+    if (len > cbuf.length - off) throw new 
IndexOutOfBoundsException("requested end array index exceeds buffer length");
+
+    // !inputFinished || output remains to be flushed
+    while (!inputFinished || position.start > outputCursor) {
+      if (position.start > outputCursor) {
+        return outputFromResultBuffer(cbuf, off, len);
+      }
+
+      int resLen = readFromIoNormalizeUptoBoundary();
+      if (resLen > 0) {
+        return outputFromResultBuffer(cbuf, off, len);
+      }
+
+      if (!readInputToBuffer()) {
 
 Review comment:
   Sorry, my last comment wasn't accounting for the fact that 
`outputFromResultBuffer(cbuf, off, len)` is not just _called_, but is the 
return value. So the potential simplification would be that the top-level entry 
point `read(char[], int, int)` method wouldn't loop at all, but rather would 
simply:
   1. read input
   2. transform as much of it as possible
   3. return output to the caller in the passed `char[]`?
   I'm not 100% on all this, but my sense is that you'd be vulnerable to buffer 
underflow on the input side unless you looped in `readInputToBuffer()` until 
reaching some arbitrary threshold of available chars (how may is enough?); and 
instead of such an arbitrary loop, you could maybe doing useful work with 
already-received input, while waiting for more input to become available on the 
input stream. And/or you'd have an increased incidence of reporting "0 chars 
read" back to the caller of `read(char[], int, int)`, forcing _them_ to loop 
(and call us repeatedly) waiting for our output.
   I took a stab at a POC reorganization of this, but it ended up being pretty 
complex itself, and helped clarify what I like about the current version (which 
I can't claim any credit for, it's based off of 
[ICUNormalizer2CharFilter](https://github.com/apache/lucene-solr/blob/cb0ff1a/lucene/analysis/icu/src/java/org/apache/lucene/analysis/icu/ICUNormalizer2CharFilter.java#L74-L96)):
 it doesn't block waiting for arbitrary amounts of data to be read or written 
-- it reads until it gets something, tries to transform it, and once it has 
something to give back, it passes it along.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org
For additional commands, e-mail: issues-h...@lucene.apache.org

Reply via email to