Bug 1004098 - Make nsTArray use size_t in its interface (32bitness is fine as an internal detail) - r=froydnj, sr=bsmedberg
authorBenoit Jacob <bjacob@mozilla.com>
Thu, 08 May 2014 21:03:35 -0400
changeset 182282 b347f6eb2239cf0c08eef7af4f6d9eb36a0eda99
parent 182281 36ba501f5585c84cdbe8b7597bd1f92c03bfb57e
child 182283 fbef254f0aa5c1eb8b6c635d1f3a1d8a41b89c1c
push idunknown
push userunknown
push dateunknown
reviewersfroydnj, bsmedberg
bugs1004098
milestone32.0a1
Bug 1004098 - Make nsTArray use size_t in its interface (32bitness is fine as an internal detail) - r=froydnj, sr=bsmedberg
content/base/src/nsXMLNameSpaceMap.cpp
content/html/content/src/HTMLFormElement.cpp
content/html/content/src/HTMLInputElement.cpp
content/media/AudioNodeExternalInputStream.cpp
content/media/AudioNodeExternalInputStream.h
content/media/EncodedBufferCache.cpp
content/media/MediaCache.cpp
content/media/mediasource/SourceBufferResource.h
content/media/webaudio/AnalyserNode.cpp
content/media/webaudio/AudioNode.cpp
content/media/webaudio/WebAudioUtils.cpp
content/media/webaudio/WebAudioUtils.h
content/xul/document/src/XULDocument.cpp
dom/indexedDB/TransactionThreadPool.cpp
dom/ipc/TabChild.cpp
dom/workers/WorkerPrivate.cpp
dom/xbl/XBLChildrenElement.cpp
dom/xbl/nsBindingManager.cpp
dom/xslt/base/txExpandedNameMap.cpp
editor/libeditor/html/nsHTMLEditRules.cpp
editor/libeditor/html/nsHTMLEditor.cpp
gfx/thebes/gfxXlibSurface.cpp
image/src/RasterImage.cpp
image/src/RasterImage.h
layout/base/DisplayItemClip.cpp
layout/generic/nsTextFrame.cpp
layout/style/nsTransitionManager.cpp
layout/tables/nsCellMap.cpp
layout/tables/nsTableFrame.cpp
layout/xul/nsMenuBarFrame.cpp
modules/libjar/nsJARProtocolHandler.h
toolkit/components/places/nsMaybeWeakPtr.cpp
toolkit/components/url-classifier/ChunkSet.cpp
toolkit/components/url-classifier/Classifier.cpp
widget/xpwidgets/nsTransferable.cpp
xpcom/ds/nsExpirationTracker.h
xpcom/glue/DeadlockDetector.h
xpcom/glue/nsTArray-inl.h
xpcom/glue/nsTArray.cpp
xpcom/glue/nsTArray.h
xpcom/glue/nsTArrayForwardDeclare.h
xpcom/glue/nsTObserverArray.h
xpcom/tests/TestTArray.cpp
--- a/content/base/src/nsXMLNameSpaceMap.cpp
+++ b/content/base/src/nsXMLNameSpaceMap.cpp
@@ -74,31 +74,31 @@ nsXMLNameSpaceMap::AddPrefix(nsIAtom *aP
   NS_ENSURE_SUCCESS(rv, rv);
 
   return AddPrefix(aPrefix, id);
 }
 
 int32_t
 nsXMLNameSpaceMap::FindNameSpaceID(nsIAtom *aPrefix) const
 {
-  uint32_t index = mNameSpaces.IndexOf(aPrefix);
+  size_t index = mNameSpaces.IndexOf(aPrefix);
   if (index != mNameSpaces.NoIndex) {
     return mNameSpaces[index].nameSpaceID;
   }
 
   // The default mapping for no prefix is no namespace.  If a non-null prefix
   // was specified and we didn't find it, we return an error.
 
   return aPrefix ? kNameSpaceID_Unknown : kNameSpaceID_None;
 }
 
 nsIAtom*
 nsXMLNameSpaceMap::FindPrefix(int32_t aNameSpaceID) const
 {
-  uint32_t index = mNameSpaces.IndexOf(aNameSpaceID);
+  size_t index = mNameSpaces.IndexOf(aNameSpaceID);
   if (index != mNameSpaces.NoIndex) {
     return mNameSpaces[index].prefix;
   }
 
   return nullptr;
 }
 
 void
--- a/content/html/content/src/HTMLFormElement.cpp
+++ b/content/html/content/src/HTMLFormElement.cpp
@@ -1247,17 +1247,17 @@ HTMLFormElement::RemoveElement(nsGeneric
   // Determine whether to remove the child from the elements list
   // or the not in elements list.
   bool childInElements = HTMLFormControlsCollection::ShouldBeInElements(aChild);
   nsTArray<nsGenericHTMLFormElement*>& controls = childInElements ?
       mControls->mElements :  mControls->mNotInElements;
   
   // Find the index of the child. This will be used later if necessary
   // to find the default submit.
-  uint32_t index = controls.IndexOf(aChild);
+  size_t index = controls.IndexOf(aChild);
   NS_ENSURE_STATE(index != controls.NoIndex);
 
   controls.RemoveElementAt(index);
 
   // Update our mFirstSubmit* values.
   nsGenericHTMLFormElement** firstSubmitSlot =
     childInElements ? &mFirstSubmitInElements : &mFirstSubmitNotInElements;
   if (aChild == *firstSubmitSlot) {
@@ -2334,17 +2334,17 @@ HTMLFormElement::AddImageElementToTable(
                                         const nsAString& aName)
 {
   return AddElementToTableInternal(mImageNameLookupTable, aChild, aName);
 }
 
 nsresult
 HTMLFormElement::RemoveImageElement(HTMLImageElement* aChild)
 {
-  uint32_t index = mImageElements.IndexOf(aChild);
+  size_t index = mImageElements.IndexOf(aChild);
   NS_ENSURE_STATE(index != mImageElements.NoIndex);
 
   mImageElements.RemoveElementAt(index);
   return NS_OK;
 }
 
 nsresult
 HTMLFormElement::RemoveImageElementFromTable(HTMLImageElement* aElement,
--- a/content/html/content/src/HTMLInputElement.cpp
+++ b/content/html/content/src/HTMLInputElement.cpp
@@ -2513,17 +2513,17 @@ HTMLInputElement::GetDisplayFileName(nsA
       nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
                                          "NoFilesSelected", value);
     } else {
       nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
                                          "NoFileSelected", value);
     }
   } else {
     nsString count;
-    count.AppendInt(mFiles.Length());
+    count.AppendInt(int(mFiles.Length()));
 
     const char16_t* params[] = { count.get() };
     nsContentUtils::FormatLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
                                           "XFilesSelected", params, value);
   }
 
   aValue = value;
 }
--- a/content/media/AudioNodeExternalInputStream.cpp
+++ b/content/media/AudioNodeExternalInputStream.cpp
@@ -26,24 +26,24 @@ AudioNodeExternalInputStream::~AudioNode
 
 AudioNodeExternalInputStream::TrackMapEntry::~TrackMapEntry()
 {
   if (mResampler) {
     speex_resampler_destroy(mResampler);
   }
 }
 
-uint32_t
+size_t
 AudioNodeExternalInputStream::GetTrackMapEntry(const StreamBuffer::Track& aTrack,
                                                GraphTime aFrom)
 {
   AudioSegment* segment = aTrack.Get<AudioSegment>();
 
   // Check the map for an existing entry corresponding to the input track.
-  for (uint32_t i = 0; i < mTrackMap.Length(); ++i) {
+  for (size_t i = 0; i < mTrackMap.Length(); ++i) {
     TrackMapEntry* map = &mTrackMap[i];
     if (map->mTrackID == aTrack.GetID()) {
       return i;
     }
   }
 
   // Determine channel count by finding the first entry with non-silent data.
   AudioSegment::ChunkIterator ci(*segment);
@@ -53,17 +53,17 @@ AudioNodeExternalInputStream::GetTrackMa
   if (ci.IsEnded()) {
     // The track is entirely silence so far, we can ignore it for now.
     return nsTArray<TrackMapEntry>::NoIndex;
   }
 
   // Create a speex resampler with the same sample rate and number of channels
   // as the track.
   SpeexResamplerState* resampler = nullptr;
-  uint32_t channelCount = std::min((*ci).mChannelData.Length(),
+  size_t channelCount = std::min((*ci).mChannelData.Length(),
                                    WebAudioUtils::MaxChannelCount);
   if (aTrack.GetRate() != mSampleRate) {
     resampler = speex_resampler_init(channelCount,
       aTrack.GetRate(), mSampleRate, SPEEX_RESAMPLER_QUALITY_DEFAULT, nullptr);
     speex_resampler_skip_zeros(resampler);
   }
 
   TrackMapEntry* map = mTrackMap.AppendElement();
@@ -335,17 +335,17 @@ AudioNodeExternalInputStream::ProcessInp
   MediaStream* source = mInputs[0]->GetSource();
   nsAutoTArray<AudioSegment,1> audioSegments;
   nsAutoTArray<bool,1> trackMapEntriesUsed;
   uint32_t inputChannels = 0;
   for (StreamBuffer::TrackIter tracks(source->mBuffer, MediaSegment::AUDIO);
        !tracks.IsEnded(); tracks.Next()) {
     const StreamBuffer::Track& inputTrack = *tracks;
     // Create a TrackMapEntry if necessary.
-    uint32_t trackMapIndex = GetTrackMapEntry(inputTrack, aFrom);
+    size_t trackMapIndex = GetTrackMapEntry(inputTrack, aFrom);
     // Maybe there's nothing in this track yet. If so, ignore it. (While the
     // track is only playing silence, we may not be able to determine the
     // correct number of channels to start resampling.)
     if (trackMapIndex == nsTArray<TrackMapEntry>::NoIndex) {
       continue;
     }
 
     while (trackMapEntriesUsed.Length() <= trackMapIndex) {
--- a/content/media/AudioNodeExternalInputStream.h
+++ b/content/media/AudioNodeExternalInputStream.h
@@ -87,15 +87,15 @@ private:
   nsTArray<TrackMapEntry> mTrackMap;
   // Amount of track data produced so far. A multiple of WEBAUDIO_BLOCK_SIZE.
   TrackTicks mCurrentOutputPosition;
 
   /**
    * Creates a TrackMapEntry for the track, if needed. Returns the index
    * of the TrackMapEntry or NoIndex if no entry is needed yet.
    */
-  uint32_t GetTrackMapEntry(const StreamBuffer::Track& aTrack,
-                            GraphTime aFrom);
+  size_t GetTrackMapEntry(const StreamBuffer::Track& aTrack,
+                          GraphTime aFrom);
 };
 
 }
 
 #endif /* MOZILLA_AUDIONODESTREAM_H_ */
--- a/content/media/EncodedBufferCache.cpp
+++ b/content/media/EncodedBufferCache.cpp
@@ -24,18 +24,18 @@ EncodedBufferCache::AppendBuffer(nsTArra
     if (!NS_FAILED(rv)) {
       mTempFileEnabled = true;
     }
   }
 
   if (mTempFileEnabled) {
     // has created temporary file, write buffer in it
     for (uint32_t i = 0; i < mEncodedBuffers.Length(); i++) {
-      int64_t amount = PR_Write(mFD, mEncodedBuffers.ElementAt(i).Elements(), mEncodedBuffers.ElementAt(i).Length());
-      if (amount <  mEncodedBuffers.ElementAt(i).Length()) {
+      int32_t amount = PR_Write(mFD, mEncodedBuffers.ElementAt(i).Elements(), mEncodedBuffers.ElementAt(i).Length());
+      if (amount < 0 || size_t(amount) < mEncodedBuffers.ElementAt(i).Length()) {
         NS_WARNING("Failed to write media cache block!");
       }
     }
     mEncodedBuffers.Clear();
   }
 
 }
 
--- a/content/media/MediaCache.cpp
+++ b/content/media/MediaCache.cpp
@@ -774,17 +774,17 @@ MediaCache::AppendMostReusableBlock(Bloc
 int32_t
 MediaCache::FindReusableBlock(TimeStamp aNow,
                                 MediaCacheStream* aForStream,
                                 int32_t aForStreamBlock,
                                 int32_t aMaxSearchBlockIndex)
 {
   mReentrantMonitor.AssertCurrentThreadIn();
 
-  uint32_t length = std::min(uint32_t(aMaxSearchBlockIndex), mIndex.Length());
+  uint32_t length = std::min(uint32_t(aMaxSearchBlockIndex), uint32_t(mIndex.Length()));
 
   if (aForStream && aForStreamBlock > 0 &&
       uint32_t(aForStreamBlock) <= aForStream->mBlocks.Length()) {
     int32_t prevCacheBlock = aForStream->mBlocks[aForStreamBlock - 1];
     if (prevCacheBlock >= 0) {
       uint32_t freeBlockScanEnd =
         std::min(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
       for (uint32_t i = prevCacheBlock; i < freeBlockScanEnd; ++i) {
--- a/content/media/mediasource/SourceBufferResource.h
+++ b/content/media/mediasource/SourceBufferResource.h
@@ -139,17 +139,17 @@ private:
 
     // Copies aCount bytes from aOffset in the queue into aDest.
     inline void CopyData(uint64_t aOffset, uint32_t aCount, char* aDest) {
       uint32_t offset = 0;
       uint32_t start = GetAtOffset(aOffset, &offset);
       uint32_t end = std::min(GetAtOffset(aOffset + aCount, nullptr) + 1, GetSize());
       for (uint32_t i = start; i < end; ++i) {
         ResourceItem* item = ResourceAt(i);
-        uint32_t bytes = std::min(aCount, item->mData.Length() - offset);
+        uint32_t bytes = std::min(aCount, uint32_t(item->mData.Length() - offset));
         if (bytes != 0) {
           memcpy(aDest, &item->mData[offset], bytes);
           offset = 0;
           aCount -= bytes;
           aDest += bytes;
         }
       }
     }
--- a/content/media/webaudio/AnalyserNode.cpp
+++ b/content/media/webaudio/AnalyserNode.cpp
@@ -167,63 +167,63 @@ void
 AnalyserNode::GetFloatFrequencyData(const Float32Array& aArray)
 {
   if (!FFTAnalysis()) {
     // Might fail to allocate memory
     return;
   }
 
   float* buffer = aArray.Data();
-  uint32_t length = std::min(aArray.Length(), mOutputBuffer.Length());
+  size_t length = std::min(size_t(aArray.Length()), mOutputBuffer.Length());
 
-  for (uint32_t i = 0; i < length; ++i) {
+  for (size_t i = 0; i < length; ++i) {
     buffer[i] = WebAudioUtils::ConvertLinearToDecibels(mOutputBuffer[i], mMinDecibels);
   }
 }
 
 void
 AnalyserNode::GetByteFrequencyData(const Uint8Array& aArray)
 {
   if (!FFTAnalysis()) {
     // Might fail to allocate memory
     return;
   }
 
   const double rangeScaleFactor = 1.0 / (mMaxDecibels - mMinDecibels);
 
   unsigned char* buffer = aArray.Data();
-  uint32_t length = std::min(aArray.Length(), mOutputBuffer.Length());
+  size_t length = std::min(size_t(aArray.Length()), mOutputBuffer.Length());
 
-  for (uint32_t i = 0; i < length; ++i) {
+  for (size_t i = 0; i < length; ++i) {
     const double decibels = WebAudioUtils::ConvertLinearToDecibels(mOutputBuffer[i], mMinDecibels);
     // scale down the value to the range of [0, UCHAR_MAX]
     const double scaled = std::max(0.0, std::min(double(UCHAR_MAX),
                                                  UCHAR_MAX * (decibels - mMinDecibels) * rangeScaleFactor));
     buffer[i] = static_cast<unsigned char>(scaled);
   }
 }
 
 void
 AnalyserNode::GetFloatTimeDomainData(const Float32Array& aArray)
 {
   float* buffer = aArray.Data();
-  uint32_t length = std::min(aArray.Length(), mBuffer.Length());
+  size_t length = std::min(size_t(aArray.Length()), mBuffer.Length());
 
-  for (uint32_t i = 0; i < length; ++i) {
+  for (size_t i = 0; i < length; ++i) {
     buffer[i] = mBuffer[(i + mWriteIndex) % mBuffer.Length()];;
   }
 }
 
 void
 AnalyserNode::GetByteTimeDomainData(const Uint8Array& aArray)
 {
   unsigned char* buffer = aArray.Data();
-  uint32_t length = std::min(aArray.Length(), mBuffer.Length());
+  size_t length = std::min(size_t(aArray.Length()), mBuffer.Length());
 
-  for (uint32_t i = 0; i < length; ++i) {
+  for (size_t i = 0; i < length; ++i) {
     const float value = mBuffer[(i + mWriteIndex) % mBuffer.Length()];
     // scale the value to the range of [0, UCHAR_MAX]
     const float scaled = std::max(0.0f, std::min(float(UCHAR_MAX),
                                                  128.0f * (value + 1.0f)));
     buffer[i] = static_cast<unsigned char>(scaled);
   }
 }
 
--- a/content/media/webaudio/AudioNode.cpp
+++ b/content/media/webaudio/AudioNode.cpp
@@ -104,33 +104,33 @@ AudioNode::SizeOfExcludingThis(MallocSiz
 
 size_t
 AudioNode::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
 {
   return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
 }
 
 template <class InputNode>
-static uint32_t
+static size_t
 FindIndexOfNode(const nsTArray<InputNode>& aInputNodes, const AudioNode* aNode)
 {
-  for (uint32_t i = 0; i < aInputNodes.Length(); ++i) {
+  for (size_t i = 0; i < aInputNodes.Length(); ++i) {
     if (aInputNodes[i].mInputNode == aNode) {
       return i;
     }
   }
   return nsTArray<InputNode>::NoIndex;
 }
 
 template <class InputNode>
-static uint32_t
+static size_t
 FindIndexOfNodeWithPorts(const nsTArray<InputNode>& aInputNodes, const AudioNode* aNode,
                          uint32_t aInputPort, uint32_t aOutputPort)
 {
-  for (uint32_t i = 0; i < aInputNodes.Length(); ++i) {
+  for (size_t i = 0; i < aInputNodes.Length(); ++i) {
     if (aInputNodes[i].mInputNode == aNode &&
         aInputNodes[i].mInputPort == aInputPort &&
         aInputNodes[i].mOutputPort == aOutputPort) {
       return i;
     }
   }
   return nsTArray<InputNode>::NoIndex;
 }
@@ -142,37 +142,37 @@ AudioNode::DisconnectFromGraph()
   // prematurely
   nsRefPtr<AudioNode> kungFuDeathGrip = this;
 
   // The idea here is that we remove connections one by one, and at each step
   // the graph is in a valid state.
 
   // Disconnect inputs. We don't need them anymore.
   while (!mInputNodes.IsEmpty()) {
-    uint32_t i = mInputNodes.Length() - 1;
+    size_t i = mInputNodes.Length() - 1;
     nsRefPtr<AudioNode> input = mInputNodes[i].mInputNode;
     mInputNodes.RemoveElementAt(i);
     input->mOutputNodes.RemoveElement(this);
   }
 
   while (!mOutputNodes.IsEmpty()) {
-    uint32_t i = mOutputNodes.Length() - 1;
+    size_t i = mOutputNodes.Length() - 1;
     nsRefPtr<AudioNode> output = mOutputNodes[i].forget();
     mOutputNodes.RemoveElementAt(i);
-    uint32_t inputIndex = FindIndexOfNode(output->mInputNodes, this);
+    size_t inputIndex = FindIndexOfNode(output->mInputNodes, this);
     // It doesn't matter which one we remove, since we're going to remove all
     // entries for this node anyway.
     output->mInputNodes.RemoveElementAt(inputIndex);
   }
 
   while (!mOutputParams.IsEmpty()) {
-    uint32_t i = mOutputParams.Length() - 1;
+    size_t i = mOutputParams.Length() - 1;
     nsRefPtr<AudioParam> output = mOutputParams[i].forget();
     mOutputParams.RemoveElementAt(i);
-    uint32_t inputIndex = FindIndexOfNode(output->InputNodes(), this);
+    size_t inputIndex = FindIndexOfNode(output->InputNodes(), this);
     // It doesn't matter which one we remove, since we're going to remove all
     // entries for this node anyway.
     output->RemoveInputNode(inputIndex);
   }
 
   DestroyMediaStream();
 }
 
--- a/content/media/webaudio/WebAudioUtils.cpp
+++ b/content/media/webaudio/WebAudioUtils.cpp
@@ -11,17 +11,17 @@
 #include "speex/speex_resampler.h"
 
 namespace mozilla {
 
 namespace dom {
 
 // 32 is the minimum required by the spec and matches what is used by blink.
 // The limit protects against large memory allocations.
-const uint32_t WebAudioUtils::MaxChannelCount = 32;
+const size_t WebAudioUtils::MaxChannelCount = 32;
 
 struct ConvertTimeToTickHelper
 {
   AudioNodeStream* mSourceStream;
   AudioNodeStream* mDestinationStream;
 
   static int64_t Convert(double aTime, void* aClosure)
   {
--- a/content/media/webaudio/WebAudioUtils.h
+++ b/content/media/webaudio/WebAudioUtils.h
@@ -20,17 +20,17 @@ namespace mozilla {
 
 class AudioNodeStream;
 
 namespace dom {
 
 class AudioParamTimeline;
 
 struct WebAudioUtils {
-  static const uint32_t MaxChannelCount;
+  static const size_t MaxChannelCount;
 
   static bool FuzzyEqual(float v1, float v2)
   {
     using namespace std;
     return fabsf(v1 - v2) < 1e-7f;
   }
   static bool FuzzyEqual(double v1, double v2)
   {
--- a/content/xul/document/src/XULDocument.cpp
+++ b/content/xul/document/src/XULDocument.cpp
@@ -1028,17 +1028,17 @@ XULDocument::AttributeChanged(nsIDocumen
                             attrSet != hasAttr || !value.Equals(currentValue);
                         nsDelayedBroadcastUpdate delayedUpdate(aElement,
                                                                listenerEl,
                                                                aAttribute,
                                                                value,
                                                                attrSet,
                                                                needsAttrChange);
 
-                        uint32_t index =
+                        size_t index =
                             mDelayedAttrChangeBroadcasts.IndexOf(delayedUpdate,
                                 0, nsDelayedBroadcastUpdate::Comparator());
                         if (index != mDelayedAttrChangeBroadcasts.NoIndex) {
                             if (mHandlingDelayedAttrChange) {
                                 NS_WARNING("Broadcasting loop!");
                                 continue;
                             }
                             mDelayedAttrChangeBroadcasts.RemoveElementAt(index);
--- a/dom/indexedDB/TransactionThreadPool.cpp
+++ b/dom/indexedDB/TransactionThreadPool.cpp
@@ -253,28 +253,28 @@ TransactionThreadPool::FinishTransaction
     }
 
     return;
   }
   TransactionInfo* info = transactionsInProgress.Get(aTransaction);
   NS_ASSERTION(info, "We've never heard of this transaction?!?");
 
   const nsTArray<nsString>& objectStoreNames = aTransaction->mObjectStoreNames;
-  for (uint32_t index = 0, count = objectStoreNames.Length(); index < count;
+  for (size_t index = 0, count = objectStoreNames.Length(); index < count;
        index++) {
     TransactionInfoPair* blockInfo =
       dbTransactionInfo->blockingTransactions.Get(objectStoreNames[index]);
     NS_ASSERTION(blockInfo, "Huh?");
 
     if (aTransaction->mMode == IDBTransaction::READ_WRITE &&
         blockInfo->lastBlockingReads == info) {
       blockInfo->lastBlockingReads = nullptr;
     }
 
-    uint32_t i = blockInfo->lastBlockingWrites.IndexOf(info);
+    size_t i = blockInfo->lastBlockingWrites.IndexOf(info);
     if (i != blockInfo->lastBlockingWrites.NoIndex) {
       blockInfo->lastBlockingWrites.RemoveElementAt(i);
     }
   }
 
   info->blocking.EnumerateEntries(MaybeUnblockTransaction, info);
 
   transactionsInProgress.Remove(aTransaction);
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -1450,17 +1450,17 @@ TabChild::RecvCacheFileDescriptor(const 
 
     mAppPackageFileDescriptorRecved = true;
 
     // aFileDescriptor may be invalid here, but the callback will choose how to
     // handle it.
 
     // First see if we already have a request for this path.
     const CachedFileDescriptorInfo search(aPath);
-    uint32_t index =
+    size_t index =
         mCachedFileDescriptorInfos.IndexOf(search, 0,
                                            search.PathOnlyComparator());
     if (index == mCachedFileDescriptorInfos.NoIndex) {
         // We haven't had any requests for this path yet. Assume that we will
         // in a little while and save the file descriptor here.
         mCachedFileDescriptorInfos.AppendElement(
             new CachedFileDescriptorInfo(aPath, aFileDescriptor));
         return true;
@@ -1502,17 +1502,17 @@ TabChild::GetCachedFileDescriptor(const 
 {
     MOZ_ASSERT(NS_IsMainThread());
     MOZ_ASSERT(!aPath.IsEmpty());
     MOZ_ASSERT(aCallback);
 
     // First see if we've already received a cached file descriptor for this
     // path.
     const CachedFileDescriptorInfo search(aPath);
-    uint32_t index =
+    size_t index =
         mCachedFileDescriptorInfos.IndexOf(search, 0,
                                            search.PathOnlyComparator());
     if (index == mCachedFileDescriptorInfos.NoIndex) {
         // We haven't received a file descriptor for this path yet. Assume that
         // we will in a little while and save the request here.
         if (!mAppPackageFileDescriptorRecved) {
           mCachedFileDescriptorInfos.AppendElement(
               new CachedFileDescriptorInfo(aPath, aCallback));
@@ -1558,17 +1558,17 @@ TabChild::CancelCachedFileDescriptorCall
     MOZ_ASSERT(aCallback);
 
     if (mAppPackageFileDescriptorRecved) {
       // Already received cached file descriptor for the app package. Nothing to do here.
       return;
     }
 
     const CachedFileDescriptorInfo search(aPath, aCallback);
-    uint32_t index =
+    size_t index =
         mCachedFileDescriptorInfos.IndexOf(search, 0,
                                            search.PathAndCallbackComparator());
     if (index == mCachedFileDescriptorInfos.NoIndex) {
         // Nothing to do here.
         return;
     }
 
     nsAutoPtr<CachedFileDescriptorInfo>& info =
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -3108,23 +3108,23 @@ WorkerPrivateParent<Derived>::BroadcastE
   }
 
   nsAutoTArray<WindowAction, 10> windowActions;
   nsresult rv;
 
   // First fire the error event at all SharedWorker objects. This may include
   // multiple objects in a single window as well as objects in different
   // windows.
-  for (uint32_t index = 0; index < sharedWorkers.Length(); index++) {
+  for (size_t index = 0; index < sharedWorkers.Length(); index++) {
     nsRefPtr<SharedWorker>& sharedWorker = sharedWorkers[index];
 
     // May be null.
     nsPIDOMWindow* window = sharedWorker->GetOwner();
 
-    uint32_t actionsIndex = windowActions.LastIndexOf(WindowAction(window));
+    size_t actionsIndex = windowActions.LastIndexOf(WindowAction(window));
 
     // Get the context for this window so that we can report errors correctly.
     JSContext* cx;
     rv = NS_OK;
 
     if (actionsIndex == windowActions.NoIndex) {
       nsIScriptContext* scx = sharedWorker->GetContextForEventHandlers(&rv);
       cx = (NS_SUCCEEDED(rv) && scx) ?
--- a/dom/xbl/XBLChildrenElement.cpp
+++ b/dom/xbl/XBLChildrenElement.cpp
@@ -174,33 +174,33 @@ nsAnonymousContentList::IndexOf(nsIConte
   NS_ASSERTION(!aContent->NodeInfo()->Equals(nsGkAtoms::children,
                                              kNameSpaceID_XBL),
                "Looking for insertion point");
 
   if (!mParent) {
     return -1;
   }
 
-  uint32_t index = 0;
+  size_t index = 0;
   for (nsIContent* child = mParent->GetFirstChild();
        child;
        child = child->GetNextSibling()) {
     if (child->NodeInfo()->Equals(nsGkAtoms::children, kNameSpaceID_XBL)) {
       XBLChildrenElement* point = static_cast<XBLChildrenElement*>(child);
       if (!point->mInsertedChildren.IsEmpty()) {
-        uint32_t insIndex = point->mInsertedChildren.IndexOf(aContent);
+        size_t insIndex = point->mInsertedChildren.IndexOf(aContent);
         if (insIndex != point->mInsertedChildren.NoIndex) {
           return index + insIndex;
         }
         index += point->mInsertedChildren.Length();
       }
       else {
         int32_t insIndex = point->IndexOf(aContent);
         if (insIndex != -1) {
-          return index + (uint32_t)insIndex;
+          return index + (size_t)insIndex;
         }
         index += point->GetChildCount();
       }
     }
     else {
       if (child == aContent) {
         return index;
       }
--- a/dom/xbl/nsBindingManager.cpp
+++ b/dom/xbl/nsBindingManager.cpp
@@ -329,17 +329,17 @@ nsBindingManager::LoadBindingDocument(ns
   return NS_OK;
 }
 
 void
 nsBindingManager::RemoveFromAttachedQueue(nsXBLBinding* aBinding)
 {
   // Don't remove items here as that could mess up an executing
   // ProcessAttachedQueue. Instead, null the entry in the queue.
-  uint32_t index = mAttachedStack.IndexOf(aBinding);
+  size_t index = mAttachedStack.IndexOf(aBinding);
   if (index != mAttachedStack.NoIndex) {
     mAttachedStack[index] = nullptr;
   }
 }
 
 nsresult
 nsBindingManager::AddToAttachedQueue(nsXBLBinding* aBinding)
 {
@@ -835,17 +835,17 @@ nsBindingManager::AppendAllSheets(nsTArr
     mBoundContentSet->EnumerateEntries(EnumAppendAllSheets, &aArray);
   }
 }
 
 static void
 InsertAppendedContent(XBLChildrenElement* aPoint,
                       nsIContent* aFirstNewContent)
 {
-  uint32_t insertionIndex;
+  size_t insertionIndex;
   if (nsIContent* prevSibling = aFirstNewContent->GetPreviousSibling()) {
     // If we have a previous sibling, then it must already be in aPoint. Find
     // it and insert after it.
     insertionIndex = aPoint->IndexOfInsertedChild(prevSibling);
     MOZ_ASSERT(insertionIndex != aPoint->NoIndex);
 
     // Our insertion index is one after our previous sibling's index.
     ++insertionIndex;
@@ -1078,24 +1078,24 @@ nsBindingManager::HandleChildInsertion(n
     if (!point) {
       break;
     }
 
     // Insert the child into the proper insertion point.
     // TODO If there were multiple insertion points, this approximation can be
     // wrong. We need to re-run the distribution algorithm. In the meantime,
     // this should work well enough.
-    uint32_t index = aAppend ? point->mInsertedChildren.Length() : 0;
+    size_t index = aAppend ? point->mInsertedChildren.Length() : 0;
     for (nsIContent* currentSibling = aChild->GetPreviousSibling();
          currentSibling;
          currentSibling = currentSibling->GetPreviousSibling()) {
       // If we find one of our previous siblings in the insertion point, the
       // index following it is the correct insertion point. Otherwise, we guess
       // based on whether we're appending or inserting.
-      uint32_t pointIndex = point->IndexOfInsertedChild(currentSibling);
+      size_t pointIndex = point->IndexOfInsertedChild(currentSibling);
       if (pointIndex != point->NoIndex) {
         index = pointIndex + 1;
         break;
       }
     }
 
     point->InsertInsertedChildAt(aChild, index);
 
--- a/dom/xslt/base/txExpandedNameMap.cpp
+++ b/dom/xslt/base/txExpandedNameMap.cpp
@@ -21,17 +21,17 @@ class txMapItemComparator
  * returned
  * @param  aKey   key for item to add
  * @param  aValue value of item to add
  * @return errorcode
  */
 nsresult txExpandedNameMap_base::addItem(const txExpandedName& aKey,
                                          void* aValue)
 {
-    uint32_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
+    size_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
     if (pos != mItems.NoIndex) {
         return NS_ERROR_XSLT_ALREADY_SET;
     }
 
     MapItem* item = mItems.AppendElement();
     NS_ENSURE_TRUE(item, NS_ERROR_OUT_OF_MEMORY);
 
     item->mNamespaceID = aKey.mNamespaceID;
@@ -48,21 +48,20 @@ nsresult txExpandedNameMap_base::addItem
  * @param  aValue value of item to set
  * @return errorcode
  */
 nsresult txExpandedNameMap_base::setItem(const txExpandedName& aKey,
                                          void* aValue,
                                          void** aOldValue)
 {
     *aOldValue = nullptr;
-    uint32_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
+    size_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
     if (pos != mItems.NoIndex) {
         *aOldValue = mItems[pos].mValue;
         mItems[pos].mValue = aValue;
-        
         return NS_OK;
     }
 
     MapItem* item = mItems.AppendElement();
     NS_ENSURE_TRUE(item, NS_ERROR_OUT_OF_MEMORY);
 
     item->mNamespaceID = aKey.mNamespaceID;
     item->mLocalName = aKey.mLocalName;
@@ -73,33 +72,33 @@ nsresult txExpandedNameMap_base::setItem
 
 /**
  * Gets an item
  * @param  aKey  key for item to get
  * @return item with specified key, or null if no such item exists
  */
 void* txExpandedNameMap_base::getItem(const txExpandedName& aKey) const
 {
-    uint32_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
+    size_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
     if (pos != mItems.NoIndex) {
         return mItems[pos].mValue;
     }
 
     return nullptr;
 }
 
 /**
  * Removes an item, deleting it if the map owns the values
  * @param  aKey  key for item to remove
  * @return item with specified key, or null if it has been deleted
  *         or no such item exists
  */
 void* txExpandedNameMap_base::removeItem(const txExpandedName& aKey)
 {
     void* value = nullptr;
-    uint32_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
+    size_t pos = mItems.IndexOf(aKey, 0, txMapItemComparator());
     if (pos != mItems.NoIndex) {
         value = mItems[pos].mValue;
         mItems.RemoveElementAt(pos);
     }
 
     return value;
 }
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -8140,18 +8140,18 @@ nsHTMLEditRules::RemoveEmptyNodes()
   nsTArray<nsCOMPtr<nsINode> > skipList;
 
   // check for empty nodes
   while (!iter->IsDone()) {
     nsINode* node = iter->GetCurrentNode();
     NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);
 
     nsINode* parent = node->GetParentNode();
-    
-    uint32_t idx = skipList.IndexOf(node);
+
+    size_t idx = skipList.IndexOf(node);
     if (idx != skipList.NoIndex) {
       // this node is on our skip list.  Skip processing for this node, 
       // and replace its value in the skip list with the value of its parent
       skipList[idx] = parent;
     } else {
       bool bIsCandidate = false;
       bool bIsEmptyNode = false;
       bool bIsMailCite = false;
--- a/editor/libeditor/html/nsHTMLEditor.cpp
+++ b/editor/libeditor/html/nsHTMLEditor.cpp
@@ -3007,17 +3007,17 @@ nsHTMLEditor::AddNewStyleSheetToList(con
 
   return mStyleSheets.AppendElement(aStyleSheet) ? NS_OK : NS_ERROR_UNEXPECTED;
 }
 
 nsresult
 nsHTMLEditor::RemoveStyleSheetFromList(const nsAString &aURL)
 {
   // is it already in the list?
-  uint32_t foundIndex;
+  size_t foundIndex;
   foundIndex = mStyleSheetURLs.IndexOf(aURL);
   if (foundIndex == mStyleSheetURLs.NoIndex)
     return NS_ERROR_FAILURE;
 
   // Attempt both removals; if one fails there's not much we can do.
   mStyleSheets.RemoveElementAt(foundIndex);
   mStyleSheetURLs.RemoveElementAt(foundIndex);
 
@@ -3027,17 +3027,17 @@ nsHTMLEditor::RemoveStyleSheetFromList(c
 NS_IMETHODIMP
 nsHTMLEditor::GetStyleSheetForURL(const nsAString &aURL,
                                   nsCSSStyleSheet **aStyleSheet)
 {
   NS_ENSURE_ARG_POINTER(aStyleSheet);
   *aStyleSheet = 0;
 
   // is it already in the list?
-  uint32_t foundIndex;
+  size_t foundIndex;
   foundIndex = mStyleSheetURLs.IndexOf(aURL);
   if (foundIndex == mStyleSheetURLs.NoIndex)
     return NS_OK; //No sheet -- don't fail!
 
   *aStyleSheet = mStyleSheets[foundIndex];
   NS_ENSURE_TRUE(*aStyleSheet, NS_ERROR_FAILURE);
 
   NS_ADDREF(*aStyleSheet);
--- a/gfx/thebes/gfxXlibSurface.cpp
+++ b/gfx/thebes/gfxXlibSurface.cpp
@@ -399,17 +399,17 @@ DisplayTable::GetColormapAndVisual(Scree
     if (!aVisual || aVisual->c_class != TrueColor)
         return false;
 
     if (!sDisplayTable) {
         sDisplayTable = new DisplayTable();
     }
 
     nsTArray<DisplayInfo>* displays = &sDisplayTable->mDisplays;
-    uint32_t d = displays->IndexOf(display, 0, FindDisplay());
+    size_t d = displays->IndexOf(display, 0, FindDisplay());
 
     if (d == displays->NoIndex) {
         d = displays->Length();
         // Register for notification of display closing, when this info
         // becomes invalid.
         XExtCodes *codes = XAddExtension(display);
         if (!codes)
             return false;
--- a/image/src/RasterImage.cpp
+++ b/image/src/RasterImage.cpp
@@ -2856,17 +2856,17 @@ RasterImage::RequestDiscard()
     ForceDiscard();
   }
 
   return NS_OK;
 }
 
 // Flushes up to aMaxBytes to the decoder.
 nsresult
-RasterImage::DecodeSomeData(uint32_t aMaxBytes, DecodeStrategy aStrategy)
+RasterImage::DecodeSomeData(size_t aMaxBytes, DecodeStrategy aStrategy)
 {
   // We should have a decoder if we get here
   NS_ABORT_IF_FALSE(mDecoder, "trying to decode without decoder!");
 
   mDecodingMonitor.AssertCurrentThreadIn();
 
   // First, if we've just been called because we allocated a frame on the main
   // thread, let the decoder deal with the data it set aside at that time by
@@ -2881,18 +2881,18 @@ RasterImage::DecodeSomeData(uint32_t aMa
 
   // If we have nothing else to decode, return
   if (mBytesDecoded == mSourceData.Length())
     return NS_OK;
 
   MOZ_ASSERT(mBytesDecoded < mSourceData.Length());
 
   // write the proper amount of data
-  uint32_t bytesToDecode = std::min(aMaxBytes,
-                                    mSourceData.Length() - mBytesDecoded);
+  size_t bytesToDecode = std::min(aMaxBytes,
+                                  mSourceData.Length() - mBytesDecoded);
   nsresult rv = WriteToDecoder(mSourceData.Elements() + mBytesDecoded,
                                bytesToDecode,
                                aStrategy);
 
   return rv;
 }
 
 // There are various indicators that tell us we're finished with the decode
@@ -3379,29 +3379,29 @@ RasterImage::DecodePool::DecodeJob::Run(
   // still needs a new frame, we can't do anything. Wait until the
   // FrameNeededWorker enqueues another frame.
   if (mImage->mDecoder->NeedsNewFrame()) {
     return NS_OK;
   }
 
   mRequest->mRequestStatus = DecodeRequest::REQUEST_ACTIVE;
 
-  uint32_t oldByteCount = mImage->mBytesDecoded;
+  size_t oldByteCount = mImage->mBytesDecoded;
 
   DecodeType type = DECODE_TYPE_UNTIL_DONE_BYTES;
 
   // Multithreaded decoding can be disabled. If we've done so, we don't want to
   // monopolize the main thread, and will allow a timeout in DecodeSomeOfImage.
   if (NS_IsMainThread()) {
     type = DECODE_TYPE_UNTIL_TIME;
   }
 
   DecodePool::Singleton()->DecodeSomeOfImage(mImage, DECODE_ASYNC, type, mRequest->mBytesToDecode);
 
-  uint32_t bytesDecoded = mImage->mBytesDecoded - oldByteCount;
+  size_t bytesDecoded = mImage->mBytesDecoded - oldByteCount;
 
   mRequest->mRequestStatus = DecodeRequest::REQUEST_WORK_DONE;
 
   // If the decoder needs a new frame, enqueue an event to get it; that event
   // will enqueue another decode request when it's done.
   if (mImage->mDecoder && mImage->mDecoder->NeedsNewFrame()) {
     FrameNeededWorker::GetNewFrame(mImage);
   }
--- a/image/src/RasterImage.h
+++ b/image/src/RasterImage.h
@@ -364,17 +364,17 @@ private:
     NS_INLINE_DECL_THREADSAFE_REFCOUNTING(DecodeRequest)
 
     // The status tracker that is associated with a given decode request, to
     // ensure their lifetimes are linked.
     nsRefPtr<imgStatusTracker> mStatusTracker;
 
     RasterImage* mImage;
 
-    uint32_t mBytesToDecode;
+    size_t mBytesToDecode;
 
     enum DecodeRequestStatus
     {
       REQUEST_INACTIVE,
       REQUEST_PENDING,
       REQUEST_ACTIVE,
       REQUEST_WORK_DONE,
       REQUEST_STOPPED
@@ -676,17 +676,17 @@ private: // data
   // BEGIN LOCKED MEMBER VARIABLES
   mozilla::ReentrantMonitor  mDecodingMonitor;
 
   FallibleTArray<char>       mSourceData;
 
   // Decoder and friends
   nsRefPtr<Decoder>          mDecoder;
   nsRefPtr<DecodeRequest>    mDecodeRequest;
-  uint32_t                   mBytesDecoded;
+  size_t                     mBytesDecoded;
 
   bool                       mInDecoder;
   // END LOCKED MEMBER VARIABLES
 
   // Notification state. Used to avoid recursive notifications.
   ImageStatusDiff            mStatusDiff;
   bool                       mNotifying:1;
 
@@ -724,17 +724,17 @@ private: // data
   nsresult RequestDecodeIfNeeded(nsresult aStatus,
                                  eShutdownIntent aIntent,
                                  bool aDone,
                                  bool aWasSize);
   nsresult WantDecodedFrames();
   nsresult SyncDecode();
   nsresult InitDecoder(bool aDoSizeDecode);
   nsresult WriteToDecoder(const char *aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
-  nsresult DecodeSomeData(uint32_t aMaxBytes, DecodeStrategy aStrategy);
+  nsresult DecodeSomeData(size_t aMaxBytes, DecodeStrategy aStrategy);
   bool     IsDecodeFinished();
   TimeStamp mDrawStartTime;
 
   inline bool CanQualityScale(const gfx::Size& scale);
   inline bool CanScale(GraphicsFilter aFilter, gfx::Size aScale, uint32_t aFlags);
 
   struct ScaleResult
   {
--- a/layout/base/DisplayItemClip.cpp
+++ b/layout/base/DisplayItemClip.cpp
@@ -311,32 +311,32 @@ DisplayItemClip::AddOffsetAndComputeDiff
     }
   }
 }
 
 uint32_t
 DisplayItemClip::GetCommonRoundedRectCount(const DisplayItemClip& aOther,
                                            uint32_t aMax) const
 {
-  uint32_t end = std::min(std::min(mRoundedClipRects.Length(), aMax),
+  uint32_t end = std::min(std::min(mRoundedClipRects.Length(), size_t(aMax)),
                           aOther.mRoundedClipRects.Length());
   uint32_t clipCount = 0;
   for (; clipCount < end; ++clipCount) {
     if (mRoundedClipRects[clipCount] !=
         aOther.mRoundedClipRects[clipCount]) {
       return clipCount;
     }
   }
   return clipCount;
 }
 
 void
 DisplayItemClip::AppendRoundedRects(nsTArray<RoundedRect>* aArray, uint32_t aCount) const
 {
-  uint32_t count = std::min(mRoundedClipRects.Length(), aCount);
+  uint32_t count = std::min(mRoundedClipRects.Length(), size_t(aCount));
   for (uint32_t i = 0; i < count; ++i) {
     *aArray->AppendElement() = mRoundedClipRects[i];
   }
 }
 
 bool
 DisplayItemClip::ComputeRegionInClips(DisplayItemClip* aOldClip,
                                       const nsPoint& aShift,
--- a/layout/generic/nsTextFrame.cpp
+++ b/layout/generic/nsTextFrame.cpp
@@ -2112,17 +2112,17 @@ BuildTextRunsScanner::BuildTextRunForFra
     NS_ASSERTION(iter.GetSkippedOffset() == transformedLength,
                  "We didn't cover all the characters in the text run!");
   }
 
   gfxTextRun* textRun;
   gfxTextRunFactory::Parameters params =
       { mContext, finalUserData, &skipChars,
         textBreakPointsAfterTransform.Elements(),
-        textBreakPointsAfterTransform.Length(),
+        uint32_t(textBreakPointsAfterTransform.Length()),
         int32_t(firstFrame->PresContext()->AppUnitsPerDevPixel())};
 
   if (mDoubleByteText) {
     const char16_t* text = static_cast<const char16_t*>(textPtr);
     if (transformingFactory) {
       textRun = transformingFactory->MakeTextRun(text, transformedLength, &params,
                                                  fontGroup, textFlags, styles.Elements());
       if (textRun) {
--- a/layout/style/nsTransitionManager.cpp
+++ b/layout/style/nsTransitionManager.cpp
@@ -569,22 +569,22 @@ nsTransitionManager::ConsiderStartingTra
     haveChange &&
     // Check that we can interpolate between these values
     // (If this is ever a performance problem, we could add a
     // CanInterpolate method, but it seems fine for now.)
     nsStyleAnimation::Interpolate(aProperty, startValue, endValue,
                                   0.5, dummyValue);
 
   bool haveCurrentTransition = false;
-  uint32_t currentIndex = nsTArray<ElementPropertyTransition>::NoIndex;
+  size_t currentIndex = nsTArray<ElementPropertyTransition>::NoIndex;
   const ElementPropertyTransition *oldPT = nullptr;
   if (aElementTransitions) {
     nsTArray<ElementPropertyTransition> &pts =
       aElementTransitions->mPropertyTransitions;
-    for (uint32_t i = 0, i_end = pts.Length(); i < i_end; ++i) {
+    for (size_t i = 0, i_end = pts.Length(); i < i_end; ++i) {
       MOZ_ASSERT(pts[i].mProperties.Length() == 1,
                  "Should have one animation property for a transition");
       if (pts[i].mProperties[0].mProperty == aProperty) {
         haveCurrentTransition = true;
         currentIndex = i;
         oldPT = &aElementTransitions->mPropertyTransitions[currentIndex];
         break;
       }
--- a/layout/tables/nsCellMap.cpp
+++ b/layout/tables/nsCellMap.cpp
@@ -713,17 +713,17 @@ nsTableCellMap::Dump(char* aString) cons
   printf("***** START TABLE CELL MAP DUMP ***** %p\n", (void*)this);
   // output col info
   int32_t colCount = mCols.Length();
   printf ("cols array orig/span-> %p", (void*)this);
   for (int32_t colX = 0; colX < colCount; colX++) {
     const nsColInfo& colInfo = mCols.ElementAt(colX);
     printf ("%d=%d/%d ", colX, colInfo.mNumCellsOrig, colInfo.mNumCellsSpan);
   }
-  printf(" cols in cache %d\n", mTableFrame.GetColCache().Length());
+  printf(" cols in cache %d\n", int(mTableFrame.GetColCache().Length()));
   nsCellMap* cellMap = mFirstMap;
   while (cellMap) {
     cellMap->Dump(nullptr != mBCInfo);
     cellMap = cellMap->GetNextSibling();
   }
   if (nullptr != mBCInfo) {
     printf("***** bottom borders *****\n");
     nscoord       size;
@@ -2178,17 +2178,17 @@ void nsCellMap::ShrinkWithoutCell(nsTabl
 
   // remove the deleted cell and cellData entries for it
   for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
     CellDataArray& row = mRows[rowX];
 
     // endIndexForRow points at the first slot we don't want to clean up.  This
     // makes the aColIndex == 0 case work right with our unsigned int colX.
     NS_ASSERTION(endColIndex + 1 <= row.Length(), "span beyond the row size!");
-    uint32_t endIndexForRow = std::min(endColIndex + 1, row.Length());
+    uint32_t endIndexForRow = std::min(endColIndex + 1, uint32_t(row.Length()));
 
     // Since endIndexForRow <= row.Length(), enough to compare aColIndex to it.
     if (uint32_t(aColIndex) < endIndexForRow) {
       for (colX = endIndexForRow; colX > uint32_t(aColIndex); colX--) {
         DestroyCellData(row[colX-1]);
       }
       row.RemoveElementsAt(aColIndex, endIndexForRow - aColIndex);
     }
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -2924,17 +2924,17 @@ nsTableFrame::ReflowChildren(nsTableRefl
     if (tfoot) {
       rv = SetupHeaderFooterChild(aReflowState, tfoot, &footerHeight);
       if (NS_FAILED(rv))
         return rv;
     }
   }
    // if the child is a tbody in paginated mode reduce the height by a repeated footer
   bool allowRepeatedFooter = false;
-  for (uint32_t childX = 0; childX < rowGroups.Length(); childX++) {
+  for (size_t childX = 0; childX < rowGroups.Length(); childX++) {
     nsIFrame* kidFrame = rowGroups[childX];
     // Get the frame state bits
     // See if we should only reflow the dirty child frames
     if (reflowAllKids ||
         NS_SUBTREE_DIRTY(kidFrame) ||
         (aReflowState.reflowState.mFlags.mSpecialHeightReflow &&
          (isPaginated || (kidFrame->GetStateBits() &
                           NS_FRAME_CONTAINS_RELATIVE_HEIGHT)))) {
--- a/layout/xul/nsMenuBarFrame.cpp
+++ b/layout/xul/nsMenuBarFrame.cpp
@@ -190,33 +190,33 @@ nsMenuBarFrame::FindMenuWithShortcut(nsI
   // Enumerate over our list of frames.
   nsIFrame* immediateParent = nullptr;
   GetInsertionPoint(PresContext()->PresShell(), this, nullptr, &immediateParent);
   if (!immediateParent)
     immediateParent = this;
 
   // Find a most preferred accesskey which should be returned.
   nsIFrame* foundMenu = nullptr;
-  uint32_t foundIndex = accessKeys.NoIndex;
+  size_t foundIndex = accessKeys.NoIndex;
   nsIFrame* currFrame = immediateParent->GetFirstPrincipalChild();
 
   while (currFrame) {
     nsIContent* current = currFrame->GetContent();
 
     // See if it's a menu item.
     if (nsXULPopupManager::IsValidMenuItem(PresContext(), current, false)) {
       // Get the shortcut attribute.
       nsAutoString shortcutKey;
       current->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, shortcutKey);
       if (!shortcutKey.IsEmpty()) {
         ToLowerCase(shortcutKey);
         const char16_t* start = shortcutKey.BeginReading();
         const char16_t* end = shortcutKey.EndReading();
         uint32_t ch = UTF16CharEnumerator::NextChar(&start, end);
-        uint32_t index = accessKeys.IndexOf(ch);
+        size_t index = accessKeys.IndexOf(ch);
         if (index != accessKeys.NoIndex &&
             (foundIndex == accessKeys.NoIndex || index < foundIndex)) {
           foundMenu = currFrame;
           foundIndex = index;
         }
       }
     }
     currFrame = currFrame->GetNextSibling();
--- a/modules/libjar/nsJARProtocolHandler.h
+++ b/modules/libjar/nsJARProtocolHandler.h
@@ -10,20 +10,20 @@
 #include "nsIProtocolHandler.h"
 #include "nsIJARURI.h"
 #include "nsIZipReader.h"
 #include "nsIMIMEService.h"
 #include "nsWeakReference.h"
 #include "nsCOMPtr.h"
 #include "nsClassHashtable.h"
 #include "nsHashKeys.h"
+#include "nsTArrayForwardDeclare.h"
 
 class nsIHashable;
 class nsIRemoteOpenFileListener;
-template<class E, uint32_t N> class nsAutoTArray;
 
 class nsJARProtocolHandler : public nsIJARProtocolHandler
                            , public nsSupportsWeakReference
 {
     typedef nsAutoTArray<nsCOMPtr<nsIRemoteOpenFileListener>, 5>
             RemoteFileListenerArray;
 
 public:
--- a/toolkit/components/places/nsMaybeWeakPtr.cpp
+++ b/toolkit/components/places/nsMaybeWeakPtr.cpp
@@ -50,17 +50,17 @@ NS_AppendWeakElementBase(isupports_array
   }
   return NS_OK;
 }
 
 nsresult
 NS_RemoveWeakElementBase(isupports_array_type *aArray,
                          nsISupports *aElement)
 {
-  uint32_t index = aArray->IndexOf(aElement);
+  size_t index = aArray->IndexOf(aElement);
   if (index != aArray->NoIndex) {
     aArray->RemoveElementAt(index);
     return NS_OK;
   }
 
   // Don't use do_GetWeakReference; it should only be called if we know
   // the object supports weak references.
   nsCOMPtr<nsISupportsWeakReference> supWeakRef = do_QueryInterface(aElement);
--- a/toolkit/components/url-classifier/ChunkSet.cpp
+++ b/toolkit/components/url-classifier/ChunkSet.cpp
@@ -34,17 +34,17 @@ ChunkSet::Serialize(nsACString& aChunkSt
   }
 
   return NS_OK;
 }
 
 nsresult
 ChunkSet::Set(uint32_t aChunk)
 {
-  uint32_t idx = mChunks.BinaryIndexOf(aChunk);
+  size_t idx = mChunks.BinaryIndexOf(aChunk);
   if (idx == nsTArray<uint32_t>::NoIndex) {
     mChunks.InsertElementSorted(aChunk);
   }
   return NS_OK;
 }
 
 nsresult
 ChunkSet::Unset(uint32_t aChunk)
--- a/toolkit/components/url-classifier/Classifier.cpp
+++ b/toolkit/components/url-classifier/Classifier.cpp
@@ -732,26 +732,26 @@ Classifier::ReadNoiseEntries(const Prefi
   if (!cache) {
     return NS_ERROR_FAILURE;
   }
 
   nsTArray<uint32_t> prefixes;
   nsresult rv = cache->GetPrefixes(&prefixes);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  uint32_t idx = prefixes.BinaryIndexOf(aPrefix.ToUint32());
+  size_t idx = prefixes.BinaryIndexOf(aPrefix.ToUint32());
 
   if (idx == nsTArray<uint32_t>::NoIndex) {
     NS_WARNING("Could not find prefix in PrefixSet during noise lookup");
     return NS_ERROR_FAILURE;
   }
 
   idx -= idx % aCount;
 
-  for (uint32_t i = 0; (i < aCount) && ((idx+i) < prefixes.Length()); i++) {
+  for (size_t i = 0; (i < aCount) && ((idx+i) < prefixes.Length()); i++) {
     Prefix newPref;
     newPref.FromUint32(prefixes[idx+i]);
     if (newPref != aPrefix) {
       aNoiseEntries->AppendElement(newPref);
     }
   }
 
   return NS_OK;
--- a/widget/xpwidgets/nsTransferable.cpp
+++ b/widget/xpwidgets/nsTransferable.cpp
@@ -32,20 +32,20 @@ Notes to self:
 #include "nsIOutputStream.h"
 #include "nsIInputStream.h"
 #include "nsIFile.h"
 #include "nsILoadContext.h"
 #include "nsAutoPtr.h"
 
 NS_IMPL_ISUPPORTS(nsTransferable, nsITransferable)
 
-uint32_t GetDataForFlavor (const nsTArray<DataStruct>& aArray,
+size_t GetDataForFlavor (const nsTArray<DataStruct>& aArray,
                            const char* aDataFlavor)
 {
-  for (uint32_t i = 0 ; i < aArray.Length () ; ++i) {
+  for (size_t i = 0 ; i < aArray.Length () ; ++i) {
     if (aArray[i].GetFlavor().Equals (aDataFlavor))
       return i;
   }
 
   return aArray.NoIndex;
 }
 
 //-------------------------------------------------------------------------
@@ -537,17 +537,17 @@ nsTransferable::FlavorsTransferableCanIm
   if ( converter ) {
     nsCOMPtr<nsISupportsArray> convertedList;
     converter->GetInputDataFlavors(getter_AddRefs(convertedList));
 
     if ( convertedList ) {
       uint32_t importListLen;
       convertedList->Count(&importListLen);
 
-      for ( uint32_t i=0; i < importListLen; ++i ) {
+      for (uint32_t i = 0; i < importListLen; ++i ) {
         nsCOMPtr<nsISupports> genericFlavor;
         convertedList->GetElementAt ( i, getter_AddRefs(genericFlavor) );
 
         nsCOMPtr<nsISupportsCString> flavorWrapper ( do_QueryInterface (genericFlavor) );
         nsAutoCString flavorStr;
         flavorWrapper->GetData( flavorStr );
 
         if (GetDataForFlavor (mDataArray, flavorStr.get())
--- a/xpcom/ds/nsExpirationTracker.h
+++ b/xpcom/ds/nsExpirationTracker.h
@@ -172,17 +172,17 @@ template <class T, uint32_t K> class nsE
       // The following is rather tricky. We have to cope with objects being
       // removed from this generation either because of a call to RemoveObject
       // (or indirectly via MarkUsed) inside NotifyExpired. Fortunately no
       // objects can be added to this generation because it's not the newest
       // generation. We depend on the fact that RemoveObject can only cause
       // the indexes of objects in this generation to *decrease*, not increase.
       // So if we start from the end and work our way backwards we are guaranteed
       // to see each object at least once.
-      uint32_t index = generation.Length();
+      size_t index = generation.Length();
       for (;;) {
         // Objects could have been removed so index could be outside
         // the array
         index = XPCOM_MIN(index, generation.Length());
         if (index == 0)
           break;
         --index;
         NotifyExpired(generation[index]);
--- a/xpcom/glue/DeadlockDetector.h
+++ b/xpcom/glue/DeadlockDetector.h
@@ -176,19 +176,17 @@ public:
         }
     };
     typedef nsTArray<ResourceAcquisition> ResourceAcquisitionArray;
 
 private:
     typedef nsTArray<PLHashEntry*> HashEntryArray;
     typedef typename HashEntryArray::index_type index_type;
     typedef typename HashEntryArray::size_type size_type;
-    enum {
-        NoIndex = HashEntryArray::NoIndex
-    };
+    static const HashEntryArray::index_type NoIndex = HashEntryArray::NoIndex;
 
     /**
      * Value type for the ordering table.  Contains the other
      * resources on which an ordering constraint |key < other|
      * exists.  The catch is that we also store the calling context at
      * which the other resource was acquired; this improves the
      * quality of error messages when potential deadlock is detected.
      */
--- a/xpcom/glue/nsTArray-inl.h
+++ b/xpcom/glue/nsTArray-inl.h
@@ -90,30 +90,33 @@ bool nsTArray_base<Alloc, Copy>::UsesAut
   ptrdiff_t diff = reinterpret_cast<const char*>(GetAutoArrayBuffer(8)) -
                    reinterpret_cast<const char*>(GetAutoArrayBuffer(4));
   NS_ABORT_IF_FALSE(diff >= 0 && diff <= 4, "GetAutoArrayBuffer doesn't do what we expect.");
 #endif
 
   return mHdr == GetAutoArrayBuffer(4) || mHdr == GetAutoArrayBuffer(8);
 }
 
+// defined in nsTArray.cpp
+bool
+IsTwiceTheRequiredBytesRepresentableAsUint32(size_t capacity, size_t elemSize);
 
 template<class Alloc, class Copy>
 typename Alloc::ResultTypeProxy
 nsTArray_base<Alloc, Copy>::EnsureCapacity(size_type capacity, size_type elemSize) {
   // This should be the most common case so test this first
   if (capacity <= mHdr->mCapacity)
     return Alloc::SuccessResult();
 
   // If the requested memory allocation exceeds size_type(-1)/2, then
   // our doubling algorithm may not be able to allocate it.
-  // Additionally we couldn't fit in the Header::mCapacity
-  // member. Just bail out in cases like that.  We don't want to be
-  // allocating 2 GB+ arrays anyway.
-  if ((uint64_t)capacity * elemSize > size_type(-1)/2) {
+  // Additionally, if it exceeds uint32_t(-1) then we couldn't fit in the
+  // Header::mCapacity member. Just bail out in cases like that.  We don't want
+  // to be allocating 2 GB+ arrays anyway.
+  if (!IsTwiceTheRequiredBytesRepresentableAsUint32(capacity, elemSize)) {
     Alloc::SizeTooBig((size_t)capacity * elemSize);
     return Alloc::FailureResult();
   }
 
   if (mHdr == EmptyHdr()) {
     // Malloc() new data
     Header *header = static_cast<Header*>
                      (Alloc::Malloc(sizeof(Header) + capacity * elemSize));
@@ -125,21 +128,21 @@ nsTArray_base<Alloc, Copy>::EnsureCapaci
     mHdr = header;
 
     return Alloc::SuccessResult();
   }
 
   // We increase our capacity so |capacity * elemSize + sizeof(Header)| is the
   // next power of two, if this value is less than pageSize bytes, or otherwise
   // so it's the next multiple of pageSize.
-  const uint32_t pageSizeBytes = 12;
-  const uint32_t pageSize = 1 << pageSizeBytes;
+  const size_t pageSizeBytes = 12;
+  const size_t pageSize = 1 << pageSizeBytes;
 
-  uint32_t minBytes = capacity * elemSize + sizeof(Header);
-  uint32_t bytesToAlloc;
+  size_t minBytes = capacity * elemSize + sizeof(Header);
+  size_t bytesToAlloc;
   if (minBytes >= pageSize) {
     // Round up to the next multiple of pageSize.
     bytesToAlloc = pageSize * ((minBytes + pageSize - 1) / pageSize);
   }
   else {
     // Round up to the next power of two.  See
     // http://graphics.stanford.edu/~seander/bithacks.html
     bytesToAlloc = minBytes - 1;
@@ -168,17 +171,17 @@ nsTArray_base<Alloc, Copy>::EnsureCapaci
   } else {
     // Realloc() existing data
     header = static_cast<Header*>(Alloc::Realloc(mHdr, bytesToAlloc));
     if (!header)
       return Alloc::FailureResult();
   }
 
   // How many elements can we fit in bytesToAlloc?
-  uint32_t newCapacity = (bytesToAlloc - sizeof(Header)) / elemSize;
+  size_t newCapacity = (bytesToAlloc - sizeof(Header)) / elemSize;
   MOZ_ASSERT(newCapacity >= capacity, "Didn't enlarge the array enough!");
   header->mCapacity = newCapacity;
 
   mHdr = header;
 
   return Alloc::SuccessResult();
 }
 
--- a/xpcom/glue/nsTArray.cpp
+++ b/xpcom/glue/nsTArray.cpp
@@ -3,10 +3,17 @@
 /* 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 <string.h>
 #include "nsTArray.h"
 #include "nsXPCOM.h"
 #include "nsDebug.h"
+#include "mozilla/CheckedInt.h"
 
 nsTArrayHeader nsTArrayHeader::sEmptyHdr = { 0, 0, 0 };
+
+bool
+IsTwiceTheRequiredBytesRepresentableAsUint32(size_t capacity, size_t elemSize) {
+  using mozilla::CheckedUint32;
+  return ((CheckedUint32(capacity) * elemSize) * 2).isValid();
+}
--- a/xpcom/glue/nsTArray.h
+++ b/xpcom/glue/nsTArray.h
@@ -280,47 +280,47 @@ struct NS_COM_GLUE nsTArrayHeader
 };
 
 // This class provides a SafeElementAt method to nsTArray<T*> which does
 // not take a second default value parameter.
 template <class E, class Derived>
 struct nsTArray_SafeElementAtHelper
 {
   typedef E*       elem_type;
-  typedef uint32_t index_type;
+  typedef size_t   index_type;
 
   // No implementation is provided for these two methods, and that is on
   // purpose, since we don't support these functions on non-pointer type
   // instantiations.
   elem_type& SafeElementAt(index_type i);
   const elem_type& SafeElementAt(index_type i) const;
 };
 
 template <class E, class Derived>
 struct nsTArray_SafeElementAtHelper<E*, Derived>
 {
   typedef E*       elem_type;
-  typedef uint32_t index_type;
+  typedef size_t   index_type;
 
   elem_type SafeElementAt(index_type i) {
     return static_cast<Derived*> (this)->SafeElementAt(i, nullptr);
   }
 
   const elem_type SafeElementAt(index_type i) const {
     return static_cast<const Derived*> (this)->SafeElementAt(i, nullptr);
   }
 };
 
 // E is the base type that the smart pointer is templated over; the
 // smart pointer can act as E*.
 template <class E, class Derived>
 struct nsTArray_SafeElementAtSmartPtrHelper
 {
   typedef E*       elem_type;
-  typedef uint32_t index_type;
+  typedef size_t   index_type;
 
   elem_type SafeElementAt(index_type i) {
     return static_cast<Derived*> (this)->SafeElementAt(i, nullptr);
   }
 
   const elem_type SafeElementAt(index_type i) const {
     return static_cast<const Derived*> (this)->SafeElementAt(i, nullptr);
   }
@@ -355,18 +355,18 @@ class nsTArray_base
   // the same free().
   template<class Allocator, class Copier>
   friend class nsTArray_base;
 
 protected:
   typedef nsTArrayHeader Header;
 
 public:
-  typedef uint32_t size_type;
-  typedef uint32_t index_type;
+  typedef size_t size_type;
+  typedef size_t index_type;
 
   // @return The number of elements in the array.
   size_type Length() const {
     return mHdr->mLength;
   }
 
   // @return True if the array is empty or false otherwise.
   bool IsEmpty() const {
@@ -412,17 +412,17 @@ protected:
   // @param elemAlign    The alignment in bytes of an array element.
   void ShiftData(index_type start, size_type oldLen, size_type newLen,
                  size_type elemSize, size_t elemAlign);
 
   // This method increments the length member of the array's header.
   // Note that mHdr may actually be sEmptyHdr in the case where a
   // zero-length array is inserted into our array. But then n should
   // always be 0.
-  void IncrementLength(uint32_t n) {
+  void IncrementLength(size_t n) {
     if (mHdr == EmptyHdr()) {
       if (MOZ_UNLIKELY(n != 0)) {
         // Writing a non-zero length to the empty header would be extremely bad.
         MOZ_CRASH();
       }
     } else {
       mHdr->mLength += n;
     }
@@ -1639,18 +1639,18 @@ ImplCycleCollectionUnlink(nsTArray_Impl<
 template <typename E, typename Alloc>
 inline void
 ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback,
                             nsTArray_Impl<E, Alloc>& aField,
                             const char* aName,
                             uint32_t aFlags = 0)
 {
   aFlags |= CycleCollectionEdgeNameArrayFlag;
-  uint32_t length = aField.Length();
-  for (uint32_t i = 0; i < length; ++i) {
+  size_t length = aField.Length();
+  for (size_t i = 0; i < length; ++i) {
     ImplCycleCollectionTraverse(aCallback, aField[i], aName, aFlags);
   }
 }
 
 //
 // nsTArray is an infallible vector class.  See the comment at the top of this
 // file for more details.
 //
@@ -1688,17 +1688,17 @@ public:
   template<class Allocator>
   explicit FallibleTArray(const nsTArray_Impl<E, Allocator>& other) : base_type(other) {}
 };
 
 //
 // nsAutoArrayBase is a base class for AutoFallibleTArray and nsAutoTArray.
 // You shouldn't use this class directly.
 //
-template <class TArrayBase, uint32_t N>
+template <class TArrayBase, size_t N>
 class nsAutoArrayBase : public TArrayBase
 {
 public:
   typedef nsAutoArrayBase<TArrayBase, N> self_type;
   typedef TArrayBase base_type;
   typedef typename base_type::Header Header;
   typedef typename base_type::elem_type elem_type;
 
@@ -1759,17 +1759,17 @@ private:
 //
 // nsAutoTArray<E, N> is an infallible vector class with N elements of inline
 // storage.  If you try to store more than N elements inside an
 // nsAutoTArray<E, N>, we'll call malloc() and store them all on the heap.
 //
 // Note that you can cast an nsAutoTArray<E, N> to
 // |const AutoFallibleTArray<E, N>&|.
 //
-template<class E, uint32_t N>
+template<class E, size_t N>
 class nsAutoTArray : public nsAutoArrayBase<nsTArray<E>, N>
 {
   typedef nsAutoTArray<E, N> self_type;
   typedef nsAutoArrayBase<nsTArray<E>, N> Base;
 
 public:
   nsAutoTArray() {}
 
@@ -1782,17 +1782,17 @@ public:
     return *reinterpret_cast<const AutoFallibleTArray<E, N>*>(this);
   }
 };
 
 //
 // AutoFallibleTArray<E, N> is a fallible vector class with N elements of
 // inline storage.
 //
-template<class E, uint32_t N>
+template<class E, size_t N>
 class AutoFallibleTArray : public nsAutoArrayBase<FallibleTArray<E>, N>
 {
   typedef AutoFallibleTArray<E, N> self_type;
   typedef nsAutoArrayBase<FallibleTArray<E>, N> Base;
 
 public:
   AutoFallibleTArray() {}
 
--- a/xpcom/glue/nsTArrayForwardDeclare.h
+++ b/xpcom/glue/nsTArrayForwardDeclare.h
@@ -14,26 +14,26 @@
 // Including this header is preferable to writing
 //
 //   template<class E> class nsTArray;
 //
 // yourself, since this header gives us flexibility to e.g. change the default
 // template parameters.
 //
 
-#include <stdint.h>
+#include <stddef.h>
 
 template<class E>
 class nsTArray;
 
 template<class E>
 class FallibleTArray;
 
-template<class E, uint32_t N>
+template<class E, size_t N>
 class nsAutoTArray;
 
-template<class E, uint32_t N>
+template<class E, size_t N>
 class AutoFallibleTArray;
 
 #define InfallibleTArray nsTArray
 #define AutoInfallibleTArray nsAutoTArray
 
 #endif
--- a/xpcom/glue/nsTObserverArray.h
+++ b/xpcom/glue/nsTObserverArray.h
@@ -17,19 +17,19 @@
  * N is the number of built-in storage slots that come with the array.
  * NOTE: You probably want to use nsTObserverArray, unless you specifically
  * want built-in storage. See below.
  * @see nsTObserverArray, nsTArray
  */
 
 class NS_COM_GLUE nsTObserverArray_base {
   public:
-    typedef uint32_t index_type;
-    typedef uint32_t size_type;
-    typedef int32_t  diff_type;
+    typedef size_t index_type;
+    typedef size_t size_type;
+    typedef ptrdiff_t diff_type;
 
   protected:
     class Iterator_base {
       protected:
         friend class nsTObserverArray_base;
 
         Iterator_base(index_type aPosition, Iterator_base* aNext)
           : mPosition(aPosition),
@@ -64,17 +64,17 @@ class NS_COM_GLUE nsTObserverArray_base 
     /**
      * Clears iterators when the array is destroyed.
      */
     void ClearIterators();
 
     mutable Iterator_base* mIterators;
 };
 
-template<class T, uint32_t N>
+template<class T, size_t N>
 class nsAutoTObserverArray : protected nsTObserverArray_base {
   public:
     typedef T           elem_type;
     typedef nsTArray<T> array_type;
 
     nsAutoTObserverArray() {
     }
 
@@ -410,33 +410,33 @@ class nsTObserverArray : public nsAutoTO
     nsTObserverArray() {}
 
     // Initialize this array and pre-allocate some number of elements.
     explicit nsTObserverArray(size_type capacity) {
       base_type::mArray.SetCapacity(capacity);
     }
 };
 
-template <typename T, uint32_t N>
+template <typename T, size_t N>
 inline void
 ImplCycleCollectionUnlink(nsAutoTObserverArray<T, N>& aField)
 {
   aField.Clear();
 }
 
-template <typename T, uint32_t N>
+template <typename T, size_t N>
 inline void
 ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback,
                             nsAutoTObserverArray<T, N>& aField,
                             const char* aName,
                             uint32_t aFlags = 0)
 {
   aFlags |= CycleCollectionEdgeNameArrayFlag;
-  uint32_t length = aField.Length();
-  for (uint32_t i = 0; i < length; ++i) {
+  size_t length = aField.Length();
+  for (size_t i = 0; i < length; ++i) {
     ImplCycleCollectionTraverse(aCallback, aField.ElementAt(i), aName, aFlags);
   }
 }
 
 // XXXbz I wish I didn't have to pass in the observer type, but I
 // don't see a way to get it out of array_.
 // Note that this macro only works if the array holds pointers to XPCOM objects.
 #define NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(array_, obstype_, func_, params_) \
--- a/xpcom/tests/TestTArray.cpp
+++ b/xpcom/tests/TestTArray.cpp
@@ -3,16 +3,17 @@
 /* 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 "mozilla/ArrayUtils.h"
 
 #include <stdlib.h>
 #include <stdio.h>
+#include <iostream>
 #include "nsTArray.h"
 #include "nsAutoPtr.h"
 #include "nsStringAPI.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsDirectoryServiceUtils.h"
 #include "nsComponentManagerUtils.h"
 #include "nsXPCOM.h"
 #include "nsIFile.h"
@@ -26,41 +27,41 @@ template <class T>
 inline bool operator<(const nsCOMPtr<T>& lhs, const nsCOMPtr<T>& rhs) {
   return lhs.get() < rhs.get();
 }
 
 //----
 
 template <class ElementType>
 static bool test_basic_array(ElementType *data,
-                               uint32_t dataLen,
-                               const ElementType& extra) {
+                             size_t dataLen,
+                             const ElementType& extra) {
   nsTArray<ElementType> ary;
   ary.AppendElements(data, dataLen);
   if (ary.Length() != dataLen) {
     return false;
   }
   if (!(ary == ary)) {
     return false;
   }
-  uint32_t i;
+  size_t i;
   for (i = 0; i < ary.Length(); ++i) {
     if (ary[i] != data[i])
       return false;
   }
   for (i = 0; i < ary.Length(); ++i) {
     if (ary.SafeElementAt(i, extra) != data[i])
       return false;
   }
   if (ary.SafeElementAt(ary.Length(), extra) != extra ||
       ary.SafeElementAt(ary.Length() * 10, extra) != extra)
     return false;
   // ensure sort results in ascending order
   ary.Sort();
-  uint32_t j = 0, k = ary.IndexOfFirstElementGt(extra);
+  size_t j = 0, k = ary.IndexOfFirstElementGt(extra);
   if (k != 0 && ary[k-1] == extra)
     return false;
   for (i = 0; i < ary.Length(); ++i) {
     k = ary.IndexOfFirstElementGt(ary[i]);
     if (k == 0 || ary[k-1] != ary[i])
       return false;
     if (k < j)
       return false;
@@ -76,59 +77,59 @@ static bool test_basic_array(ElementType
     return false;
   }
   for (i = 0; i < ary.Length(); ++i) {
     if (ary.BinaryIndexOf(ary[i]) != i)
       return false;
   }
   if (ary.BinaryIndexOf(extra) != ary.NoIndex)
     return false;
-  uint32_t oldLen = ary.Length();
+  size_t oldLen = ary.Length();
   ary.RemoveElement(data[dataLen / 2]);
   if (ary.Length() != (oldLen - 1))
     return false;
   if (!(ary == ary))
     return false;
 
-  uint32_t index = ary.Length() / 2;
+  size_t index = ary.Length() / 2;
   if (!ary.InsertElementAt(index, extra))
     return false;
   if (!(ary == ary))
     return false;
   if (ary[index] != extra)
     return false;
-  if (ary.IndexOf(extra) == UINT32_MAX)
+  if (ary.IndexOf(extra) == ary.NoIndex)
     return false;
-  if (ary.LastIndexOf(extra) == UINT32_MAX)
+  if (ary.LastIndexOf(extra) == ary.NoIndex)
     return false;
   // ensure proper searching
   if (ary.IndexOf(extra) > ary.LastIndexOf(extra))
     return false;
   if (ary.IndexOf(extra, index) != ary.LastIndexOf(extra, index))
     return false;
 
   nsTArray<ElementType> copy(ary);
   if (!(ary == copy))
     return false;
   for (i = 0; i < copy.Length(); ++i) {
     if (ary[i] != copy[i])
       return false;
   }
   if (!ary.AppendElements(copy))
     return false;
-  uint32_t cap = ary.Capacity();
+  size_t cap = ary.Capacity();
   ary.RemoveElementsAt(copy.Length(), copy.Length());
   ary.Compact();
   if (ary.Capacity() == cap)
     return false;
 
   ary.Clear();
-  if (ary.IndexOf(extra) != UINT32_MAX)
+  if (ary.IndexOf(extra) != ary.NoIndex)
     return false;
-  if (ary.LastIndexOf(extra) != UINT32_MAX)
+  if (ary.LastIndexOf(extra) != ary.NoIndex)
     return false;
 
   ary.Clear();
   if (!ary.IsEmpty() || ary.Elements() == nullptr)
     return false;
   if (!(ary == nsTArray<ElementType>()))
     return false;
   if (ary == copy)
@@ -220,17 +221,17 @@ class Object {
   private:
     nsCString mStr;
     uint32_t  mNum;
 };
 
 static bool test_object_array() {
   nsTArray<Object> objArray;
   const char kdata[] = "hello world";
-  uint32_t i;
+  size_t i;
   for (i = 0; i < ArrayLength(kdata); ++i) {
     char x[] = {kdata[i],'\0'};
     if (!objArray.AppendElement(Object(x, i)))
       return false;
   }
   for (i = 0; i < ArrayLength(kdata); ++i) {
     if (objArray[i].Str()[0] != kdata[i])
       return false;
@@ -246,54 +247,54 @@ static bool test_object_array() {
   return true;
 }
 
 // nsTArray<nsAutoPtr<T>> is not supported
 #if 0
 static bool test_autoptr_array() {
   nsTArray< nsAutoPtr<Object> > objArray;
   const char kdata[] = "hello world";
-  for (uint32_t i = 0; i < ArrayLength(kdata); ++i) {
+  for (size_t i = 0; i < ArrayLength(kdata); ++i) {
     char x[] = {kdata[i],'\0'};
     nsAutoPtr<Object> obj(new Object(x,i));
     if (!objArray.AppendElement(obj))  // XXX does not call copy-constructor for nsAutoPtr!!!
       return false;
     if (obj.get() == nullptr)
       return false;
     obj.forget();  // the array now owns the reference
   }
-  for (uint32_t i = 0; i < ArrayLength(kdata); ++i) {
+  for (size_t i = 0; i < ArrayLength(kdata); ++i) {
     if (objArray[i]->Str()[0] != kdata[i])
       return false;
     if (objArray[i]->Num() != i)
       return false;
   }
   return true;
 }
 #endif
 
 //----
 
 static bool test_string_array() {
   nsTArray<nsCString> strArray;
   const char kdata[] = "hello world";
-  uint32_t i;
+  size_t i;
   for (i = 0; i < ArrayLength(kdata); ++i) {
     nsCString str;
     str.Assign(kdata[i]);
     if (!strArray.AppendElement(str))
       return false;
   }
   for (i = 0; i < ArrayLength(kdata); ++i) {
     if (strArray[i].CharAt(0) != kdata[i])
       return false;
   }
 
   const char kextra[] = "foo bar";
-  uint32_t oldLen = strArray.Length();
+  size_t oldLen = strArray.Length();
   if (!strArray.AppendElement(kextra))
     return false;
   strArray.RemoveElement(kextra);
   if (oldLen != strArray.Length())
     return false;
 
   if (strArray.IndexOf("e") != 1)
     return false;
@@ -337,17 +338,17 @@ static bool test_comptr_array() {
   FilePointer tmpDir;
   NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tmpDir));
   if (!tmpDir)
     return false;
   const char *kNames[] = {
     "foo.txt", "bar.html", "baz.gif"
   };
   nsTArray<FilePointer> fileArray;
-  uint32_t i;
+  size_t i;
   for (i = 0; i < ArrayLength(kNames); ++i) {
     FilePointer f;
     tmpDir->Clone(getter_AddRefs(f));
     if (!f)
       return false;
     if (NS_FAILED(f->AppendNative(nsDependentCString(kNames[i]))))
       return false;
     fileArray.AppendElement(f);
@@ -469,17 +470,17 @@ static bool test_autoarray() {
 
   nsTArray<uint32_t> array2;
   void* emptyHdr = array2.DebugGetHeader();
   array.SwapElements(array2);
   if (emptyHdr == array.DebugGetHeader())
     return false;
   if (hdr == array2.DebugGetHeader())
     return false;
-  uint32_t i;
+  size_t i;
   for (i = 0; i < ArrayLength(data); ++i) {
     if (array2[i] != data[i])
       return false;
   }
   if (!array.IsEmpty())
     return false;
 
   array.Compact();
@@ -514,18 +515,18 @@ static bool test_indexof() {
   array.RemoveElementAt(1);
   // we should not find the 5!
   return array.IndexOf(5, 1) == array.NoIndex;
 }
 
 //----
 
 template <class Array>
-static bool is_heap(const Array& ary, uint32_t len) {
-  uint32_t index = 1;
+static bool is_heap(const Array& ary, size_t len) {
+  size_t index = 1;
   while (index < len) {
     if (ary[index] > ary[(index - 1) >> 1])
       return false;
     index++;
   }
   return true;
 } 
 
@@ -543,17 +544,17 @@ static bool test_heap() {
   if (!is_heap(ary, ArrayLength(data) - 1))
     return false;
   // push the previously poped value back on and make sure it's still a heap
   ary.PushHeap(root);
   if (!is_heap(ary, ArrayLength(data)))
     return false;
   // make sure the heap looks like what we expect
   const int expected_data[] = {8,7,5,6,4,1,4,2,3};
-  uint32_t index;
+  size_t index;
   for (index = 0; index < ArrayLength(data); index++)
     if (ary[index] != expected_data[index])
       return false;
   return true;
 }
 
 //----
 
@@ -590,26 +591,28 @@ static bool test_heap() {
              __FILE__, __LINE__, #arr);                   \
       return false;                                    \
     }                                                     \
   } while(0)
 
 #define CHECK_EQ_INT(actual, expected) \
   do {                                                                       \
     if ((actual) != (expected)) {                                            \
-      printf("%s:%d CHECK_EQ_INT(%s=%u, %s=%u) failed.\n",                   \
-             __FILE__, __LINE__, #actual, (actual), #expected, (expected));  \
-      return false;                                                       \
+      std::cout << __FILE__ << ":" << __LINE__ << " CHECK_EQ_INT("             \
+                << #actual << "=" << (actual) << ", "                        \
+                << #expected << "=" << (expected) << ") failed."             \
+                << std::endl;                                                \
+      return false;                                                          \
     }                                                                        \
   } while(0)
 
 #define CHECK_ARRAY(arr, data) \
   do {                                                          \
-    CHECK_EQ_INT((arr).Length(), (uint32_t)ArrayLength(data));  \
-    for (uint32_t _i = 0; _i < ArrayLength(data); _i++) {       \
+    CHECK_EQ_INT((arr).Length(), (size_t)ArrayLength(data));  \
+    for (size_t _i = 0; _i < ArrayLength(data); _i++) {       \
       CHECK_EQ_INT((arr)[_i], (data)[_i]);                      \
     }                                                           \
   } while(0)
 
 static bool test_swap() {
   // Test nsTArray::SwapElements.  Unfortunately there are many cases.
   int data1[] = {8, 6, 7, 5};
   int data2[] = {3, 0, 9};
@@ -750,17 +753,17 @@ static bool test_swap() {
   // Swap two arrays and make sure that their capacities don't increase
   // unnecessarily.
   {
     nsTArray<int> a;
     nsTArray<int> b;
     b.AppendElements(data2, ArrayLength(data2));
 
     CHECK_EQ_INT(a.Capacity(), 0);
-    uint32_t bCapacity = b.Capacity();
+    size_t bCapacity = b.Capacity();
 
     a.SwapElements(b);
 
     // Make sure that we didn't increase the capacity of either array.
     CHECK_ARRAY(a, data2);
     CHECK_EQ_INT(b.Length(), 0);
     CHECK_EQ_INT(b.Capacity(), 0);
     CHECK_EQ_INT(a.Capacity(), bCapacity);
@@ -847,22 +850,22 @@ static bool test_fallible()
   }
 
   // Allocate a bunch of 128MB arrays.  Larger allocations will fail on some
   // platforms without actually hitting OOM.
   //
   // 36 * 128MB > 4GB, so we should definitely OOM by the 36th array.
   const unsigned numArrays = 36;
   FallibleTArray<char> arrays[numArrays];
-  for (uint32_t i = 0; i < numArrays; i++) {
+  for (size_t i = 0; i < numArrays; i++) {
     bool success = arrays[i].SetCapacity(128 * 1024 * 1024);
     if (!success) {
       // We got our OOM.  Check that it didn't come too early.
       if (i < 8) {
-        printf("test_fallible: Got OOM on iteration %d.  Too early!\n", i);
+        printf("test_fallible: Got OOM on iteration %d.  Too early!\n", int(i));
         return false;
       }
       return true;
     }
   }
 
   // No OOM?  That's...weird.
   printf("test_fallible: Didn't OOM or crash?  nsTArray::SetCapacity "