]> source.dussan.org Git - poi.git/commitdiff
HWPF: better fix for TextPieceTable.getCharIndex()
authorMaxim Valyanskiy <maxcom@apache.org>
Tue, 6 Jul 2010 15:45:36 +0000 (15:45 +0000)
committerMaxim Valyanskiy <maxcom@apache.org>
Tue, 6 Jul 2010 15:45:36 +0000 (15:45 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@960922 13f79535-47bb-0310-9956-ffa450edef68

src/scratchpad/src/org/apache/poi/hwpf/model/TextPieceTable.java

index fae08e03f5e903b0e347d703ecc37cfb1bb78fe5..11a5b372ee4f0029ea32df756562f1c162c23a3c 100644 (file)
@@ -242,29 +242,50 @@ public final class TextPieceTable implements CharIndexTranslator {
                return false;
        }
 
-       public int getCharIndex(int bytePos) {
-               int charCount = 0;
+    public int getCharIndex(int bytePos) {
+        int charCount = 0;
 
         for(TextPiece tp : _textPiecesFCOrder) {
                        int pieceStart = tp.getPieceDescriptor().getFilePosition();
-                       if (pieceStart >= bytePos) {
-                               break;
+
+            if (bytePos > pieceStart + tp.bytesLength()) {
+                continue;
+            }
+
+                       if (pieceStart > bytePos) {
+                               bytePos = pieceStart;
                        }
 
-                       int bytesLength = tp.bytesLength();
-                       int pieceEnd = pieceStart + bytesLength;
+            break;
+        }
+
+        for(TextPiece tp : _textPieces) {
+            int pieceStart = tp.getPieceDescriptor().getFilePosition();
 
-                       int toAdd = bytePos > pieceEnd ? bytesLength : bytesLength - (pieceEnd - bytePos);
+            int bytesLength = tp.bytesLength();
+            int pieceEnd = pieceStart + bytesLength;
 
-                       if (tp.isUnicode()) {
-                               charCount += toAdd / 2;
-                       } else {
-                               charCount += toAdd;
-                       }
-               }
+            int toAdd;
 
-               return charCount;
-       }
+            if (bytePos< pieceStart || bytePos > pieceEnd) {
+                toAdd = bytesLength;
+            } else {
+                toAdd = bytesLength - (pieceEnd - bytePos);
+            }
+
+            if (tp.isUnicode()) {
+                charCount += toAdd / 2;
+            } else {
+                charCount += toAdd;
+            }
+
+            if (bytePos>=pieceStart && bytePos<=pieceEnd) {
+                break;
+            }
+        }
+
+        return charCount;
+    }
 
     private static class FCComparator implements Comparator<TextPiece> {
         public int compare(TextPiece textPiece, TextPiece textPiece1) {