Backed out changeset 4b54755de2a7 (bug 955957) for Build Bustage on a CLOSED TREE
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Fri, 10 Jan 2014 09:30:28 +0100
changeset 178923 93f1d824e46f7f02e04291325ab2d8ed50133a69
parent 178922 06d0c43253acc4be72516bbf1b17067bc03bb2e3
child 178924 6e5d4c425fccf24c0d80b1591af5469aa087beb3
push id3343
push userffxbld
push dateMon, 17 Mar 2014 21:55:32 +0000
treeherdermozilla-beta@2f7d3415f79f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs955957
milestone29.0a1
backs out4b54755de2a7938cd68296831127af3e36bee632
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Backed out changeset 4b54755de2a7 (bug 955957) for Build Bustage on a CLOSED TREE
gfx/thebes/gfxSkipChars.cpp
gfx/thebes/gfxSkipChars.h
layout/generic/nsTextFrame.cpp
layout/generic/nsTextFrameUtils.cpp
layout/generic/nsTextFrameUtils.h
--- a/gfx/thebes/gfxSkipChars.cpp
+++ b/gfx/thebes/gfxSkipChars.cpp
@@ -1,140 +1,231 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "gfxSkipChars.h"
 
-void
-gfxSkipCharsIterator::SetOriginalOffset(int32_t aOffset)
-{
-    aOffset += mOriginalStringToSkipCharsOffset;
-    NS_ASSERTION(uint32_t(aOffset) <= mSkipChars->mCharCount,
-                 "Invalid offset");
+#include <stdlib.h>
+#include <algorithm>
+
+#define SHORTCUT_FREQUENCY 256
 
-    mOriginalStringOffset = aOffset;
-
-    uint32_t rangeCount = mSkipChars->mRanges.Length();
-    if (rangeCount == 0) {
-        mSkippedStringOffset = aOffset;
-        return;
-    }
+// Even numbered list entries are "keep" entries
+static bool
+IsKeepEntry(uint32_t aEntry)
+{
+    return !(aEntry & 1);
+}
 
-    // at start of string?
-    if (aOffset == 0) {
-        mSkippedStringOffset = 0;
-        mCurrentRangeIndex =
-            rangeCount && mSkipChars->mRanges[0].Start() == 0 ? 0 : -1;
+void
+gfxSkipChars::BuildShortcuts()
+{
+    if (!mList || mCharCount < SHORTCUT_FREQUENCY)
+        return;
+  
+    mShortcuts = new Shortcut[mCharCount/SHORTCUT_FREQUENCY];
+    if (!mShortcuts)
         return;
-    }
-
-    // find the range that includes or precedes aOffset
-    uint32_t lo = 0, hi = rangeCount;
-    const gfxSkipChars::SkippedRange* ranges = mSkipChars->mRanges.Elements();
-    while (lo < hi) {
-        uint32_t mid = (lo + hi) / 2;
-        if (uint32_t(aOffset) < ranges[mid].Start()) {
-            hi = mid;
-        } else {
-            lo = mid + 1;
+  
+    uint32_t i;
+    uint32_t nextShortcutIndex = 0;
+    uint32_t originalCharOffset = 0;
+    uint32_t skippedCharOffset = 0;
+    for (i = 0; i < mListLength; ++i) {
+        uint8_t len = mList[i];
+    
+        // We use >= here to ensure that when mCharCount is a multiple of
+        // SHORTCUT_FREQUENCY, we fill in the final shortcut with a reference
+        // to the last element of mList. This means that in general when a list
+        // element ends on an offset that's a multiple of SHORTCUT_FREQUENCY,
+        // that list element is the shortcut for that offset, which is
+        // slightly suboptimal (the *next* element is the one we really want),
+        // but it's all correct and simpler this way.
+        while (originalCharOffset + len >= (nextShortcutIndex + 1)*SHORTCUT_FREQUENCY) {
+            mShortcuts[nextShortcutIndex] =
+                Shortcut(i, originalCharOffset, skippedCharOffset);
+            ++nextShortcutIndex;
+        }
+    
+        originalCharOffset += len;
+        if (IsKeepEntry(i)) {
+            skippedCharOffset += len;
         }
     }
-
-    if (lo == rangeCount) {
-        mCurrentRangeIndex = rangeCount - 1;
-    } else if (uint32_t(aOffset) < ranges[lo].Start()) {
-        mCurrentRangeIndex = lo - 1;
-        if (mCurrentRangeIndex == -1) {
-            mSkippedStringOffset = aOffset;
-            return;
-        }
-    } else {
-        mCurrentRangeIndex = lo;
-    }
-
-    const gfxSkipChars::SkippedRange& r = ranges[mCurrentRangeIndex];
-    if (uint32_t(aOffset) < r.End()) {
-        mSkippedStringOffset = r.SkippedOffset();
-        return;
-    }
-
-    mSkippedStringOffset = aOffset - r.NextDelta();
 }
 
 void
-gfxSkipCharsIterator::SetSkippedOffset(uint32_t aOffset)
+gfxSkipCharsIterator::SetOffsets(uint32_t aOffset, bool aInOriginalString)
 {
-    NS_ASSERTION((mSkipChars->mRanges.IsEmpty() &&
-                  aOffset <= mSkipChars->mCharCount) ||
-                 (aOffset <= mSkipChars->LastRange().SkippedOffset() +
-                                 mSkipChars->mCharCount -
-                                 mSkipChars->LastRange().End()),
-                 "Invalid skipped offset");
-    mSkippedStringOffset = aOffset;
+    NS_ASSERTION(aOffset <= mSkipChars->mCharCount,
+                 "Invalid offset");
 
-    uint32_t rangeCount = mSkipChars->mRanges.Length();
-    if (rangeCount == 0) {
-        mOriginalStringOffset = aOffset;
+    if (mSkipChars->mListLength == 0) {
+        mOriginalStringOffset = mSkippedStringOffset = aOffset;
         return;
     }
-
-    uint32_t lo = 0, hi = rangeCount;
-    const gfxSkipChars::SkippedRange* ranges = mSkipChars->mRanges.Elements();
-    while (lo < hi) {
-        uint32_t mid = (lo + hi) / 2;
-        if (aOffset < ranges[mid].SkippedOffset()) {
-            hi = mid;
+  
+    if (aOffset == 0) {
+        // Start from the beginning of the string.
+        mSkippedStringOffset = 0;
+        mOriginalStringOffset = 0;
+        mListPrefixLength = 0;
+        mListPrefixKeepCharCount = 0;
+        mListPrefixCharCount = 0;
+        if (aInOriginalString) {
+            // Nothing more to do!
+            return;
+        }
+    }
+  
+    if (aInOriginalString && mSkipChars->mShortcuts &&
+        abs(int32_t(aOffset) - int32_t(mListPrefixCharCount)) > SHORTCUT_FREQUENCY) {
+        // Take a shortcut. This makes SetOffsets(..., true) O(1) by bounding
+        // the iterations in the loop below to at most SHORTCUT_FREQUENCY iterations
+        uint32_t shortcutIndex = aOffset/SHORTCUT_FREQUENCY;
+        if (shortcutIndex == 0) {
+            mListPrefixLength = 0;
+            mListPrefixKeepCharCount = 0;
+            mListPrefixCharCount = 0;
         } else {
-            lo = mid + 1;
+            const gfxSkipChars::Shortcut& shortcut = mSkipChars->mShortcuts[shortcutIndex - 1];
+            mListPrefixLength = shortcut.mListPrefixLength;
+            mListPrefixKeepCharCount = shortcut.mListPrefixKeepCharCount;
+            mListPrefixCharCount = shortcut.mListPrefixCharCount;
         }
     }
-
-    if (lo == rangeCount) {
-        mCurrentRangeIndex = rangeCount - 1;
-    } else if (aOffset < ranges[lo].SkippedOffset()) {
-        mCurrentRangeIndex = lo - 1;
-        if (mCurrentRangeIndex == -1) {
-            mOriginalStringOffset = aOffset;
+  
+    int32_t currentRunLength = mSkipChars->mList[mListPrefixLength];
+    for (;;) {
+        // See if aOffset is in the string segment described by
+        // mSkipChars->mList[mListPrefixLength]
+        uint32_t segmentOffset = aInOriginalString ? mListPrefixCharCount : mListPrefixKeepCharCount;
+        if ((aInOriginalString || IsKeepEntry(mListPrefixLength)) &&
+            aOffset >= segmentOffset && aOffset < segmentOffset + currentRunLength) {
+            int32_t offsetInSegment = aOffset - segmentOffset;
+            mOriginalStringOffset = mListPrefixCharCount + offsetInSegment;
+            mSkippedStringOffset = mListPrefixKeepCharCount;
+            if (IsKeepEntry(mListPrefixLength)) {
+                mSkippedStringOffset += offsetInSegment;
+            }
             return;
         }
-    } else {
-        mCurrentRangeIndex = lo;
+        
+        if (aOffset < segmentOffset) {
+            // We need to move backwards
+            if (mListPrefixLength <= 0) {
+                // nowhere to go backwards
+                mOriginalStringOffset = mSkippedStringOffset = 0;
+                return;
+            }
+            // Go backwards one segment and restore invariants
+            --mListPrefixLength;
+            currentRunLength = mSkipChars->mList[mListPrefixLength];
+            mListPrefixCharCount -= currentRunLength;
+            if (IsKeepEntry(mListPrefixLength)) {
+                mListPrefixKeepCharCount -= currentRunLength;
+            }
+        } else {
+            // We need to move forwards
+            if (mListPrefixLength >= mSkipChars->mListLength - 1) {
+                // nowhere to go forwards
+                mOriginalStringOffset = mListPrefixCharCount + currentRunLength;
+                mSkippedStringOffset = mListPrefixKeepCharCount;
+                if (IsKeepEntry(mListPrefixLength)) {
+                    mSkippedStringOffset += currentRunLength;
+                }
+                return;
+            }
+            // Go forwards one segment and restore invariants
+            mListPrefixCharCount += currentRunLength;
+            if (IsKeepEntry(mListPrefixLength)) {
+                mListPrefixKeepCharCount += currentRunLength;
+            }
+            ++mListPrefixLength;
+            currentRunLength = mSkipChars->mList[mListPrefixLength];
+        }
     }
-
-    const gfxSkipChars::SkippedRange& r = ranges[mCurrentRangeIndex];
-    mOriginalStringOffset = r.End() + aOffset - r.SkippedOffset();
 }
 
 bool
 gfxSkipCharsIterator::IsOriginalCharSkipped(int32_t* aRunLength) const
 {
-    if (mCurrentRangeIndex == -1) {
-        // we're before the first skipped range (if any)
+    if (mSkipChars->mListLength == 0) {
         if (aRunLength) {
-            uint32_t end = mSkipChars->mRanges.IsEmpty() ?
-                mSkipChars->mCharCount : mSkipChars->mRanges[0].Start();
-            *aRunLength = end - mOriginalStringOffset;
+            *aRunLength = mSkipChars->mCharCount - mOriginalStringOffset;
         }
         return mSkipChars->mCharCount == uint32_t(mOriginalStringOffset);
     }
-
-    const gfxSkipChars::SkippedRange& range =
-        mSkipChars->mRanges[mCurrentRangeIndex];
-
-    if (uint32_t(mOriginalStringOffset) < range.End()) {
+  
+    uint32_t listPrefixLength = mListPrefixLength;
+    // figure out which segment we're in
+    uint32_t currentRunLength = mSkipChars->mList[listPrefixLength];
+    // Zero-length list entries are possible. Advance until mListPrefixLength
+    // is pointing to a run with real characters (or we're at the end of the
+    // string).
+    while (currentRunLength == 0 && listPrefixLength < mSkipChars->mListLength - 1) {
+        ++listPrefixLength;
+        // This does not break the iterator's invariant because no skipped
+        // or kept characters are being added
+        currentRunLength = mSkipChars->mList[listPrefixLength];
+    }
+    NS_ASSERTION(uint32_t(mOriginalStringOffset) >= mListPrefixCharCount,
+                 "Invariant violation");
+    uint32_t offsetIntoCurrentRun =
+      uint32_t(mOriginalStringOffset) - mListPrefixCharCount;
+    if (listPrefixLength >= mSkipChars->mListLength - 1 &&
+        offsetIntoCurrentRun >= currentRunLength) {
+        NS_ASSERTION(listPrefixLength == mSkipChars->mListLength - 1 &&
+                     offsetIntoCurrentRun == currentRunLength,
+                     "Overran end of string");
+        // We're at the end of the string
         if (aRunLength) {
-            *aRunLength = range.End() - mOriginalStringOffset;
+            *aRunLength = 0;
         }
         return true;
     }
-
+  
+    bool isSkipped = !IsKeepEntry(listPrefixLength);
     if (aRunLength) {
-        uint32_t end =
-            uint32_t(mCurrentRangeIndex) + 1 < mSkipChars->mRanges.Length() ?
-                mSkipChars->mRanges[mCurrentRangeIndex + 1].Start() :
-                mSkipChars->mCharCount;
-        *aRunLength = end - mOriginalStringOffset;
+        // Long runs of all-skipped or all-kept characters will be encoded as
+        // sequences of 255, 0, 255, 0 etc. Compute the maximum run length by skipping
+        // over zero entries.
+        uint32_t runLength = currentRunLength - offsetIntoCurrentRun;
+        for (uint32_t i = listPrefixLength + 2; i < mSkipChars->mListLength; i += 2) {
+            if (mSkipChars->mList[i - 1] != 0)
+                break;
+            runLength += mSkipChars->mList[i];
+        }
+        *aRunLength = runLength;
     }
+    return isSkipped;
+}
 
-    return mSkipChars->mCharCount == uint32_t(mOriginalStringOffset);
+void
+gfxSkipCharsBuilder::FlushRun()
+{
+    NS_ASSERTION((mBuffer.Length() & 1) == mRunSkipped,
+                 "out of sync?");
+    // Fill in buffer entries starting at mBufferLength, as many as necessary
+    uint32_t charCount = mRunCharCount;
+    for (;;) {
+        uint32_t chars = std::min<uint32_t>(255, charCount);
+        if (!mBuffer.AppendElement(chars)) {
+            mInErrorState = true;
+            return;
+        }
+        charCount -= chars;
+        if (charCount == 0)
+            break;
+        if (!mBuffer.AppendElement(0)) {
+            mInErrorState = true;
+            return;
+        }
+    }
+  
+    NS_ASSERTION(mCharCount + mRunCharCount >= mCharCount,
+                 "String length overflow");
+    mCharCount += mRunCharCount;
+    mRunCharCount = 0;
+    mRunSkipped = !mRunSkipped;
 }
--- a/gfx/thebes/gfxSkipChars.h
+++ b/gfx/thebes/gfxSkipChars.h
@@ -1,302 +1,316 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef GFX_SKIP_CHARS_H
 #define GFX_SKIP_CHARS_H
 
+#include "nsAutoPtr.h"
 #include "nsTArray.h"
 
 /*
  * gfxSkipChars is a data structure representing a list of characters that
  * have been skipped. The initial string is called the "original string"
  * and after skipping some characters, the result is called the "skipped string".
  * gfxSkipChars provides efficient ways to translate between offsets in the
  * original string and the skipped string. It is used by textrun code to keep
  * track of offsets before and after text transformations such as whitespace
  * compression and control code deletion.
  */
 
 /**
- * The gfxSkipChars is represented as a sorted array of skipped ranges.
- *
+ * gfxSkipCharsBuilder is a helper class that accumulates a list of (skip, keep)
+ * commands and can eventually be used to construct a real gfxSkipChars.
+ * gfxSkipCharsBuilder objects are quite large so don't keep these around.
+ * On the positive side, the Skip/KeepChar(s) methods are very efficient,
+ * especially when you have runs of all-kept or all-skipped characters.
+ * 
+ * mBuffer is an array of bytes; even numbered bytes represent characters kept,
+ * odd numbered bytes represent characters skipped. After those characters
+ * are accounted for, we have mRunCharCount characters which are kept or
+ * skipped depending on the value of mRunSkipped.
+ * 
+ * mCharCount is the sum of counts of all skipped and kept characters, i.e.,
+ * the length of the original string.
+ */
+class gfxSkipCharsBuilder {
+public:
+    gfxSkipCharsBuilder() :
+        mCharCount(0), mRunCharCount(0), mRunSkipped(false), mInErrorState(false)
+    {}
+  
+    void SkipChars(uint32_t aChars) {
+        DoChars(aChars, true);
+    }
+    void KeepChars(uint32_t aChars) {
+        DoChars(aChars, false);
+    }
+    void SkipChar() {
+        SkipChars(1);
+    }
+    void KeepChar() {
+        KeepChars(1);
+    }
+    void DoChars(uint32_t aChars, bool aSkipped) {
+        if (aSkipped != mRunSkipped && aChars > 0) {
+            FlushRun();
+        }
+        NS_ASSERTION(mRunCharCount + aChars > mRunCharCount,
+                     "Character count overflow");
+        mRunCharCount += aChars;
+    }
+
+    bool IsOK() { return !mInErrorState; }
+
+    uint32_t GetCharCount() { return mCharCount + mRunCharCount; }
+    bool GetAllCharsKept() { return mBuffer.Length() == 0; }
+
+    friend class gfxSkipChars;
+
+private:
+    typedef AutoFallibleTArray<uint8_t,256> Buffer;
+
+    /**
+     * Moves mRunCharCount/mRunSkipped to the buffer (updating mCharCount),
+     * sets mRunCharCount to zero and toggles mRunSkipped.
+     */
+    void FlushRun();
+  
+    Buffer       mBuffer;
+    uint32_t     mCharCount;
+    uint32_t     mRunCharCount;
+    bool mRunSkipped; // == mBuffer.Length()&1
+    bool mInErrorState;
+};
+
+/**
+ * The gfxSkipChars list is represented as a list of bytes of the form
+ * [chars to keep, chars to skip, chars to keep, chars to skip, ...]
+ * In the special case where all chars are to be kept, the list is length
+ * zero.
+ * 
  * A freshly-created gfxSkipChars means "all chars kept".
  */
-class gfxSkipChars
-{
-private:
-    class SkippedRange
-    {
-    public:
-        SkippedRange(uint32_t aOffset, uint32_t aLength, uint32_t aDelta)
-            : mOffset(aOffset), mLength(aLength), mDelta(aDelta)
-        { }
-
-        uint32_t Start() const
-        {
-            return mOffset;
-        }
-
-        uint32_t End() const
-        {
-            return mOffset + mLength;
-        }
-
-        uint32_t Length() const
-        {
-            return mLength;
-        }
-
-        uint32_t SkippedOffset() const
-        {
-            return mOffset - mDelta;
-        }
-
-        uint32_t Delta() const
-        {
-            return mDelta;
-        }
-
-        uint32_t NextDelta() const
-        {
-            return mDelta + mLength;
-        }
-
-        void Extend(uint32_t aChars)
-        {
-            mLength += aChars;
-        }
-
-    private:
-        uint32_t mOffset; // original-string offset at which we want to skip
-        uint32_t mLength; // number of skipped chars at this offset
-        uint32_t mDelta;  // sum of lengths of preceding skipped-ranges
-    };
-
+class gfxSkipChars {
 public:
-    gfxSkipChars()
-        : mCharCount(0)
-    { }
-
-    void SkipChars(uint32_t aChars)
-    {
-        NS_ASSERTION(mCharCount + aChars > mCharCount,
-                     "Character count overflow");
-        uint32_t rangeCount = mRanges.Length();
-        uint32_t delta = 0;
-        if (rangeCount > 0) {
-            SkippedRange& lastRange = mRanges[rangeCount - 1];
-            if (lastRange.End() == mCharCount) {
-                lastRange.Extend(aChars);
-                mCharCount += aChars;
-                return;
-            }
-            delta = lastRange.NextDelta();
-        }
-        mRanges.AppendElement(SkippedRange(mCharCount, aChars, delta));
-        mCharCount += aChars;
-    }
-
-    void KeepChars(uint32_t aChars)
-    {
-        NS_ASSERTION(mCharCount + aChars > mCharCount,
-                     "Character count overflow");
-        mCharCount += aChars;
-    }
-
-    void SkipChar()
-    {
-        SkipChars(1);
-    }
-
-    void KeepChar()
-    {
-        KeepChars(1);
-    }
-
-    void TakeFrom(gfxSkipChars* aSkipChars)
-    {
-        mRanges.SwapElements(aSkipChars->mRanges);
+    gfxSkipChars() : mListLength(0), mCharCount(0) {}
+  
+    void TakeFrom(gfxSkipChars* aSkipChars) {
+        mList = aSkipChars->mList.forget();
+        mListLength = aSkipChars->mListLength;
         mCharCount = aSkipChars->mCharCount;
         aSkipChars->mCharCount = 0;
-    }
-
-    int32_t GetOriginalCharCount() const
-    {
-        return mCharCount;
+        aSkipChars->mListLength = 0;
+        BuildShortcuts();
     }
-
-    const SkippedRange& LastRange() const
-    {
-        // this is only valid if mRanges is non-empty; no assertion here
-        // because nsTArray will already assert if we abuse it
-        return mRanges[mRanges.Length() - 1];
+  
+    void TakeFrom(gfxSkipCharsBuilder* aSkipCharsBuilder) {
+        if (!aSkipCharsBuilder->mBuffer.Length()) {
+            NS_ASSERTION(!aSkipCharsBuilder->mRunSkipped, "out of sync");
+            // all characters kept
+            mCharCount = aSkipCharsBuilder->mRunCharCount;
+            mList = nullptr;
+            mListLength = 0;
+        } else {
+            aSkipCharsBuilder->FlushRun();
+            mCharCount = aSkipCharsBuilder->mCharCount;
+            mList = new uint8_t[aSkipCharsBuilder->mBuffer.Length()];
+            if (!mList) {
+                mListLength = 0;
+            } else {
+                mListLength = aSkipCharsBuilder->mBuffer.Length();
+                memcpy(mList, aSkipCharsBuilder->mBuffer.Elements(), mListLength);
+            }
+        }
+        aSkipCharsBuilder->mBuffer.Clear();
+        aSkipCharsBuilder->mCharCount = 0;
+        aSkipCharsBuilder->mRunCharCount = 0;    
+        aSkipCharsBuilder->mRunSkipped = false;
+        BuildShortcuts();
     }
+  
+    void SetAllKeep(uint32_t aLength) {
+        mCharCount = aLength;
+        mList = nullptr;
+        mListLength = 0;
+    }
+  
+    int32_t GetOriginalCharCount() const { return mCharCount; }
 
     friend class gfxSkipCharsIterator;
 
 private:
-    nsTArray<SkippedRange> mRanges;
-    uint32_t               mCharCount;
+    struct Shortcut {
+        uint32_t mListPrefixLength;
+        uint32_t mListPrefixCharCount;
+        uint32_t mListPrefixKeepCharCount;
+    
+        Shortcut() {}
+        Shortcut(uint32_t aListPrefixLength, uint32_t aListPrefixCharCount,
+                 uint32_t aListPrefixKeepCharCount) :
+            mListPrefixLength(aListPrefixLength),
+            mListPrefixCharCount(aListPrefixCharCount),
+            mListPrefixKeepCharCount(aListPrefixKeepCharCount) {}
+    };
+  
+    void BuildShortcuts();
+
+    nsAutoArrayPtr<uint8_t>  mList;
+    nsAutoArrayPtr<Shortcut> mShortcuts;
+    uint32_t                 mListLength;
+    uint32_t                 mCharCount;
 };
 
 /**
  * A gfxSkipCharsIterator represents a position in the original string. It lets you
  * map efficiently to and from positions in the string after skipped characters
  * have been removed. You can also specify an offset that is added to all
  * incoming original string offsets and subtracted from all outgoing original
  * string offsets --- useful when the gfxSkipChars corresponds to something
  * offset from the original DOM coordinates, which it often does for gfxTextRuns.
- *
+ * 
  * The current positions (in both the original and skipped strings) are
  * always constrained to be >= 0 and <= the string length. When the position
  * is equal to the string length, it is at the end of the string. The current
  * positions do not include any aOriginalStringToSkipCharsOffset.
- *
+ * 
  * When the position in the original string corresponds to a skipped character,
  * the skipped-characters offset is the offset of the next unskipped character,
  * or the skipped-characters string length if there is no next unskipped character.
  */
-class gfxSkipCharsIterator
-{
+class gfxSkipCharsIterator {
 public:
     /**
      * @param aOriginalStringToSkipCharsOffset add this to all incoming and
      * outgoing original string offsets
      */
     gfxSkipCharsIterator(const gfxSkipChars& aSkipChars,
                          int32_t aOriginalStringToSkipCharsOffset,
                          int32_t aOriginalStringOffset)
         : mSkipChars(&aSkipChars),
-          mOriginalStringOffset(0),
-          mSkippedStringOffset(0),
-          mCurrentRangeIndex(-1),
-          mOriginalStringToSkipCharsOffset(aOriginalStringToSkipCharsOffset)
-    {
+          mOriginalStringToSkipCharsOffset(aOriginalStringToSkipCharsOffset),
+          mListPrefixLength(0), mListPrefixCharCount(0), mListPrefixKeepCharCount(0) {
           SetOriginalOffset(aOriginalStringOffset);
     }
 
     gfxSkipCharsIterator(const gfxSkipChars& aSkipChars,
                          int32_t aOriginalStringToSkipCharsOffset = 0)
         : mSkipChars(&aSkipChars),
-          mOriginalStringOffset(0),
-          mSkippedStringOffset(0),
-          mCurrentRangeIndex(-1),
-          mOriginalStringToSkipCharsOffset(aOriginalStringToSkipCharsOffset)
-    { }
+          mOriginalStringOffset(0), mSkippedStringOffset(0),
+          mOriginalStringToSkipCharsOffset(aOriginalStringToSkipCharsOffset),
+          mListPrefixLength(0), mListPrefixCharCount(0), mListPrefixKeepCharCount(0) {
+    }
 
     gfxSkipCharsIterator(const gfxSkipCharsIterator& aIterator)
         : mSkipChars(aIterator.mSkipChars),
           mOriginalStringOffset(aIterator.mOriginalStringOffset),
           mSkippedStringOffset(aIterator.mSkippedStringOffset),
-          mCurrentRangeIndex(aIterator.mCurrentRangeIndex),
-          mOriginalStringToSkipCharsOffset(aIterator.mOriginalStringToSkipCharsOffset)
-    { }
-
+          mOriginalStringToSkipCharsOffset(aIterator.mOriginalStringToSkipCharsOffset),
+          mListPrefixLength(aIterator.mListPrefixLength),
+          mListPrefixCharCount(aIterator.mListPrefixCharCount),
+          mListPrefixKeepCharCount(aIterator.mListPrefixKeepCharCount)
+    {}
+  
     /**
      * The empty constructor creates an object that is useless until it is assigned.
      */
-    gfxSkipCharsIterator()
-        : mSkipChars(nullptr)
-    { }
+    gfxSkipCharsIterator() : mSkipChars(nullptr) {}
 
     /**
      * Return true if this iterator is properly initialized and usable.
-     */
-    bool IsInitialized()
-    {
-        return mSkipChars != nullptr;
-    }
+     */  
+    bool IsInitialized() { return mSkipChars != nullptr; }
 
     /**
      * Set the iterator to aOriginalStringOffset in the original string.
      * This can efficiently move forward or backward from the current position.
      * aOriginalStringOffset is clamped to [0,originalStringLength].
      */
-    void SetOriginalOffset(int32_t aOriginalStringOffset);
-
+    void SetOriginalOffset(int32_t aOriginalStringOffset) {
+        SetOffsets(aOriginalStringOffset + mOriginalStringToSkipCharsOffset, true);
+    }
+    
     /**
      * Set the iterator to aSkippedStringOffset in the skipped string.
      * This can efficiently move forward or backward from the current position.
      * aSkippedStringOffset is clamped to [0,skippedStringLength].
      */
-    void SetSkippedOffset(uint32_t aSkippedStringOffset);
-
-    uint32_t ConvertOriginalToSkipped(int32_t aOriginalStringOffset)
-    {
+    void SetSkippedOffset(uint32_t aSkippedStringOffset) {
+        SetOffsets(aSkippedStringOffset, false);
+    }
+    
+    uint32_t ConvertOriginalToSkipped(int32_t aOriginalStringOffset) {
         SetOriginalOffset(aOriginalStringOffset);
         return GetSkippedOffset();
     }
-
-    uint32_t ConvertSkippedToOriginal(int32_t aSkippedStringOffset)
-    {
+    uint32_t ConvertSkippedToOriginal(int32_t aSkippedStringOffset) {
         SetSkippedOffset(aSkippedStringOffset);
         return GetOriginalOffset();
     }
-
+  
     /**
      * Test if the character at the current position in the original string
      * is skipped or not. If aRunLength is non-null, then *aRunLength is set
      * to a number of characters all of which are either skipped or not, starting
      * at this character. When the current position is at the end of the original
      * string, we return true and *aRunLength is set to zero.
      */
     bool IsOriginalCharSkipped(int32_t* aRunLength = nullptr) const;
-
-    void AdvanceOriginal(int32_t aDelta)
-    {
-        SetOriginalOffset(GetOriginalOffset() + aDelta);
+    
+    void AdvanceOriginal(int32_t aDelta) {
+        SetOffsets(mOriginalStringOffset + aDelta, true);
     }
-
-    void AdvanceSkipped(int32_t aDelta)
-    {
-        SetSkippedOffset(GetSkippedOffset() + aDelta);
+    void AdvanceSkipped(int32_t aDelta) {
+        SetOffsets(mSkippedStringOffset + aDelta, false);
     }
-
+  
     /**
      * @return the offset within the original string
      */
-    int32_t GetOriginalOffset() const
-    {
+    int32_t GetOriginalOffset() const {
         return mOriginalStringOffset - mOriginalStringToSkipCharsOffset;
     }
-
     /**
      * @return the offset within the skipped string corresponding to the
      * current position in the original string. If the current position
      * in the original string is a character that is skipped, then we return
      * the position corresponding to the first non-skipped character in the
      * original string after the current position, or the length of the skipped
      * string if there is no such character.
      */
-    uint32_t GetSkippedOffset() const
-    {
-        return mSkippedStringOffset;
-    }
+    uint32_t GetSkippedOffset() const { return mSkippedStringOffset; }
 
-    int32_t GetOriginalEnd() const
-    {
+    int32_t GetOriginalEnd() const {
         return mSkipChars->GetOriginalCharCount() -
             mOriginalStringToSkipCharsOffset;
     }
 
 private:
+    void SetOffsets(uint32_t aOffset, bool aInOriginalString);
+  
     const gfxSkipChars* mSkipChars;
-
-    // Current position
     int32_t mOriginalStringOffset;
     uint32_t mSkippedStringOffset;
 
-    // Index of the last skippedRange that precedes or contains the current
-    // position in the original string.
-    // If index == -1 then we are before the first skipped char.
-    int32_t mCurrentRangeIndex;
-
     // This offset is added to map from "skipped+unskipped characters in
     // the original DOM string" character space to "skipped+unskipped
     // characters in the textrun's gfxSkipChars" character space
     int32_t mOriginalStringToSkipCharsOffset;
+
+    /*
+     * This is used to speed up cursor-style traversal. The invariant is that
+     * the first mListPrefixLength bytes of mSkipChars.mList sum to
+     * mListPrefixCharCount, and the even-indexed bytes in that prefix sum to
+     * mListPrefixKeepCharCount.
+     * Also, 0 <= mListPrefixLength < mSkipChars.mListLength, or else
+     * mSkipChars.mListLength is zero.
+     * Also, mListPrefixCharCount <= mOriginalStringOffset (and therefore
+     * mListPrefixKeepCharCount < mSkippedStringOffset).
+     */
+    uint32_t mListPrefixLength;
+    uint32_t mListPrefixCharCount;
+    uint32_t mListPrefixKeepCharCount;
 };
 
 #endif /*GFX_SKIP_CHARS_H*/
--- a/layout/generic/nsTextFrame.cpp
+++ b/layout/generic/nsTextFrame.cpp
@@ -1883,17 +1883,17 @@ static const nsTextFrameUtils::Compressi
   nsTextFrameUtils::COMPRESS_NONE,               // pre-wrap
   nsTextFrameUtils::COMPRESS_WHITESPACE,         // pre-line
   nsTextFrameUtils::DISCARD_NEWLINE              // -moz-pre-discard-newlines
 };
 
 gfxTextRun*
 BuildTextRunsScanner::BuildTextRunForFrames(void* aTextBuffer)
 {
-  gfxSkipChars skipChars;
+  gfxSkipCharsBuilder builder;
 
   const void* textPtr = aTextBuffer;
   bool anySmallcapsStyle = false;
   bool anyTextTransformStyle = false;
   bool anyMathVariantStyle = false;
   uint32_t textFlags = nsTextFrameUtils::TEXT_NO_BREAKS;
 
   if (mCurrentRunContextInfo & nsTextFrameUtils::INCOMING_WHITESPACE) {
@@ -1982,64 +1982,70 @@ BuildTextRunsScanner::BuildTextRunForFra
     nsIContent* content = f->GetContent();
     const nsTextFragment* frag = content->GetText();
     int32_t contentStart = mappedFlow->mStartFrame->GetContentOffset();
     int32_t contentEnd = mappedFlow->GetContentEnd();
     int32_t contentLength = contentEnd - contentStart;
 
     TextRunMappedFlow* newFlow = &userData->mMappedFlows[i];
     newFlow->mStartFrame = mappedFlow->mStartFrame;
-    newFlow->mDOMOffsetToBeforeTransformOffset = skipChars.GetOriginalCharCount() -
+    newFlow->mDOMOffsetToBeforeTransformOffset = builder.GetCharCount() -
       mappedFlow->mStartFrame->GetContentOffset();
     newFlow->mContentLength = contentLength;
 
     while (nextBreakBeforeFrame && nextBreakBeforeFrame->GetContent() == content) {
       textBreakPoints.AppendElement(
           nextBreakBeforeFrame->GetContentOffset() + newFlow->mDOMOffsetToBeforeTransformOffset);
       nextBreakBeforeFrame = GetNextBreakBeforeFrame(&nextBreakIndex);
     }
 
     uint32_t analysisFlags;
     if (frag->Is2b()) {
       NS_ASSERTION(mDoubleByteText, "Wrong buffer char size!");
       char16_t* bufStart = static_cast<char16_t*>(aTextBuffer);
       char16_t* bufEnd = nsTextFrameUtils::TransformText(
           frag->Get2b() + contentStart, contentLength, bufStart,
-          compression, &mNextRunContextInfo, &skipChars, &analysisFlags);
+          compression, &mNextRunContextInfo, &builder, &analysisFlags);
       aTextBuffer = bufEnd;
       currentTransformedTextOffset = bufEnd - static_cast<const char16_t*>(textPtr);
     } else {
       if (mDoubleByteText) {
         // Need to expand the text. First transform it into a temporary buffer,
         // then expand.
         AutoFallibleTArray<uint8_t,BIG_TEXT_NODE_SIZE> tempBuf;
         uint8_t* bufStart = tempBuf.AppendElements(contentLength);
         if (!bufStart) {
           DestroyUserData(userDataToDestroy);
           return nullptr;
         }
         uint8_t* end = nsTextFrameUtils::TransformText(
             reinterpret_cast<const uint8_t*>(frag->Get1b()) + contentStart, contentLength,
-            bufStart, compression, &mNextRunContextInfo, &skipChars, &analysisFlags);
+            bufStart, compression, &mNextRunContextInfo, &builder, &analysisFlags);
         aTextBuffer = ExpandBuffer(static_cast<char16_t*>(aTextBuffer),
                                    tempBuf.Elements(), end - tempBuf.Elements());
         currentTransformedTextOffset =
           static_cast<char16_t*>(aTextBuffer) - static_cast<const char16_t*>(textPtr);
       } else {
         uint8_t* bufStart = static_cast<uint8_t*>(aTextBuffer);
         uint8_t* end = nsTextFrameUtils::TransformText(
             reinterpret_cast<const uint8_t*>(frag->Get1b()) + contentStart, contentLength,
-            bufStart, compression, &mNextRunContextInfo, &skipChars, &analysisFlags);
+            bufStart, compression, &mNextRunContextInfo, &builder, &analysisFlags);
         aTextBuffer = end;
         currentTransformedTextOffset = end - static_cast<const uint8_t*>(textPtr);
       }
     }
     textFlags |= analysisFlags;
   }
 
+  // Check for out-of-memory in gfxSkipCharsBuilder
+  if (!builder.IsOK()) {
+    DestroyUserData(userDataToDestroy);
+    return nullptr;
+  }
+
   void* finalUserData;
   if (userData == &dummyData) {
     textFlags |= nsTextFrameUtils::TEXT_IS_SIMPLE_FLOW;
     userData = nullptr;
     finalUserData = mMappedFlows[0].mStartFrame;
   } else {
     finalUserData = userData;
   }
@@ -2082,16 +2088,18 @@ BuildTextRunsScanner::BuildTextRunForFra
   textFlags |= nsLayoutUtils::GetTextRunFlagsForStyle(lastStyleContext,
       fontStyle, LetterSpacing(firstFrame, textStyle));
   // XXX this is a bit of a hack. For performance reasons, if we're favouring
   // performance over quality, don't try to get accurate glyph extents.
   if (!(textFlags & gfxTextRunFactory::TEXT_OPTIMIZE_SPEED)) {
     textFlags |= gfxTextRunFactory::TEXT_NEED_BOUNDING_BOX;
   }
 
+  gfxSkipChars skipChars;
+  skipChars.TakeFrom(&builder);
   // Convert linebreak coordinates to transformed string offsets
   NS_ASSERTION(nextBreakIndex == mLineBreakBeforeFrames.Length(),
                "Didn't find all the frames to break-before...");
   gfxSkipCharsIterator iter(skipChars);
   nsAutoTArray<uint32_t,50> textBreakPointsAfterTransform;
   for (uint32_t i = 0; i < textBreakPoints.Length(); ++i) {
     nsTextFrameUtils::AppendLineBreakOffset(&textBreakPointsAfterTransform, 
             iter.ConvertOriginalToSkipped(textBreakPoints[i]));
@@ -2222,17 +2230,17 @@ BuildTextRunsScanner::SetupLineBreakerCo
   if (bufferSize < mMaxTextLength || bufferSize == UINT32_MAX) {
     return false;
   }
   void *textPtr = buffer.AppendElements(bufferSize);
   if (!textPtr) {
     return false;
   }
 
-  gfxSkipChars skipChars;
+  gfxSkipCharsBuilder builder;
 
   nsAutoTArray<int32_t,50> textBreakPoints;
   TextRunUserData dummyData;
   TextRunMappedFlow dummyMappedFlow;
 
   TextRunUserData* userData;
   TextRunUserData* userDataToDestroy;
   // If the situation is particularly simple (and common) we don't need to
@@ -2267,54 +2275,54 @@ BuildTextRunsScanner::SetupLineBreakerCo
     nsIContent* content = f->GetContent();
     const nsTextFragment* frag = content->GetText();
     int32_t contentStart = mappedFlow->mStartFrame->GetContentOffset();
     int32_t contentEnd = mappedFlow->GetContentEnd();
     int32_t contentLength = contentEnd - contentStart;
 
     TextRunMappedFlow* newFlow = &userData->mMappedFlows[i];
     newFlow->mStartFrame = mappedFlow->mStartFrame;
-    newFlow->mDOMOffsetToBeforeTransformOffset = skipChars.GetOriginalCharCount() -
+    newFlow->mDOMOffsetToBeforeTransformOffset = builder.GetCharCount() -
       mappedFlow->mStartFrame->GetContentOffset();
     newFlow->mContentLength = contentLength;
 
     while (nextBreakBeforeFrame && nextBreakBeforeFrame->GetContent() == content) {
       textBreakPoints.AppendElement(
           nextBreakBeforeFrame->GetContentOffset() + newFlow->mDOMOffsetToBeforeTransformOffset);
       nextBreakBeforeFrame = GetNextBreakBeforeFrame(&nextBreakIndex);
     }
 
     uint32_t analysisFlags;
     if (frag->Is2b()) {
       NS_ASSERTION(mDoubleByteText, "Wrong buffer char size!");
       char16_t* bufStart = static_cast<char16_t*>(textPtr);
       char16_t* bufEnd = nsTextFrameUtils::TransformText(
           frag->Get2b() + contentStart, contentLength, bufStart,
-          compression, &mNextRunContextInfo, &skipChars, &analysisFlags);
+          compression, &mNextRunContextInfo, &builder, &analysisFlags);
       textPtr = bufEnd;
     } else {
       if (mDoubleByteText) {
         // Need to expand the text. First transform it into a temporary buffer,
         // then expand.
         AutoFallibleTArray<uint8_t,BIG_TEXT_NODE_SIZE> tempBuf;
         uint8_t* bufStart = tempBuf.AppendElements(contentLength);
         if (!bufStart) {
           DestroyUserData(userDataToDestroy);
           return false;
         }
         uint8_t* end = nsTextFrameUtils::TransformText(
             reinterpret_cast<const uint8_t*>(frag->Get1b()) + contentStart, contentLength,
-            bufStart, compression, &mNextRunContextInfo, &skipChars, &analysisFlags);
+            bufStart, compression, &mNextRunContextInfo, &builder, &analysisFlags);
         textPtr = ExpandBuffer(static_cast<char16_t*>(textPtr),
                                tempBuf.Elements(), end - tempBuf.Elements());
       } else {
         uint8_t* bufStart = static_cast<uint8_t*>(textPtr);
         uint8_t* end = nsTextFrameUtils::TransformText(
             reinterpret_cast<const uint8_t*>(frag->Get1b()) + contentStart, contentLength,
-            bufStart, compression, &mNextRunContextInfo, &skipChars, &analysisFlags);
+            bufStart, compression, &mNextRunContextInfo, &builder, &analysisFlags);
         textPtr = end;
       }
     }
   }
 
   // We have to set these up after we've created the textrun, because
   // the breaks may be stored in the textrun during this very call.
   // This is a bit annoying because it requires another loop over the frames
@@ -8318,17 +8326,17 @@ static char16_t TransformChar(const nsSt
 
 nsresult nsTextFrame::GetRenderedText(nsAString* aAppendToString,
                                       gfxSkipChars* aSkipChars,
                                       gfxSkipCharsIterator* aSkipIter,
                                       uint32_t aSkippedStartOffset,
                                       uint32_t aSkippedMaxLength)
 {
   // The handling of aSkippedStartOffset and aSkippedMaxLength could be more efficient...
-  gfxSkipChars skipChars;
+  gfxSkipCharsBuilder skipCharsBuilder;
   nsTextFrame* textFrame;
   const nsTextFragment* textFrag = mContent->GetText();
   uint32_t keptCharsLength = 0;
   uint32_t validCharsLength = 0;
 
   // Build skipChars and copy text, for each text frame in this continuation block
   for (textFrame = this; textFrame;
        textFrame = static_cast<nsTextFrame*>(textFrame->GetNextContinuation())) {
@@ -8347,48 +8355,48 @@ nsresult nsTextFrame::GetRenderedText(ns
 
     // Skip to the start of the text run, past ignored chars at start of line
     // XXX In the future we may decide to trim extra spaces before a hard line
     // break, in which case we need to accurately detect those sitations and 
     // call GetTrimmedOffsets() with true to trim whitespace at the line's end
     TrimmedOffsets trimmedContentOffsets = textFrame->GetTrimmedOffsets(textFrag, false);
     int32_t startOfLineSkipChars = trimmedContentOffsets.mStart - textFrame->mContentOffset;
     if (startOfLineSkipChars > 0) {
-      skipChars.SkipChars(startOfLineSkipChars);
+      skipCharsBuilder.SkipChars(startOfLineSkipChars);
       iter.SetOriginalOffset(trimmedContentOffsets.mStart);
     }
 
     // Keep and copy the appropriate chars withing the caller's requested range
     const nsStyleText* textStyle = textFrame->StyleText();
     while (iter.GetOriginalOffset() < trimmedContentOffsets.GetEnd() &&
            keptCharsLength < aSkippedMaxLength) {
       // For each original char from content text
       if (iter.IsOriginalCharSkipped() || ++validCharsLength <= aSkippedStartOffset) {
-        skipChars.SkipChar();
+        skipCharsBuilder.SkipChar();
       } else {
         ++keptCharsLength;
-        skipChars.KeepChar();
+        skipCharsBuilder.KeepChar();
         if (aAppendToString) {
           aAppendToString->Append(
               TransformChar(textStyle, textFrame->mTextRun, iter.GetSkippedOffset(),
                             textFrag->CharAt(iter.GetOriginalOffset())));
         }
       }
       iter.AdvanceOriginal(1);
     }
     if (keptCharsLength >= aSkippedMaxLength) {
       break; // Already past the end, don't build string or gfxSkipCharsIter anymore
     }
   }
   
   if (aSkipChars) {
-    aSkipChars->TakeFrom(&skipChars); // Copy skipChars into aSkipChars
+    aSkipChars->TakeFrom(&skipCharsBuilder); // Copy skipChars into aSkipChars
     if (aSkipIter) {
       // Caller must provide both pointers in order to retrieve a gfxSkipCharsIterator,
-      // because the gfxSkipCharsIterator holds a weak pointer to the gfxSkipChars.
+      // because the gfxSkipCharsIterator holds a weak pointer to the gfxSkipCars.
       *aSkipIter = gfxSkipCharsIterator(*aSkipChars, GetContentLength());
     }
   }
 
   return NS_OK;
 }
 
 nsIAtom*
--- a/layout/generic/nsTextFrameUtils.cpp
+++ b/layout/generic/nsTextFrameUtils.cpp
@@ -33,17 +33,17 @@ static bool IsDiscardable(uint8_t ch, ui
   return false;
 }
 
 char16_t*
 nsTextFrameUtils::TransformText(const char16_t* aText, uint32_t aLength,
                                 char16_t* aOutput,
                                 CompressionMode aCompression,
                                 uint8_t* aIncomingFlags,
-                                gfxSkipChars* aSkipChars,
+                                gfxSkipCharsBuilder* aSkipChars,
                                 uint32_t* aAnalysisFlags)
 {
   uint32_t flags = 0;
   char16_t* outputStart = aOutput;
 
   bool lastCharArabic = false;
 
   if (aCompression == COMPRESS_NONE ||
@@ -135,17 +135,17 @@ nsTextFrameUtils::TransformText(const ch
   return aOutput;
 }
 
 uint8_t*
 nsTextFrameUtils::TransformText(const uint8_t* aText, uint32_t aLength,
                                 uint8_t* aOutput,
                                 CompressionMode aCompression,
                                 uint8_t* aIncomingFlags,
-                                gfxSkipChars* aSkipChars,
+                                gfxSkipCharsBuilder* aSkipChars,
                                 uint32_t* aAnalysisFlags)
 {
   uint32_t flags = 0;
   uint8_t* outputStart = aOutput;
 
   if (aCompression == COMPRESS_NONE ||
       aCompression == DISCARD_NEWLINE) {
     // Skip discardables.
--- a/layout/generic/nsTextFrameUtils.h
+++ b/layout/generic/nsTextFrameUtils.h
@@ -95,24 +95,24 @@ public:
    * @param aIncomingFlags a flag indicating whether there was whitespace
    * or an Arabic character preceding this text. We set it to indicate if
    * there's an Arabic character or whitespace preceding the end of this text.
    */
   static char16_t* TransformText(const char16_t* aText, uint32_t aLength,
                                   char16_t* aOutput,
                                   CompressionMode aCompression,
                                   uint8_t * aIncomingFlags,
-                                  gfxSkipChars* aSkipChars,
+                                  gfxSkipCharsBuilder* aSkipChars,
                                   uint32_t* aAnalysisFlags);
 
   static uint8_t* TransformText(const uint8_t* aText, uint32_t aLength,
                                 uint8_t* aOutput,
                                 CompressionMode aCompression,
                                 uint8_t * aIncomingFlags,
-                                gfxSkipChars* aSkipChars,
+                                gfxSkipCharsBuilder* aSkipChars,
                                 uint32_t* aAnalysisFlags);
 
   static void
   AppendLineBreakOffset(nsTArray<uint32_t>* aArray, uint32_t aOffset)
   {
     if (aArray->Length() > 0 && (*aArray)[aArray->Length() - 1] == aOffset)
       return;
     aArray->AppendElement(aOffset);