Bug 645398 - Substitute PR_(MAX|MIN|ABS|ROUNDUP) macro calls; r=roc
authorDominic Fandrey <LoN_Kamikaze@gmx.de>
Thu, 02 Jun 2011 14:56:50 +0200
changeset 70463 e3f863f8bf4afab968896fb1a835097779f124a7
parent 70462 1f19c58519297d0a0ff772dfaad24914c8942de8
child 70464 647e11c0822a1d9e4a7149d7f7467451e84a4962
push idunknown
push userunknown
push dateunknown
reviewersroc
bugs645398
milestone7.0a1
Bug 645398 - Substitute PR_(MAX|MIN|ABS|ROUNDUP) macro calls; r=roc
content/canvas/src/WebGLContext.h
content/canvas/src/WebGLContextGL.cpp
content/canvas/src/WebGLContextValidate.cpp
content/events/src/nsEventStateManager.cpp
content/media/nsBuiltinDecoderReader.cpp
content/media/nsMediaCache.cpp
content/media/nsMediaStream.cpp
content/smil/nsSMILAnimationController.cpp
content/smil/nsSMILTimeContainer.cpp
content/xslt/src/base/txDouble.cpp
content/xslt/src/base/txStringUtils.cpp
content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
content/xslt/src/xpath/txNodeSet.cpp
content/xslt/src/xslt/txMozillaXMLOutput.cpp
content/xul/content/src/nsXULElement.cpp
db/morkreader/nsMorkReader.cpp
docshell/shistory/src/nsSHistory.cpp
dom/indexedDB/IDBFactory.cpp
dom/ipc/TabParent.cpp
editor/libeditor/html/nsHTMLEditRules.cpp
editor/libeditor/html/nsHTMLObjectResizer.cpp
extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
extensions/pref/autoconfig/src/nsAutoConfig.cpp
gfx/thebes/gfxBlur.cpp
gfx/thebes/gfxContext.cpp
gfx/thebes/gfxCoreTextShaper.cpp
gfx/thebes/gfxDWriteFontList.h
gfx/thebes/gfxFT2Utils.cpp
gfx/thebes/gfxFontUtils.h
gfx/thebes/gfxGDIFont.cpp
gfx/thebes/gfxGDIFontList.cpp
gfx/thebes/gfxHarfBuzzShaper.cpp
gfx/thebes/gfxImageSurface.cpp
gfx/thebes/gfxMacFont.cpp
gfx/thebes/gfxOS2Fonts.cpp
gfx/thebes/gfxRect.h
gfx/thebes/gfxSkipChars.cpp
intl/uconv/src/nsConverterInputStream.cpp
intl/uconv/src/nsUTF8ToUnicode.cpp
intl/uconv/util/nsUCSupport.cpp
layout/base/nsCSSColorUtils.h
layout/base/nsCSSRendering.cpp
layout/mathml/nsMathMLChar.cpp
layout/style/nsStyleAnimation.cpp
layout/tables/nsTableFrame.cpp
layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
modules/libpr0n/decoders/nsBMPDecoder.cpp
modules/libpr0n/decoders/nsGIFDecoder2.cpp
modules/libpr0n/decoders/nsICODecoder.cpp
modules/libpr0n/decoders/nsIconDecoder.cpp
modules/libpr0n/decoders/nsPNGDecoder.cpp
modules/libpr0n/src/RasterImage.cpp
modules/libpr0n/src/imgRequest.cpp
modules/libpref/src/prefapi.cpp
netwerk/base/src/nsBufferedStreams.cpp
netwerk/base/src/nsFileStreams.h
netwerk/base/src/nsIncrementalDownload.cpp
netwerk/base/src/nsSocketTransport2.cpp
netwerk/base/src/nsStandardURL.cpp
netwerk/base/src/nsSyncStreamListener.cpp
netwerk/cache/nsCacheService.cpp
netwerk/cache/nsDiskCacheBlockFile.cpp
netwerk/cache/nsDiskCacheMap.cpp
netwerk/cache/nsMemoryCacheDevice.cpp
netwerk/protocol/about/nsAboutCacheEntry.cpp
netwerk/protocol/file/nsFileChannel.cpp
netwerk/protocol/http/HttpBaseChannel.cpp
netwerk/protocol/http/nsHttpChunkedDecoder.cpp
netwerk/protocol/http/nsHttpConnectionMgr.cpp
netwerk/protocol/http/nsHttpResponseHead.cpp
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/streamconv/converters/nsBinHexDecoder.cpp
netwerk/streamconv/converters/nsIndexedToHTML.cpp
netwerk/streamconv/converters/nsMultiMixedConv.cpp
netwerk/streamconv/converters/nsTXTToHTMLConv.cpp
uriloader/exthandler/nsExternalHelperAppService.cpp
widget/src/android/nsWindow.cpp
widget/src/gtk2/nsNativeKeyBindings.cpp
widget/src/gtk2/nsNativeThemeGTK.cpp
widget/src/gtk2/nsPrintSettingsGTK.cpp
widget/src/gtk2/nsWindow.cpp
widget/src/os2/nsIdleServiceOS2.cpp
widget/src/windows/KeyboardLayout.cpp
widget/src/windows/nsIMM32Handler.cpp
widget/src/windows/nsNativeThemeWin.cpp
widget/src/windows/nsTextStore.cpp
widget/src/xpwidgets/nsBaseDragService.cpp
widget/src/xpwidgets/nsIdleService.cpp
widget/src/xpwidgets/nsNativeTheme.cpp
widget/src/xpwidgets/nsNativeTheme.h
widget/tests/TestWinTSF.cpp
xpcom/ds/nsExpirationTracker.h
xpcom/glue/nsQuickSort.cpp
xpcom/glue/nsTArray-inl.h
xpcom/glue/nsTArray.h
xpcom/glue/nsVersionComparator.cpp
xpcom/glue/nsVoidArray.cpp
xpcom/io/nsFastLoadFile.cpp
xpcom/io/nsFastLoadFile.h
xpcom/io/nsPipe3.cpp
xpcom/io/nsScriptableInputStream.cpp
xpcom/io/nsStorageStream.cpp
xpcom/io/nsUnicharInputStream.cpp
xpcom/string/public/nsAlgorithm.h
xpcom/string/src/nsReadableUtils.cpp
xpcom/string/src/nsTSubstring.cpp
xpcom/tests/TestPipes.cpp
xpfe/appshell/src/nsXULWindow.cpp
xpinstall/src/CertReader.cpp
xpinstall/src/nsXPInstallManager.cpp
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -944,17 +944,17 @@ protected:
 
     size_t mFacesCount, mMaxLevelWithCustomImages;
     nsTArray<ImageInfo> mImageInfos;
 
     PRBool mHaveGeneratedMipmap;
     FakeBlackStatus mFakeBlackStatus;
 
     void EnsureMaxLevelWithCustomImagesAtLeast(size_t aMaxLevelWithCustomImages) {
-        mMaxLevelWithCustomImages = PR_MAX(mMaxLevelWithCustomImages, aMaxLevelWithCustomImages);
+        mMaxLevelWithCustomImages = NS_MAX(mMaxLevelWithCustomImages, aMaxLevelWithCustomImages);
         mImageInfos.EnsureLengthAtLeast((mMaxLevelWithCustomImages + 1) * mFacesCount);
     }
 
     PRBool CheckFloatTextureFilterParams() const {
         // Without OES_texture_float_linear, only NEAREST and NEAREST_MIMPAMP_NEAREST are supported
         return (mMagFilter == LOCAL_GL_NEAREST) &&
             (mMinFilter == LOCAL_GL_NEAREST || mMinFilter == LOCAL_GL_NEAREST_MIPMAP_NEAREST);
     }
@@ -974,18 +974,18 @@ protected:
         ImageInfo expected = ImageInfoAt(0, face);
 
         // checks if custom level>0 images are all defined up to the highest level defined
         // and have the expected dimensions
         for (size_t level = 0; level <= mMaxLevelWithCustomImages; ++level) {
             const ImageInfo& actual = ImageInfoAt(level, face);
             if (actual != expected)
                 return PR_FALSE;
-            expected.mWidth = PR_MAX(1, expected.mWidth >> 1);
-            expected.mHeight = PR_MAX(1, expected.mHeight >> 1);
+            expected.mWidth = NS_MAX(1, expected.mWidth >> 1);
+            expected.mHeight = NS_MAX(1, expected.mHeight >> 1);
 
             // if the current level has size 1x1, we can stop here: the spec doesn't seem to forbid the existence
             // of extra useless levels.
             if (actual.mWidth == 1 && actual.mHeight == 1)
                 return PR_TRUE;
         }
 
         // if we're here, we've exhausted all levels without finding a 1x1 image
@@ -1086,17 +1086,17 @@ public:
             // if we were in GeneratedMipmap mode and are now switching to CustomMipmap mode,
             // we need to compute now all the mipmap image info.
 
             // since we were in GeneratedMipmap mode, we know that the level 0 images all have the same info,
             // and are power-of-two.
             ImageInfo imageInfo = ImageInfoAt(0, 0);
             NS_ASSERTION(imageInfo.IsPowerOfTwo(), "this texture is NPOT, so how could GenerateMipmap() ever accept it?");
 
-            WebGLsizei size = PR_MAX(imageInfo.mWidth, imageInfo.mHeight);
+            WebGLsizei size = NS_MAX(imageInfo.mWidth, imageInfo.mHeight);
 
             // so, the size is a power of two, let's find its log in base 2.
             size_t maxLevel = 0;
             for (WebGLsizei n = size; n > 1; n >>= 1)
                 ++maxLevel;
 
             EnsureMaxLevelWithCustomImagesAtLeast(maxLevel);
 
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -739,23 +739,23 @@ WebGLContext::CopyTexSubImage2D_base(Web
             || x+width <= 0
             || y >= framebufferHeight
             || y+height <= 0)
         {
             // we are completely outside of range, can exit now with buffer filled with zeros
             return NS_OK;
         }
 
-        GLint   actual_x             = PR_MIN(framebufferWidth, PR_MAX(0, x));
-        GLint   actual_x_plus_width  = PR_MIN(framebufferWidth, PR_MAX(0, x + width));
+        GLint   actual_x             = NS_MIN(framebufferWidth, NS_MAX(0, x));
+        GLint   actual_x_plus_width  = NS_MIN(framebufferWidth, NS_MAX(0, x + width));
         GLsizei actual_width   = actual_x_plus_width  - actual_x;
         GLint   actual_xoffset = xoffset + actual_x - x;
 
-        GLint   actual_y             = PR_MIN(framebufferHeight, PR_MAX(0, y));
-        GLint   actual_y_plus_height = PR_MIN(framebufferHeight, PR_MAX(0, y + height));
+        GLint   actual_y             = NS_MIN(framebufferHeight, NS_MAX(0, y));
+        GLint   actual_y_plus_height = NS_MIN(framebufferHeight, NS_MAX(0, y + height));
         GLsizei actual_height  = actual_y_plus_height - actual_y;
         GLint   actual_yoffset = yoffset + actual_y - y;
 
         gl->fCopyTexSubImage2D(target, level, actual_xoffset, actual_yoffset, actual_x, actual_y, actual_width, actual_height);
     }
 
     return NS_OK;
 }
@@ -2982,22 +2982,22 @@ WebGLContext::ReadPixels_base(WebGLint x
             || y >= boundHeight
             || y+height <= 0)
         {
             // we are completely outside of range, can exit now with buffer filled with zeros
             return NS_OK;
         }
 
         // compute the parameters of the subrect we're actually going to call glReadPixels on
-        GLint   subrect_x      = PR_MAX(x, 0);
-        GLint   subrect_end_x  = PR_MIN(x+width, boundWidth);
+        GLint   subrect_x      = NS_MAX(x, 0);
+        GLint   subrect_end_x  = NS_MIN(x+width, boundWidth);
         GLsizei subrect_width  = subrect_end_x - subrect_x;
 
-        GLint   subrect_y      = PR_MAX(y, 0);
-        GLint   subrect_end_y  = PR_MIN(y+height, boundHeight);
+        GLint   subrect_y      = NS_MAX(y, 0);
+        GLint   subrect_end_y  = NS_MIN(y+height, boundHeight);
         GLsizei subrect_height = subrect_end_y - subrect_y;
 
         if (subrect_width < 0 || subrect_height < 0 ||
             subrect_width > width || subrect_height > height)
             return ErrorInvalidOperation("ReadPixels: integer overflow computing clipped rect size");
 
         // now we know that subrect_width is in the [0..width] interval, and same for heights.
 
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -533,17 +533,17 @@ WebGLContext::InitAndValidateGL()
         GLint maxVertexOutputComponents,
               minFragmentInputComponents;
         gl->fGetIntegerv(LOCAL_GL_MAX_VERTEX_OUTPUT_COMPONENTS, &maxVertexOutputComponents);
         gl->fGetIntegerv(LOCAL_GL_MAX_FRAGMENT_INPUT_COMPONENTS, &minFragmentInputComponents);
 
         error = gl->fGetError();
         switch (error) {
             case LOCAL_GL_NO_ERROR:
-                mGLMaxVaryingVectors = PR_MIN(maxVertexOutputComponents, minFragmentInputComponents) / 4;
+                mGLMaxVaryingVectors = NS_MIN(maxVertexOutputComponents, minFragmentInputComponents) / 4;
                 break;
             case LOCAL_GL_INVALID_ENUM:
                 mGLMaxVaryingVectors = 16; // = 64/4, 64 is the min value for maxVertexOutputComponents in OpenGL 3.2 spec
                 break;
             default:
                 LogMessage("GL error 0x%x occurred during WebGL context initialization!", error);
                 return PR_FALSE;
         }
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -765,17 +765,17 @@ nsMouseWheelTransaction::LimitToOnePageS
   nscoord lineScroll = aIsHorizontal ? lineAmount.width : lineAmount.height;
 
   if (lineScroll == 0)
     return aScrollLines;
 
   nsSize pageAmount = sf->GetPageScrollAmount();
   nscoord pageScroll = aIsHorizontal ? pageAmount.width : pageAmount.height;
 
-  if (PR_ABS(aScrollLines) * lineScroll < pageScroll)
+  if (NS_ABS(aScrollLines) * lineScroll < pageScroll)
     return aScrollLines;
 
   nscoord maxLines = (pageScroll / lineScroll);
   if (maxLines >= 1)
     return ((aScrollLines < 0) ? -1 : 1) * maxLines;
 
   *aScrollQuantity = nsIScrollableFrame::PAGES;
   return (aScrollLines < 0) ? -1 : 1;
@@ -1267,32 +1267,32 @@ nsEventStateManager::PreHandleEvent(nsPr
         nscoord pixelHeight = aPresContext->AppUnitsToIntCSSPixels(
           GetScrollableLineHeight(aTargetFrame));
 
         if (msEvent->scrollFlags & nsMouseScrollEvent::kIsVertical) {
           gPixelScrollDeltaX += msEvent->delta;
           if (!gPixelScrollDeltaX || !pixelHeight)
             break;
 
-          if (PR_ABS(gPixelScrollDeltaX) >= pixelHeight) {
+          if (NS_ABS(gPixelScrollDeltaX) >= pixelHeight) {
             PRInt32 numLines = (PRInt32)ceil((float)gPixelScrollDeltaX/(float)pixelHeight);
 
             gPixelScrollDeltaX -= numLines*pixelHeight;
 
             nsWeakFrame weakFrame(aTargetFrame);
             SendLineScrollEvent(aTargetFrame, msEvent, aPresContext,
               aStatus, numLines);
             NS_ENSURE_STATE(weakFrame.IsAlive());
           }
         } else if (msEvent->scrollFlags & nsMouseScrollEvent::kIsHorizontal) {
           gPixelScrollDeltaY += msEvent->delta;
           if (!gPixelScrollDeltaY || !pixelHeight)
             break;
 
-          if (PR_ABS(gPixelScrollDeltaY) >= pixelHeight) {
+          if (NS_ABS(gPixelScrollDeltaY) >= pixelHeight) {
             PRInt32 numLines = (PRInt32)ceil((float)gPixelScrollDeltaY/(float)pixelHeight);
 
             gPixelScrollDeltaY -= numLines*pixelHeight;
 
             nsWeakFrame weakFrame(aTargetFrame);
             SendLineScrollEvent(aTargetFrame, msEvent, aPresContext,
               aStatus, numLines);
             NS_ENSURE_STATE(weakFrame.IsAlive());
@@ -1985,18 +1985,18 @@ nsEventStateManager::GenerateDragGesture
       if (!pixelThresholdX)
         pixelThresholdX = 5;
       if (!pixelThresholdY)
         pixelThresholdY = 5;
     }
 
     // fire drag gesture if mouse has moved enough
     nsIntPoint pt = aEvent->refPoint + aEvent->widget->WidgetToScreenOffset();
-    if (PR_ABS(pt.x - mGestureDownPoint.x) > pixelThresholdX ||
-        PR_ABS(pt.y - mGestureDownPoint.y) > pixelThresholdY) {
+    if (NS_ABS(pt.x - mGestureDownPoint.x) > pixelThresholdX ||
+        NS_ABS(pt.y - mGestureDownPoint.y) > pixelThresholdY) {
       if (mClickHoldContextMenu) {
         // stop the click-hold before we fire off the drag gesture, in case
         // it takes a long time
         KillClickHoldTimer();
       }
 
       nsRefPtr<nsDOMDataTransfer> dataTransfer = new nsDOMDataTransfer();
       if (!dataTransfer)
--- a/content/media/nsBuiltinDecoderReader.cpp
+++ b/content/media/nsBuiltinDecoderReader.cpp
@@ -249,17 +249,17 @@ VideoData* nsBuiltinDecoderReader::FindS
   if (HasAudio()) {
     SoundData* soundData = DecodeToFirstData(&nsBuiltinDecoderReader::DecodeAudioData,
                                              mAudioQueue);
     if (soundData) {
       audioStartTime = soundData->mTime;
     }
   }
 
-  PRInt64 startTime = PR_MIN(videoStartTime, audioStartTime);
+  PRInt64 startTime = NS_MIN(videoStartTime, audioStartTime);
   if (startTime != PR_INT64_MAX) {
     aOutStartTime = startTime;
   }
 
   return videoData;
 }
 
 template<class Data>
--- a/content/media/nsMediaCache.cpp
+++ b/content/media/nsMediaCache.cpp
@@ -813,24 +813,24 @@ nsMediaCache::AppendMostReusableBlock(Bl
 PRInt32
 nsMediaCache::FindReusableBlock(TimeStamp aNow,
                                 nsMediaCacheStream* aForStream,
                                 PRInt32 aForStreamBlock,
                                 PRInt32 aMaxSearchBlockIndex)
 {
   mReentrantMonitor.AssertCurrentThreadIn();
 
-  PRUint32 length = PR_MIN(PRUint32(aMaxSearchBlockIndex), mIndex.Length());
+  PRUint32 length = NS_MIN(PRUint32(aMaxSearchBlockIndex), mIndex.Length());
 
   if (aForStream && aForStreamBlock > 0 &&
       PRUint32(aForStreamBlock) <= aForStream->mBlocks.Length()) {
     PRInt32 prevCacheBlock = aForStream->mBlocks[aForStreamBlock - 1];
     if (prevCacheBlock >= 0) {
       PRUint32 freeBlockScanEnd =
-        PR_MIN(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
+        NS_MIN(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
       for (PRUint32 i = prevCacheBlock; i < freeBlockScanEnd; ++i) {
         if (IsBlockFree(i))
           return i;
       }
     }
   }
 
   if (!mFreeBlocks.IsEmpty()) {
@@ -1041,17 +1041,17 @@ nsMediaCache::PredictNextUse(TimeStamp a
     case READAHEAD_BLOCK: {
       PRInt64 bytesAhead =
         static_cast<PRInt64>(bo->mStreamBlock)*BLOCK_SIZE - bo->mStream->mStreamOffset;
       NS_ASSERTION(bytesAhead >= 0,
                    "Readahead block before the current stream position?");
       PRInt64 millisecondsAhead =
         bytesAhead*1000/bo->mStream->mPlaybackBytesPerSecond;
       prediction = TimeDuration::FromMilliseconds(
-          PR_MIN(millisecondsAhead, PR_INT32_MAX));
+          NS_MIN<PRInt64>(millisecondsAhead, PR_INT32_MAX));
       break;
     }
     default:
       NS_ERROR("Invalid class for predicting next use");
       return TimeDuration(0);
     }
     if (i == 0 || prediction < result) {
       result = prediction;
@@ -1069,17 +1069,17 @@ nsMediaCache::PredictNextUseForIncomingD
   if (bytesAhead <= -BLOCK_SIZE) {
     // Hmm, no idea when data behind us will be used. Guess 24 hours.
     return TimeDuration::FromSeconds(24*60*60);
   }
   if (bytesAhead <= 0)
     return TimeDuration(0);
   PRInt64 millisecondsAhead = bytesAhead*1000/aStream->mPlaybackBytesPerSecond;
   return TimeDuration::FromMilliseconds(
-      PR_MIN(millisecondsAhead, PR_INT32_MAX));
+      NS_MIN<PRInt64>(millisecondsAhead, PR_INT32_MAX));
 }
 
 enum StreamAction { NONE, SEEK, RESUME, SUSPEND };
 
 void
 nsMediaCache::Update()
 {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
@@ -1119,17 +1119,17 @@ nsMediaCache::Update()
     for (PRInt32 blockIndex = mIndex.Length() - 1; blockIndex >= maxBlocks;
          --blockIndex) {
       if (IsBlockFree(blockIndex)) {
         // Don't count overflowing free blocks in our free block count
         --freeBlockCount;
         continue;
       }
       TimeDuration predictedUse = PredictNextUse(now, blockIndex);
-      latestPredictedUseForOverflow = PR_MAX(latestPredictedUseForOverflow, predictedUse);
+      latestPredictedUseForOverflow = NS_MAX(latestPredictedUseForOverflow, predictedUse);
     }
 
     // Now try to move overflowing blocks to the main part of the cache.
     for (PRInt32 blockIndex = mIndex.Length() - 1; blockIndex >= maxBlocks;
          --blockIndex) {
       if (IsBlockFree(blockIndex))
         continue;
 
@@ -1644,17 +1644,17 @@ nsMediaCache::NoteSeek(nsMediaCacheStrea
   mReentrantMonitor.AssertCurrentThreadIn();
 
   if (aOldOffset < aStream->mStreamOffset) {
     // We seeked forward. Convert blocks from readahead to played.
     // Any readahead block that intersects the seeked-over range must
     // be converted.
     PRInt32 blockIndex = aOldOffset/BLOCK_SIZE;
     PRInt32 endIndex =
-      PR_MIN((aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
+      NS_MIN<PRInt64>((aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
              aStream->mBlocks.Length());
     TimeStamp now = TimeStamp::Now();
     while (blockIndex < endIndex) {
       PRInt32 cacheBlockIndex = aStream->mBlocks[blockIndex];
       if (cacheBlockIndex >= 0) {
         // Marking the block used may not be exactly what we want but
         // it's simple
         NoteBlockUsage(aStream, cacheBlockIndex, nsMediaCacheStream::MODE_PLAYBACK,
@@ -1664,17 +1664,17 @@ nsMediaCache::NoteSeek(nsMediaCacheStrea
     }
   } else {
     // We seeked backward. Convert from played to readahead.
     // Any played block that is entirely after the start of the seeked-over
     // range must be converted.
     PRInt32 blockIndex =
       (aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE;
     PRInt32 endIndex =
-      PR_MIN((aOldOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
+      NS_MIN<PRInt64>((aOldOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
              aStream->mBlocks.Length());
     while (blockIndex < endIndex) {
       PRInt32 cacheBlockIndex = aStream->mBlocks[endIndex - 1];
       if (cacheBlockIndex >= 0) {
         BlockOwner* bo = GetBlockOwner(cacheBlockIndex, aStream);
         NS_ASSERTION(bo, "Stream doesn't own its blocks?");
         if (bo->mClass == PLAYED_BLOCK) {
           aStream->mPlayedBlocks.RemoveBlock(cacheBlockIndex);
@@ -1708,17 +1708,17 @@ nsMediaCacheStream::NotifyDataStarted(PR
 
   ReentrantMonitorAutoEnter mon(gMediaCache->GetReentrantMonitor());
   NS_WARN_IF_FALSE(aOffset == mChannelOffset,
                    "Server is giving us unexpected offset");
   mChannelOffset = aOffset;
   if (mStreamLength >= 0) {
     // If we started reading at a certain offset, then for sure
     // the stream is at least that long.
-    mStreamLength = PR_MAX(mStreamLength, mChannelOffset);
+    mStreamLength = NS_MAX(mStreamLength, mChannelOffset);
   }
 }
 
 void
 nsMediaCacheStream::UpdatePrincipal(nsIPrincipal* aPrincipal)
 {
   if (!mPrincipal) {
     NS_ASSERTION(!mUsingNullPrincipal, "Are we using a null principal or not?");
@@ -1763,17 +1763,17 @@ nsMediaCacheStream::NotifyDataReceived(P
 
   LOG(PR_LOG_DEBUG, ("Stream %p DataReceived at %lld count=%lld",
       this, (long long)mChannelOffset, (long long)aSize));
 
   // We process the data one block (or part of a block) at a time
   while (size > 0) {
     PRUint32 blockIndex = mChannelOffset/BLOCK_SIZE;
     PRInt32 blockOffset = PRInt32(mChannelOffset - blockIndex*BLOCK_SIZE);
-    PRInt32 chunkSize = PRInt32(PR_MIN(BLOCK_SIZE - blockOffset, size));
+    PRInt32 chunkSize = NS_MIN<PRInt64>(BLOCK_SIZE - blockOffset, size);
 
     // This gets set to something non-null if we have a whole block
     // of data to write to the cache
     const char* blockDataToStore = nsnull;
     ReadMode mode = MODE_PLAYBACK;
     if (blockOffset == 0 && chunkSize == BLOCK_SIZE) {
       // We received a whole block, so avoid a useless copy through
       // mPartialBlockBuffer
@@ -1804,17 +1804,17 @@ nsMediaCacheStream::NotifyDataReceived(P
     size -= chunkSize;
     data += chunkSize;
   }
 
   nsMediaCache::ResourceStreamIterator iter(mResourceID);
   while (nsMediaCacheStream* stream = iter.Next()) {
     if (stream->mStreamLength >= 0) {
       // The stream is at least as long as what we've read
-      stream->mStreamLength = PR_MAX(stream->mStreamLength, mChannelOffset);
+      stream->mStreamLength = NS_MAX(stream->mStreamLength, mChannelOffset);
     }
     stream->UpdatePrincipal(aPrincipal);
     stream->mClient->CacheClientNotifyDataReceived();
   }
 
   // Notify in case there's a waiting reader
   // XXX it would be fairly easy to optimize things a lot more to
   // avoid waking up reader threads unnecessarily
@@ -1970,19 +1970,19 @@ nsMediaCacheStream::GetCachedDataEndInte
   if (blockIndex == mChannelOffset/BLOCK_SIZE) {
     // The block containing mChannelOffset may be partially read but not
     // yet committed to the main cache
     result = mChannelOffset;
   }
   if (mStreamLength >= 0) {
     // The last block in the cache may only be partially valid, so limit
     // the cached range to the stream length
-    result = PR_MIN(result, mStreamLength);
+    result = NS_MIN(result, mStreamLength);
   }
-  return PR_MAX(result, aOffset);
+  return NS_MAX(result, aOffset);
 }
 
 PRInt64
 nsMediaCacheStream::GetNextCachedDataInternal(PRInt64 aOffset)
 {
   gMediaCache->GetReentrantMonitor().AssertCurrentThreadIn();
   if (aOffset == mStreamLength)
     return -1;
@@ -2101,36 +2101,36 @@ nsMediaCacheStream::Read(char* aBuffer, 
     return NS_ERROR_FAILURE;
 
   PRUint32 count = 0;
   // Read one block (or part of a block) at a time
   while (count < aCount) {
     PRUint32 streamBlock = PRUint32(mStreamOffset/BLOCK_SIZE);
     PRUint32 offsetInStreamBlock =
       PRUint32(mStreamOffset - streamBlock*BLOCK_SIZE);
-    PRInt32 size = PR_MIN(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
+    PRInt32 size = NS_MIN(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
 
     if (mStreamLength >= 0) {
       // Don't try to read beyond the end of the stream
       PRInt64 bytesRemaining = mStreamLength - mStreamOffset;
       if (bytesRemaining <= 0) {
         // Get out of here and return NS_OK
         break;
       }
-      size = PR_MIN(size, PRInt32(bytesRemaining));
+      size = NS_MIN(size, PRInt32(bytesRemaining));
     }
 
     PRInt32 bytes;
     PRUint32 channelBlock = PRUint32(mChannelOffset/BLOCK_SIZE);
     PRInt32 cacheBlock = streamBlock < mBlocks.Length() ? mBlocks[streamBlock] : -1;
     if (channelBlock == streamBlock && mStreamOffset < mChannelOffset) {
       // We can just use the data in mPartialBlockBuffer. In fact we should
       // use it rather than waiting for the block to fill and land in
       // the cache.
-      bytes = PR_MIN(size, mChannelOffset - mStreamOffset);
+      bytes = NS_MIN<PRInt64>(size, mChannelOffset - mStreamOffset);
       memcpy(aBuffer + count,
         reinterpret_cast<char*>(mPartialBlockBuffer) + offsetInStreamBlock, bytes);
       if (mCurrentMode == MODE_METADATA) {
         mMetadataInPartialBlockBuffer = PR_TRUE;
       }
       gMediaCache->NoteBlockUsage(this, cacheBlock, mCurrentMode, TimeStamp::Now());
     } else {
       if (cacheBlock < 0) {
@@ -2187,35 +2187,35 @@ nsMediaCacheStream::ReadFromCache(char* 
 
   // Read one block (or part of a block) at a time
   PRUint32 count = 0;
   PRInt64 streamOffset = aOffset;
   while (count < aCount) {
     PRUint32 streamBlock = PRUint32(streamOffset/BLOCK_SIZE);
     PRUint32 offsetInStreamBlock =
       PRUint32(streamOffset - streamBlock*BLOCK_SIZE);
-    PRInt32 size = PR_MIN(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
+    PRInt32 size = NS_MIN<PRInt64>(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
 
     if (mStreamLength >= 0) {
       // Don't try to read beyond the end of the stream
       PRInt64 bytesRemaining = mStreamLength - streamOffset;
       if (bytesRemaining <= 0) {
         return NS_ERROR_FAILURE;
       }
-      size = PR_MIN(size, PRInt32(bytesRemaining));
+      size = NS_MIN(size, PRInt32(bytesRemaining));
     }
 
     PRInt32 bytes;
     PRUint32 channelBlock = PRUint32(mChannelOffset/BLOCK_SIZE);
     PRInt32 cacheBlock = streamBlock < mBlocks.Length() ? mBlocks[streamBlock] : -1;
     if (channelBlock == streamBlock && streamOffset < mChannelOffset) {
       // We can just use the data in mPartialBlockBuffer. In fact we should
       // use it rather than waiting for the block to fill and land in
       // the cache.
-      bytes = PR_MIN(size, mChannelOffset - streamOffset);
+      bytes = NS_MIN<PRInt64>(size, mChannelOffset - streamOffset);
       memcpy(aBuffer + count,
         reinterpret_cast<char*>(mPartialBlockBuffer) + offsetInStreamBlock, bytes);
     } else {
       if (cacheBlock < 0) {
         // We expect all blocks to be cached! Fail!
         return NS_ERROR_FAILURE;
       }
       PRInt64 offset = cacheBlock*BLOCK_SIZE + offsetInStreamBlock;
--- a/content/media/nsMediaStream.cpp
+++ b/content/media/nsMediaStream.cpp
@@ -933,17 +933,17 @@ public:
     *aIsReliable = PR_TRUE;
     return 100*1024*1024; // arbitray, use 100MB/s
   }
   virtual PRInt64 GetLength() { return mSize; }
   virtual PRInt64 GetNextCachedData(PRInt64 aOffset)
   {
     return (aOffset < mSize) ? aOffset : -1;
   }
-  virtual PRInt64 GetCachedDataEnd(PRInt64 aOffset) { return PR_MAX(aOffset, mSize); }
+  virtual PRInt64 GetCachedDataEnd(PRInt64 aOffset) { return NS_MAX(aOffset, mSize); }
   virtual PRBool  IsDataCachedToEndOfStream(PRInt64 aOffset) { return PR_TRUE; }
   virtual PRBool  IsSuspendedByCache() { return PR_FALSE; }
   virtual PRBool  IsSuspended() { return PR_FALSE; }
 
   nsresult GetCachedRanges(nsTArray<nsByteRange>& aRanges);
 
 private:
   // The file size, or -1 if not known. Immutable after Open().
--- a/content/smil/nsSMILAnimationController.cpp
+++ b/content/smil/nsSMILAnimationController.cpp
@@ -574,34 +574,34 @@ nsSMILAnimationController::DoMilestoneSa
     // Due to negative offsets, early ends and the like, a timed element might
     // register a milestone that is actually in the past. That's fine, but it's
     // still only going to get *sampled* with whatever time we're up to and no
     // earlier.
     //
     // Because we're only performing this clamping at the last moment, the
     // animations will still all get sampled in the correct order and
     // dependencies will be appropriately resolved.
-    sampleTime = PR_MAX(nextMilestone.mTime, sampleTime);
+    sampleTime = NS_MAX(nextMilestone.mTime, sampleTime);
 
     for (PRUint32 i = 0; i < length; ++i) {
       nsISMILAnimationElement* elem = params.mElements[i].get();
       NS_ABORT_IF_FALSE(elem, "NULL animation element in list");
       nsSMILTimeContainer* container = elem->GetTimeContainer();
       if (!container)
         // The container may be nsnull if the element has been detached from its
         // parent since registering a milestone.
         continue;
 
       nsSMILTimeValue containerTimeValue =
         container->ParentToContainerTime(sampleTime);
       if (!containerTimeValue.IsResolved())
         continue;
 
       // Clamp the converted container time to non-negative values.
-      nsSMILTime containerTime = PR_MAX(0, containerTimeValue.GetMillis());
+      nsSMILTime containerTime = NS_MAX<nsSMILTime>(0, containerTimeValue.GetMillis());
 
       if (nextMilestone.mIsEnd) {
         elem->TimedElement().SampleEndAt(containerTime);
       } else {
         elem->TimedElement().SampleAt(containerTime);
       }
     }
   }
--- a/content/smil/nsSMILTimeContainer.cpp
+++ b/content/smil/nsSMILTimeContainer.cpp
@@ -144,17 +144,17 @@ nsSMILTimeContainer::GetCurrentTime() co
   return mCurrentTime;
 }
 
 void
 nsSMILTimeContainer::SetCurrentTime(nsSMILTime aSeekTo)
 {
   // SVG 1.1 doesn't specify what to do for negative times so we adopt SVGT1.2's
   // behaviour of clamping negative times to 0.
-  aSeekTo = PR_MAX(0, aSeekTo);
+  aSeekTo = NS_MAX<nsSMILTime>(0, aSeekTo);
 
   // The following behaviour is consistent with:
   // http://www.w3.org/2003/01/REC-SVG11-20030114-errata
   //  #getCurrentTime_setCurrentTime_undefined_before_document_timeline_begin
   // which says that if SetCurrentTime is called before the document timeline
   // has begun we should still adjust the offset.
   nsSMILTime parentTime = GetParentTime();
   mParentOffset = parentTime - aSeekTo;
--- a/content/xslt/src/base/txDouble.cpp
+++ b/content/xslt/src/base/txDouble.cpp
@@ -256,17 +256,17 @@ void Double::toString(double aValue, nsA
     if (intDigits < 1) {
         *dest = '0'; ++dest;
         *dest = '.'; ++dest;
         for (i = 0; i > intDigits; --i) {
             *dest = '0'; ++dest;
         }
     }
     // mantissa
-    int firstlen = PR_MIN(intDigits, endp - buf);
+    int firstlen = NS_MIN<size_t>(intDigits, endp - buf);
     for (i = 0; i < firstlen; i++) {
         *dest = buf[i]; ++dest;
     }
     if (i < endp - buf) {
         if (i > 0) {
             *dest = '.'; ++dest;
         }
         for (; i < endp - buf; i++) {
--- a/content/xslt/src/base/txStringUtils.cpp
+++ b/content/xslt/src/base/txStringUtils.cpp
@@ -116,17 +116,17 @@ public:
   typedef PRUnichar value_type;
 
   CopyToLowerCase(nsAString::iterator& aDestIter) : mIter(aDestIter)
   {
   }
 
   void write(const PRUnichar* aSource, PRUint32 aSourceLength)
   {
-    PRUint32 len = PR_MIN(PRUint32(mIter.size_forward()), aSourceLength);
+    PRUint32 len = NS_MIN(PRUint32(mIter.size_forward()), aSourceLength);
     PRUnichar* cp = mIter.get();
     const PRUnichar* end = aSource + len;
     while (aSource != end) {
       PRUnichar ch = *aSource;
       if ((ch >= 'A') && (ch <= 'Z'))
         *cp = ch + ('a' - 'A');
       else
         *cp = ch;
--- a/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
+++ b/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
@@ -707,17 +707,17 @@ txXPathNodeUtils::comparePosition(const 
         otherNode = otherNode->GetNodeParent();
     }
 
     // Walk back down along the parent-chains until we find where they split.
     PRInt32 total = parents.Length() - 1;
     PRInt32 otherTotal = otherParents.Length() - 1;
     NS_ASSERTION(total != otherTotal, "Can't have same number of parents");
 
-    PRInt32 lastIndex = PR_MIN(total, otherTotal);
+    PRInt32 lastIndex = NS_MIN(total, otherTotal);
     PRInt32 i;
     parent = nsnull;
     for (i = 0; i <= lastIndex; ++i) {
         node = parents.ElementAt(total - i);
         otherNode = otherParents.ElementAt(otherTotal - i);
         if (node != otherNode) {
             if (!parent) {
                 // The two nodes are in different orphan subtrees.
--- a/content/xslt/src/xpath/txNodeSet.cpp
+++ b/content/xslt/src/xpath/txNodeSet.cpp
@@ -547,17 +547,17 @@ PRBool txNodeSet::ensureGrowSize(PRInt32
         mStart = dest;
         mEnd = dest + oldSize;
             
         return PR_TRUE;
     }
 
     // This isn't 100% safe. But until someone manages to make a 1gig nodeset
     // it should be ok.
-    PRInt32 newLength = PR_MAX(oldLength, kTxNodeSetMinSize);
+    PRInt32 newLength = NS_MAX(oldLength, kTxNodeSetMinSize);
 
     while (newLength < ensureSize) {
         newLength *= kTxNodeSetGrowFactor;
     }
 
     txXPathNode* newArr = static_cast<txXPathNode*>
                                      (nsMemory::Alloc(newLength *
                                                          sizeof(txXPathNode)));
--- a/content/xslt/src/xslt/txMozillaXMLOutput.cpp
+++ b/content/xslt/src/xslt/txMozillaXMLOutput.cpp
@@ -679,17 +679,17 @@ txMozillaXMLOutput::createTxWrapper()
         }
 #endif
 
         if (childContent->Tag() == nsGkAtoms::documentTypeNodeName) {
 #ifdef DEBUG
             // The new documentElement should go after the document type.
             // This is needed for cases when there is no existing
             // documentElement in the document.
-            rootLocation = PR_MAX(rootLocation, j + 1);
+            rootLocation = NS_MAX(rootLocation, j + 1);
 #endif
             ++j;
         }
         else {
             rv = mDocument->RemoveChildAt(j, PR_TRUE);
             NS_ENSURE_SUCCESS(rv, rv);
 
             rv = wrapper->AppendChildTo(childContent, PR_TRUE);
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -1034,17 +1034,17 @@ nsXULElement::RemoveChildAt(PRUint32 aIn
     
     if (newCurrentIndex == -2)
         controlElement->SetCurrentItem(nsnull);
     else if (newCurrentIndex > -1) {
         // Make sure the index is still valid
         PRInt32 treeRows;
         listBox->GetRowCount(&treeRows);
         if (treeRows > 0) {
-            newCurrentIndex = PR_MIN((treeRows - 1), newCurrentIndex);
+            newCurrentIndex = NS_MIN((treeRows - 1), newCurrentIndex);
             nsCOMPtr<nsIDOMElement> newCurrentItem;
             listBox->GetItemAtIndex(newCurrentIndex, getter_AddRefs(newCurrentItem));
             nsCOMPtr<nsIDOMXULSelectControlItemElement> xulCurItem = do_QueryInterface(newCurrentItem);
             if (xulCurItem)
                 controlElement->SetCurrentItem(xulCurItem);
         } else {
             controlElement->SetCurrentItem(nsnull);
         }
--- a/db/morkreader/nsMorkReader.cpp
+++ b/db/morkreader/nsMorkReader.cpp
@@ -310,17 +310,17 @@ nsMorkReader::ParseMap(const nsCSubstrin
 
           tokenStart = idx;
           while (idx < len && line[idx] != ')') {
             if (line[idx] == '\\') {
               ++idx; // skip escaped ')' characters
             }
             ++idx;
           }
-          PRUint32 tokenEnd = PR_MIN(idx, len);
+          PRUint32 tokenEnd = NS_MIN(idx, len);
           ++idx;
 
           nsCString value;
           MorkUnescape(Substring(line, tokenStart, tokenEnd - tokenStart),
                        value);
           aMap->Put(key, value);
           key.Truncate(0);
           break;
@@ -458,17 +458,17 @@ nsMorkReader::ParseTable(const nsCSubstr
           tokenStart = idx;
           while (idx < len && line[idx] != '^' && line[idx] != '=') {
             if (line[idx] == '\\') {
               ++idx; // skip escaped characters
             }
             ++idx;
           }
 
-          tokenEnd = PR_MIN(idx, len);
+          tokenEnd = NS_MIN(idx, len);
 
           nsCAutoString column;
           const nsCSubstring &colValue =
             Substring(line, tokenStart, tokenEnd - tokenStart);
           if (columnIsAtom) {
             column.Assign(colValue);
           } else {
             MorkUnescape(colValue, column);
@@ -491,17 +491,17 @@ nsMorkReader::ParseTable(const nsCSubstr
           PRBool valueIsAtom = (line[idx - 1] == '^');
           tokenStart = idx - 1;  // include the '=' or '^' marker in the value
           while (idx < len && line[idx] != ')') {
             if (line[idx] == '\\') {
               ++idx; // skip escaped characters
             }
             ++idx;
           }
-          tokenEnd = PR_MIN(idx, len);
+          tokenEnd = NS_MIN(idx, len);
           ++idx;
 
           const nsCSubstring &value =
             Substring(line, tokenStart, tokenEnd - tokenStart);
           if (valueIsAtom) {
             (*currentRow)[columnIndex] = value;
           } else {
             nsCAutoString value2;
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -998,17 +998,17 @@ nsSHistory::EvictGlobalContentViewer()
           uri->GetSpec(spec);
           printf("Considering for eviction: %s\n", spec.get());
         }
 #endif
         
         // This SHEntry has a ContentViewer, so check how far away it is from
         // the currently used SHEntry within this SHistory object
         if (viewer) {
-          PRInt32 distance = PR_ABS(shist->mIndex - i);
+          PRInt32 distance = NS_ABS(shist->mIndex - i);
           
 #ifdef DEBUG_PAGE_CACHE
           printf("Has a cached content viewer: %s\n", spec.get());
           printf("mIndex: %d i: %d\n", shist->mIndex, i);
 #endif
           totalContentViewers++;
 
           // If this entry is further away from focus than any previously found
@@ -1208,17 +1208,17 @@ PRBool IsSameTree(nsISHEntry* aEntry1, n
   }
 
   nsCOMPtr<nsISHContainer> container1 = do_QueryInterface(aEntry1);
   nsCOMPtr<nsISHContainer> container2 = do_QueryInterface(aEntry2);
   PRInt32 count1, count2;
   container1->GetChildCount(&count1);
   container2->GetChildCount(&count2);
   // We allow null entries in the end of the child list.
-  PRInt32 count = PR_MAX(count1, count2);
+  PRInt32 count = NS_MAX(count1, count2);
   for (PRInt32 i = 0; i < count; ++i) {
     nsCOMPtr<nsISHEntry> child1, child2;
     container1->GetChildAt(i, getter_AddRefs(child1));
     container2->GetChildAt(i, getter_AddRefs(child2));
     if (!IsSameTree(child1, child2)) {
       return PR_FALSE;
     }
   }
--- a/dom/indexedDB/IDBFactory.cpp
+++ b/dom/indexedDB/IDBFactory.cpp
@@ -622,17 +622,17 @@ IDBFactory::SetCurrentDatabase(IDBDataba
 
   return true;
 }
 
 // static
 PRUint32
 IDBFactory::GetIndexedDBQuota()
 {
-  return PRUint32(PR_MAX(gIndexedDBQuota, 0));
+  return PRUint32(NS_MAX(gIndexedDBQuota, 0));
 }
 
 // static
 void
 IDBFactory::NoteUsedByProcessType(GeckoProcessType aProcessType)
 {
   if (gAllowedProcessType == GeckoProcessType_Invalid) {
     gAllowedProcessType = aProcessType;
@@ -978,19 +978,19 @@ OpenDatabaseHelper::DoDatabaseWork(mozIS
   rv = IDBFactory::LoadDatabaseInformation(connection, mDatabaseId, mVersion,
                                            mObjectStores);
   NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
 
   for (PRUint32 i = 0; i < mObjectStores.Length(); i++) {
     nsAutoPtr<ObjectStoreInfo>& objectStoreInfo = mObjectStores[i];
     for (PRUint32 j = 0; j < objectStoreInfo->indexes.Length(); j++) {
       IndexInfo& indexInfo = objectStoreInfo->indexes[j];
-      mLastIndexId = PR_MAX(indexInfo.id, mLastIndexId);
+      mLastIndexId = NS_MAX(indexInfo.id, mLastIndexId);
     }
-    mLastObjectStoreId = PR_MAX(objectStoreInfo->id, mLastObjectStoreId);
+    mLastObjectStoreId = NS_MAX(objectStoreInfo->id, mLastObjectStoreId);
   }
 
   return NS_OK;
 }
 
 nsresult
 OpenDatabaseHelper::GetSuccessResult(JSContext* aCx,
                                      jsval *aVal)
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -395,17 +395,17 @@ TabParent::HandleQueryContentEvent(nsQue
   aEvent.mSucceeded = PR_FALSE;
   aEvent.mWasAsync = PR_FALSE;
   aEvent.mReply.mFocusedWidget = nsCOMPtr<nsIWidget>(GetWidget()).get();
 
   switch (aEvent.message)
   {
   case NS_QUERY_SELECTED_TEXT:
     {
-      aEvent.mReply.mOffset = PR_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+      aEvent.mReply.mOffset = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
       if (mIMESelectionAnchor == mIMESelectionFocus) {
         aEvent.mReply.mString.Truncate(0);
       } else {
         if (mIMESelectionAnchor > mIMECacheText.Length() ||
             mIMESelectionFocus > mIMECacheText.Length()) {
           break;
         }
         PRUint32 selLen = mIMESelectionAnchor > mIMESelectionFocus ?
@@ -441,17 +441,17 @@ TabParent::HandleQueryContentEvent(nsQue
   }
   return true;
 }
 
 bool
 TabParent::SendCompositionEvent(nsCompositionEvent& event)
 {
   mIMEComposing = event.message == NS_COMPOSITION_START;
-  mIMECompositionStart = PR_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+  mIMECompositionStart = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
   if (mIMECompositionEnding)
     return true;
   event.seqno = ++mIMESeqno;
   return PBrowserParent::SendCompositionEvent(event);
 }
 
 /**
  * During ResetInputState or CancelComposition, widget usually sends a
@@ -466,17 +466,17 @@ TabParent::SendTextEvent(nsTextEvent& ev
   if (mIMECompositionEnding) {
     mIMECompositionText = event.theText;
     return true;
   }
 
   // We must be able to simulate the selection because
   // we might not receive selection updates in time
   if (!mIMEComposing) {
-    mIMECompositionStart = PR_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+    mIMECompositionStart = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
   }
   mIMESelectionAnchor = mIMESelectionFocus =
       mIMECompositionStart + event.theText.Length();
 
   event.seqno = ++mIMESeqno;
   return PBrowserParent::SendTextEvent(event);
 }
 
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -2018,17 +2018,17 @@ nsHTMLEditRules::WillDeleteSelection(nsI
         res = range->GetStartOffset(&so);
         NS_ENSURE_SUCCESS(res, res);
         res = range->GetEndOffset(&eo);
         NS_ENSURE_SUCCESS(res, res);
       }
       res = nsWSRunObject::PrepareToDeleteRange(mHTMLEditor, address_of(visNode), &so, address_of(visNode), &eo);
       NS_ENSURE_SUCCESS(res, res);
       nsCOMPtr<nsIDOMCharacterData> nodeAsText(do_QueryInterface(visNode));
-      res = mHTMLEditor->DeleteText(nodeAsText, NS_MIN(so, eo), PR_ABS(eo - so));
+      res = mHTMLEditor->DeleteText(nodeAsText, NS_MIN(so, eo), NS_ABS(eo - so));
       *aHandled = PR_TRUE;
       NS_ENSURE_SUCCESS(res, res);    
       res = InsertBRIfNeeded(aSelection);
       return res;
     }
     else if ( (wsType==nsWSRunObject::eSpecial)  || 
               (wsType==nsWSRunObject::eBreak)    ||
               nsHTMLEditUtils::IsHR(visNode) ) 
--- a/editor/libeditor/html/nsHTMLObjectResizer.cpp
+++ b/editor/libeditor/html/nsHTMLObjectResizer.cpp
@@ -922,18 +922,18 @@ nsHTMLEditor::MouseMove(nsIDOMEvent* aMo
 
     nsCOMPtr<nsILookAndFeel> look = do_GetService(kLookAndFeelCID);
     NS_ASSERTION(look, "Look and feel service must be implemented for this toolkit");
 
     PRInt32 xThreshold=1, yThreshold=1;
     look->GetMetric(nsILookAndFeel::eMetric_DragThresholdX, xThreshold);
     look->GetMetric(nsILookAndFeel::eMetric_DragThresholdY, yThreshold);
 
-    if (PR_ABS(clientX - mOriginalX ) * 2 >= xThreshold ||
-        PR_ABS(clientY - mOriginalY ) * 2 >= yThreshold) {
+    if (NS_ABS(clientX - mOriginalX ) * 2 >= xThreshold ||
+        NS_ABS(clientY - mOriginalY ) * 2 >= yThreshold) {
       mGrabberClicked = PR_FALSE;
       StartMoving(nsnull);
     }
   }
   if (mIsMoving) {
     nsCOMPtr<nsIDOMMouseEvent> mouseEvent ( do_QueryInterface(aMouseEvent) );
     PRInt32 clientX, clientY;
     mouseEvent->GetClientX(&clientX);
--- a/extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
+++ b/extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
@@ -518,17 +518,17 @@ nsGnomeVFSInputStream::DoRead(char *aBuf
     rv = GNOME_VFS_OK;
 
     while (aCount && rv != GNOME_VFS_ERROR_EOF)
     {
       // Copy data out of our buffer
       PRUint32 bufLen = mDirBuf.Length() - mDirBufCursor;
       if (bufLen)
       {
-        PRUint32 n = PR_MIN(bufLen, aCount);
+        PRUint32 n = NS_MIN(bufLen, aCount);
         memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n);
         *aCountRead += n;
         aBuf += n;
         aCount -= n;
         mDirBufCursor += n;
       }
 
       if (!mDirListPtr)    // Are we at the end of the directory list?
--- a/extensions/pref/autoconfig/src/nsAutoConfig.cpp
+++ b/extensions/pref/autoconfig/src/nsAutoConfig.cpp
@@ -132,17 +132,17 @@ nsAutoConfig::OnDataAvailable(nsIRequest
                               PRUint32 aSourceOffset,
                               PRUint32 aLength)
 {    
     PRUint32 amt, size;
     nsresult rv;
     char buf[1024];
     
     while (aLength) {
-        size = PR_MIN(aLength, sizeof(buf));
+        size = NS_MIN<size_t>(aLength, sizeof(buf));
         rv = aIStream->Read(buf, size, &amt);
         if (NS_FAILED(rv))
             return rv;
         mBuf.Append(buf, amt);
         aLength -= amt;
     }
     return NS_OK;
 }
--- a/gfx/thebes/gfxBlur.cpp
+++ b/gfx/thebes/gfxBlur.cpp
@@ -343,21 +343,21 @@ SpreadHorizontal(unsigned char* aInput,
             // to the next point outside the skip rect.
             if (inSkipRectY && x >= aSkipRect.x &&
                 x < aSkipRect.XMost()) {
                 x = aSkipRect.XMost();
                 if (x >= aWidth)
                     break;
             }
 
-            PRInt32 sMin = PR_MAX(x - aRadius, 0);
-            PRInt32 sMax = PR_MIN(x + aRadius, aWidth - 1);
+            PRInt32 sMin = NS_MAX(x - aRadius, 0);
+            PRInt32 sMax = NS_MIN(x + aRadius, aWidth - 1);
             PRInt32 v = 0;
             for (PRInt32 s = sMin; s <= sMax; ++s) {
-                v = PR_MAX(v, aInput[aStride * y + s]);
+                v = NS_MAX<PRInt32>(v, aInput[aStride * y + s]);
             }
             aOutput[aStride * y + x] = v;
         }
     }
 }
 
 static void
 SpreadVertical(unsigned char* aInput,
@@ -388,21 +388,21 @@ SpreadVertical(unsigned char* aInput,
             // to the next point outside the skip rect.
             if (inSkipRectX && y >= aSkipRect.y &&
                 y < aSkipRect.YMost()) {
                 y = aSkipRect.YMost();
                 if (y >= aRows)
                     break;
             }
 
-            PRInt32 sMin = PR_MAX(y - aRadius, 0);
-            PRInt32 sMax = PR_MIN(y + aRadius, aRows - 1);
+            PRInt32 sMin = NS_MAX(y - aRadius, 0);
+            PRInt32 sMax = NS_MIN(y + aRadius, aRows - 1);
             PRInt32 v = 0;
             for (PRInt32 s = sMin; s <= sMax; ++s) {
-                v = PR_MAX(v, aInput[aStride * s + x]);
+                v = NS_MAX<PRInt32>(v, aInput[aStride * s + x]);
             }
             aOutput[aStride * y + x] = v;
         }
     }
 }
 
 void
 gfxAlphaBoxBlur::Paint(gfxContext* aDestinationCtx, const gfxPoint& offset)
--- a/gfx/thebes/gfxContext.cpp
+++ b/gfx/thebes/gfxContext.cpp
@@ -393,20 +393,20 @@ gfxContext::UserToDevice(const gfxRect& 
     x[1] = xmax;  y[1] = ymax;
     x[2] = xmax;  y[2] = ymin;
 
     cairo_user_to_device(mCairo, &xmin, &ymin);
     xmax = xmin;
     ymax = ymin;
     for (int i = 0; i < 3; i++) {
         cairo_user_to_device(mCairo, &x[i], &y[i]);
-        xmin = PR_MIN(xmin, x[i]);
-        xmax = PR_MAX(xmax, x[i]);
-        ymin = PR_MIN(ymin, y[i]);
-        ymax = PR_MAX(ymax, y[i]);
+        xmin = NS_MIN(xmin, x[i]);
+        xmax = NS_MAX(xmax, x[i]);
+        ymin = NS_MIN(ymin, y[i]);
+        ymax = NS_MAX(ymax, y[i]);
     }
 
     return gfxRect(xmin, ymin, xmax - xmin, ymax - ymin);
 }
 
 PRBool
 gfxContext::UserToDevicePixelSnapped(gfxRect& rect, PRBool ignoreScale) const
 {
--- a/gfx/thebes/gfxCoreTextShaper.cpp
+++ b/gfx/thebes/gfxCoreTextShaper.cpp
@@ -34,16 +34,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "prmem.h"
 #include "nsString.h"
 #include "nsBidiUtils.h"
 
 #include "gfxTypes.h"
 
 #include "nsPromiseFlatString.h"
 
@@ -373,17 +374,17 @@ gfxCoreTextShaper::SetGlyphsFromRun(gfxT
             charEnd += direction;
             while (charEnd != charLimit && charToGlyph[charEnd] == NO_GLYPH) {
                 charEnd += direction;
             }
 
             // find the maximum glyph index covered by the clump so far
             for (PRInt32 i = charStart; i != charEnd; i += direction) {
                 if (charToGlyph[i] != NO_GLYPH) {
-                    glyphEnd = PR_MAX(glyphEnd, charToGlyph[i] + 1); // update extent of glyph range
+                    glyphEnd = NS_MAX(glyphEnd, charToGlyph[i] + 1); // update extent of glyph range
                 }
             }
 
             if (glyphEnd == glyphStart + 1) {
                 // for the common case of a single-glyph clump, we can skip the following checks
                 break;
             }
 
@@ -448,18 +449,18 @@ gfxCoreTextShaper::SetGlyphsFromRun(gfxT
 
         // Then we check if the clump falls outside our actual string range; if so, just go to the next.
         if (endCharIndex <= aRunStart || baseCharIndex >= aRunStart + aRunLength) {
             glyphStart = glyphEnd;
             charStart = charEnd;
             continue;
         }
         // Ensure we won't try to go beyond the valid length of the textRun's text
-        baseCharIndex = PR_MAX(baseCharIndex, aRunStart);
-        endCharIndex = PR_MIN(endCharIndex, aRunStart + aRunLength);
+        baseCharIndex = NS_MAX(baseCharIndex, aRunStart);
+        endCharIndex = NS_MIN(endCharIndex, aRunStart + aRunLength);
 
         // Now we're ready to set the glyph info in the textRun; measure the glyph width
         // of the first (perhaps only) glyph, to see if it is "Simple"
         double toNextGlyph;
         if (glyphStart < numGlyphs-1) {
             toNextGlyph = positions[glyphStart+1].x - positions[glyphStart].x;
         } else {
             toNextGlyph = positions[0].x + runWidth - positions[glyphStart].x;
--- a/gfx/thebes/gfxDWriteFontList.h
+++ b/gfx/thebes/gfxDWriteFontList.h
@@ -94,17 +94,17 @@ public:
      */
     gfxDWriteFontEntry(const nsAString& aFaceName,
                               IDWriteFont *aFont) 
       : gfxFontEntry(aFaceName), mFont(aFont), mFontFile(nsnull)
     {
         mItalic = (aFont->GetStyle() == DWRITE_FONT_STYLE_ITALIC ||
                    aFont->GetStyle() == DWRITE_FONT_STYLE_OBLIQUE);
         mStretch = FontStretchFromDWriteStretch(aFont->GetStretch());
-        PRUint16 weight = PR_ROUNDUP(aFont->GetWeight() - 50, 100);
+        PRUint16 weight = NS_ROUNDUP(aFont->GetWeight() - 50, 100);
 
         weight = NS_MAX<PRUint16>(100, weight);
         weight = NS_MIN<PRUint16>(900, weight);
         mWeight = weight;
 
         mIsCJK = UNINITIALIZED_VALUE;
     }
 
--- a/gfx/thebes/gfxFT2Utils.cpp
+++ b/gfx/thebes/gfxFT2Utils.cpp
@@ -65,17 +65,17 @@ ScaleRoundDesignUnits(FT_Short aDesignMe
 // Pango does similar snapping for underline and strikethrough when fonts are
 // hinted, but nsCSSRendering::GetTextDecorationRectInternal always snaps the
 // top and size of lines.  Optimizing the distance between the line and
 // baseline is probably good for the gap between text and underline, but
 // optimizing the center of the line is better for positioning strikethough.
 static void
 SnapLineToPixels(gfxFloat& aOffset, gfxFloat& aSize)
 {
-    gfxFloat snappedSize = PR_MAX(NS_floor(aSize + 0.5), 1.0);
+    gfxFloat snappedSize = NS_MAX(NS_floor(aSize + 0.5), 1.0);
     // Correct offset for change in size
     gfxFloat offset = aOffset - 0.5 * (aSize - snappedSize);
     // Snap offset
     aOffset = NS_floor(offset + 0.5);
     aSize = snappedSize;
 }
 
 void
@@ -196,29 +196,29 @@ gfxFT2LockedFace::GetMetrics(gfxFont::Me
     // aveCharWidth is used for the width of text input elements so be
     // liberal rather than conservative in the estimate.
     if (os2 && os2->xAvgCharWidth) {
         // Round to pixels as this is compared with maxAdvance to guess
         // whether this is a fixed width font.
         gfxFloat avgCharWidth =
             ScaleRoundDesignUnits(os2->xAvgCharWidth, ftMetrics.x_scale);
         aMetrics->aveCharWidth =
-            PR_MAX(aMetrics->aveCharWidth, avgCharWidth);
+            NS_MAX(aMetrics->aveCharWidth, avgCharWidth);
     }
     aMetrics->aveCharWidth =
-        PR_MAX(aMetrics->aveCharWidth, aMetrics->zeroOrAveCharWidth);
+        NS_MAX(aMetrics->aveCharWidth, aMetrics->zeroOrAveCharWidth);
     if (aMetrics->aveCharWidth == 0.0) {
         aMetrics->aveCharWidth = aMetrics->spaceWidth;
     }
     if (aMetrics->zeroOrAveCharWidth == 0.0) {
         aMetrics->zeroOrAveCharWidth = aMetrics->aveCharWidth;
     }
     // Apparently hinting can mean that max_advance is not always accurate.
     aMetrics->maxAdvance =
-        PR_MAX(aMetrics->maxAdvance, aMetrics->aveCharWidth);
+        NS_MAX(aMetrics->maxAdvance, aMetrics->aveCharWidth);
 
     // gfxFont::Metrics::underlineOffset is the position of the top of the
     // underline.
     //
     // FT_FaceRec documentation describes underline_position as "the
     // center of the underlining stem".  This was the original definition
     // of the PostScript metric, but in the PostScript table of OpenType
     // fonts the metric is "the top of the underline"
@@ -253,27 +253,27 @@ gfxFT2LockedFace::GetMetrics(gfxFont::Me
         aMetrics->strikeoutOffset = emHeight * 409.0 / 2048.0
             + 0.5 * aMetrics->strikeoutSize;
     }
     SnapLineToPixels(aMetrics->strikeoutOffset, aMetrics->strikeoutSize);
 
     if (os2 && os2->ySuperscriptYOffset) {
         gfxFloat val = ScaleRoundDesignUnits(os2->ySuperscriptYOffset,
                                              ftMetrics.y_scale);
-        aMetrics->superscriptOffset = PR_MAX(1.0, val);
+        aMetrics->superscriptOffset = NS_MAX(1.0, val);
     } else {
         aMetrics->superscriptOffset = aMetrics->xHeight;
     }
     
     if (os2 && os2->ySubscriptYOffset) {
         gfxFloat val = ScaleRoundDesignUnits(os2->ySubscriptYOffset,
                                              ftMetrics.y_scale);
         // some fonts have the incorrect sign. 
         val = fabs(val);
-        aMetrics->subscriptOffset = PR_MAX(1.0, val);
+        aMetrics->subscriptOffset = NS_MAX(1.0, val);
     } else {
         aMetrics->subscriptOffset = aMetrics->xHeight;
     }
 
     aMetrics->maxHeight = aMetrics->maxAscent + aMetrics->maxDescent;
 
     // Make the line height an integer number of pixels so that lines will be
     // equally spaced (rather than just being snapped to pixels, some up and
@@ -285,17 +285,17 @@ gfxFT2LockedFace::GetMetrics(gfxFont::Me
 
     // maxHeight will normally be an integer, but round anyway in case
     // FreeType is configured differently.
     aMetrics->internalLeading =
         NS_floor(aMetrics->maxHeight - aMetrics->emHeight + 0.5);
 
     // Text input boxes currently don't work well with lineHeight
     // significantly less than maxHeight (with Verdana, for example).
-    lineHeight = NS_floor(PR_MAX(lineHeight, aMetrics->maxHeight) + 0.5);
+    lineHeight = NS_floor(NS_MAX(lineHeight, aMetrics->maxHeight) + 0.5);
     aMetrics->externalLeading =
         lineHeight - aMetrics->internalLeading - aMetrics->emHeight;
 
     // Ensure emAscent + emDescent == emHeight
     gfxFloat sum = aMetrics->emAscent + aMetrics->emDescent;
     aMetrics->emAscent = sum > 0.0 ?
         aMetrics->emAscent * aMetrics->emHeight / sum : 0.0;
     aMetrics->emDescent = aMetrics->emHeight - aMetrics->emAscent;
--- a/gfx/thebes/gfxFontUtils.h
+++ b/gfx/thebes/gfxFontUtils.h
@@ -38,16 +38,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef GFX_FONT_UTILS_H
 #define GFX_FONT_UTILS_H
 
 #include "gfxTypes.h"
 
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "prcpucfg.h"
 
 #include "nsDataHashtable.h"
 
 #include "nsITimer.h"
 #include "nsCOMPtr.h"
 #include "nsIRunnable.h"
 #include "nsThreadUtils.h"
@@ -117,17 +118,17 @@ public:
         if (!hasBlocksInRange) return PR_FALSE;
 
         Block *block;
         PRUint32 i, start, end;
         
         // first block, check bits
         if ((block = mBlocks[startBlock])) {
             start = aStart;
-            end = PR_MIN(aEnd, ((startBlock+1) << BLOCK_INDEX_SHIFT) - 1);
+            end = NS_MIN(aEnd, ((startBlock+1) << BLOCK_INDEX_SHIFT) - 1);
             for (i = start; i <= end; i++) {
                 if ((block->mBits[(i>>3) & (BLOCK_SIZE - 1)]) & (1 << (i & 0x7)))
                     return PR_TRUE;
             }
         }
         if (endBlock == startBlock) return PR_FALSE;
 
         // [2..n-1] blocks check bytes
@@ -205,17 +206,17 @@ public:
                     return;
                 mBlocks[i] = block;
 
                 if (fullBlock)
                     continue;
             }
 
             const PRUint32 start = aStart > blockFirstBit ? aStart - blockFirstBit : 0;
-            const PRUint32 end = PR_MIN(aEnd - blockFirstBit, BLOCK_SIZE_BITS - 1);
+            const PRUint32 end = NS_MIN<PRUint32>(aEnd - blockFirstBit, BLOCK_SIZE_BITS - 1);
 
             for (PRUint32 bit = start; bit <= end; ++bit) {
                 block->mBits[bit>>3] |= 1 << (bit & 0x7);
             }
         }
     }
 
     void clear(PRUint32 aIndex) {
@@ -249,17 +250,17 @@ public:
             Block *block = mBlocks[i];
             if (!block) {
                 // any nonexistent block is implicitly all clear,
                 // so there's no need to even create it
                 continue;
             }
 
             const PRUint32 start = aStart > blockFirstBit ? aStart - blockFirstBit : 0;
-            const PRUint32 end = PR_MIN(aEnd - blockFirstBit, BLOCK_SIZE_BITS - 1);
+            const PRUint32 end = NS_MIN<PRUint32>(aEnd - blockFirstBit, BLOCK_SIZE_BITS - 1);
 
             for (PRUint32 bit = start; bit <= end; ++bit) {
                 block->mBits[bit>>3] &= ~(1 << (bit & 0x7));
             }
         }
     }
 
     PRUint32 GetSize() {
--- a/gfx/thebes/gfxGDIFont.cpp
+++ b/gfx/thebes/gfxGDIFont.cpp
@@ -369,17 +369,17 @@ gfxGDIFont::Initialize()
     }
 
     mMetrics->internalLeading = metrics.tmInternalLeading;
     mMetrics->externalLeading = metrics.tmExternalLeading;
     mMetrics->maxHeight = metrics.tmHeight;
     mMetrics->maxAscent = metrics.tmAscent;
     mMetrics->maxDescent = metrics.tmDescent;
     mMetrics->maxAdvance = metrics.tmMaxCharWidth;
-    mMetrics->aveCharWidth = PR_MAX(1, metrics.tmAveCharWidth);
+    mMetrics->aveCharWidth = NS_MAX<gfxFloat>(1, metrics.tmAveCharWidth);
     // The font is monospace when TMPF_FIXED_PITCH is *not* set!
     // See http://msdn2.microsoft.com/en-us/library/ms534202(VS.85).aspx
     if (!(metrics.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
         mMetrics->maxAdvance = mMetrics->aveCharWidth;
     }
 
     // Cache the width of a single space.
     SIZE size;
--- a/gfx/thebes/gfxGDIFontList.cpp
+++ b/gfx/thebes/gfxGDIFontList.cpp
@@ -429,17 +429,17 @@ GDIFontEntry::InitLogFont(const nsAStrin
     mLogFont.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
     // always force lfItalic if we want it.  Font selection code will
     // do its best to give us an italic font entry, but if no face exists
     // it may give us a regular one based on weight.  Windows should
     // do fake italic for us in that case.
     mLogFont.lfItalic         = mItalic;
     mLogFont.lfWeight         = mWeight;
 
-    int len = PR_MIN(aName.Length(), LF_FACESIZE - 1);
+    int len = NS_MIN<int>(aName.Length(), LF_FACESIZE - 1);
     memcpy(&mLogFont.lfFaceName, nsPromiseFlatString(aName).get(), len * 2);
     mLogFont.lfFaceName[len] = '\0';
 }
 
 GDIFontEntry* 
 GDIFontEntry::CreateFontEntry(const nsAString& aName, gfxWindowsFontType aFontType, 
                                   PRBool aItalic, PRUint16 aWeight, 
                                   gfxUserFontData* aUserFontData)
@@ -463,17 +463,17 @@ GDIFontFamily::FamilyAddStylesProc(const
                                         const NEWTEXTMETRICEXW *nmetrics,
                                         DWORD fontType, LPARAM data)
 {
     const NEWTEXTMETRICW& metrics = nmetrics->ntmTm;
     LOGFONTW logFont = lpelfe->elfLogFont;
     GDIFontFamily *ff = reinterpret_cast<GDIFontFamily*>(data);
 
     // Some fonts claim to support things > 900, but we don't so clamp the sizes
-    logFont.lfWeight = PR_MAX(PR_MIN(logFont.lfWeight, 900), 100);
+    logFont.lfWeight = NS_MAX<LONG>(NS_MIN<LONG>(logFont.lfWeight, 900), 100);
 
     gfxWindowsFontType feType = GDIFontEntry::DetermineFontType(metrics, fontType);
 
     GDIFontEntry *fe = nsnull;
     for (PRUint32 i = 0; i < ff->mAvailableFonts.Length(); ++i) {
         fe = static_cast<GDIFontEntry*>(ff->mAvailableFonts[i].get());
         if (feType > fe->mFontType) {
             // if the new type is better than the old one, remove the old entries
@@ -546,17 +546,17 @@ GDIFontFamily::FindStyleVariations()
 
     HDC hdc = GetDC(nsnull);
     SetGraphicsMode(hdc, GM_ADVANCED);
 
     LOGFONTW logFont;
     memset(&logFont, 0, sizeof(LOGFONTW));
     logFont.lfCharSet = DEFAULT_CHARSET;
     logFont.lfPitchAndFamily = 0;
-    PRUint32 l = PR_MIN(mName.Length(), LF_FACESIZE - 1);
+    PRUint32 l = NS_MIN<PRUint32>(mName.Length(), LF_FACESIZE - 1);
     memcpy(logFont.lfFaceName,
            nsPromiseFlatString(mName).get(),
            l * sizeof(PRUnichar));
     logFont.lfFaceName[l] = 0;
 
     EnumFontFamiliesExW(hdc, &logFont,
                         (FONTENUMPROCW)GDIFontFamily::FamilyAddStylesProc,
                         (LPARAM)this, 0);
@@ -815,17 +815,17 @@ public:
 
     unsigned long Read(void *outBuffer, const unsigned long aBytesToRead)
     {
         PRUint32 bytesLeft = aBytesToRead;  // bytes left in the out buffer
         PRUint8 *out = static_cast<PRUint8*> (outBuffer);
 
         while (mCurrentChunk < mNumChunks && bytesLeft) {
             FontDataChunk& currentChunk = mDataChunks[mCurrentChunk];
-            PRUint32 bytesToCopy = PR_MIN(bytesLeft, 
+            PRUint32 bytesToCopy = NS_MIN(bytesLeft, 
                                           currentChunk.mLength - mChunkOffset);
             memcpy(out, currentChunk.mData + mChunkOffset, bytesToCopy);
             bytesLeft -= bytesToCopy;
             mChunkOffset += bytesToCopy;
             out += bytesToCopy;
 
             NS_ASSERTION(mChunkOffset <= currentChunk.mLength, "oops, buffer overrun");
 
@@ -883,17 +883,17 @@ gfxGDIFontList::MakePlatformFont(const g
     // for TTF fonts, first try using the t2embed library
     if (!isCFF) {
         // TrueType-style glyphs, use EOT library
         AutoFallibleTArray<PRUint8,2048> eotHeader;
         PRUint8 *buffer;
         PRUint32 eotlen;
 
         isEmbedded = PR_TRUE;
-        PRUint32 nameLen = PR_MIN(uniqueName.Length(), LF_FACESIZE - 1);
+        PRUint32 nameLen = NS_MIN<PRUint32>(uniqueName.Length(), LF_FACESIZE - 1);
         nsPromiseFlatString fontName(Substring(uniqueName, 0, nameLen));
         
         FontDataOverlay overlayNameData = {0, 0, 0};
 
         rv = gfxFontUtils::MakeEOTHeader(aFontData, aLength, &eotHeader, 
                                          &overlayNameData);
         if (NS_SUCCEEDED(rv)) {
 
--- a/gfx/thebes/gfxHarfBuzzShaper.cpp
+++ b/gfx/thebes/gfxHarfBuzzShaper.cpp
@@ -32,16 +32,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "prmem.h"
 #include "nsString.h"
 #include "nsBidiUtils.h"
 #include "nsMathUtils.h"
 
 #include "gfxTypes.h"
 
 #include "gfxContext.h"
@@ -330,17 +331,17 @@ GetKernValueFmt0(const void* aSubtable,
             hi = mid;
         }
     }
 
     if (lo < limit && KERN_PAIR_KEY(lo->left, lo->right) == key) {
         if (aIsOverride) {
             aValue = PRInt16(lo->value);
         } else if (aIsMinimum) {
-            aValue = PR_MAX(aValue, PRInt16(lo->value));
+            aValue = NS_MAX(aValue, PRInt32(lo->value));
         } else {
             aValue += PRInt16(lo->value);
         }
     }
 }
 
 // Get kerning value from Apple (version 1.0) kern table,
 // subtable format 2 (simple N x M array of kerning values)
@@ -1042,17 +1043,17 @@ gfxHarfBuzzShaper::SetGlyphsFromRun(gfxC
             charEnd += 1;
             while (charEnd != charLimit && charToGlyph[charEnd] == NO_GLYPH) {
                 charEnd += 1;
             }
 
             // find the maximum glyph index covered by the clump so far
             for (PRInt32 i = charStart; i < charEnd; ++i) {
                 if (charToGlyph[i] != NO_GLYPH) {
-                    glyphEnd = PR_MAX(glyphEnd, charToGlyph[i] + 1);
+                    glyphEnd = NS_MAX(glyphEnd, charToGlyph[i] + 1);
                     // update extent of glyph range
                 }
             }
 
             if (glyphEnd == glyphStart + 1) {
                 // for the common case of a single-glyph clump,
                 // we can skip the following checks
                 break;
--- a/gfx/thebes/gfxImageSurface.cpp
+++ b/gfx/thebes/gfxImageSurface.cpp
@@ -207,17 +207,17 @@ gfxImageSurface::CopyFrom(gfxImageSurfac
         !(other->mFormat == ImageFormatRGB24 && mFormat == ImageFormatARGB32))
     {
         return PR_FALSE;
     }
 
     if (other->mStride == mStride) {
         memcpy (mData, other->mData, mStride * mSize.height);
     } else {
-        int lineSize = PR_MIN(other->mStride, mStride);
+        int lineSize = NS_MIN(other->mStride, mStride);
         for (int i = 0; i < mSize.height; i++) {
             unsigned char *src = other->mData + other->mStride * i;
             unsigned char *dst = mData + mStride * i;
 
             memcpy (dst, src, lineSize);
         }
     }
 
--- a/gfx/thebes/gfxMacFont.cpp
+++ b/gfx/thebes/gfxMacFont.cpp
@@ -223,17 +223,17 @@ gfxMacFont::InitMetrics()
         char warnBuf[1024];
         sprintf(warnBuf, "Bad font metrics for: %s (invalid unitsPerEm value)",
                 NS_ConvertUTF16toUTF8(mFontEntry->Name()).get());
         NS_WARNING(warnBuf);
 #endif
         return;
     }
 
-    mAdjustedSize = PR_MAX(mStyle.size, 1.0f);
+    mAdjustedSize = NS_MAX(mStyle.size, 1.0);
     mFUnitsConvFactor = mAdjustedSize / upem;
 
     // For CFF fonts, when scaling values read from CGFont* APIs, we need to
     // use CG's idea of unitsPerEm, which may differ from the "true" value in
     // the head table of the font (see bug 580863)
     gfxFloat cgConvFactor;
     if (static_cast<MacOSFontEntry*>(mFontEntry.get())->IsCFF()) {
         cgConvFactor = mAdjustedSize / ::CGFontGetUnitsPerEm(mCGFont);
--- a/gfx/thebes/gfxOS2Fonts.cpp
+++ b/gfx/thebes/gfxOS2Fonts.cpp
@@ -125,17 +125,17 @@ static void FillMetricsDefaults(gfxFont:
     aMetrics->superscriptOffset = aMetrics->xHeight;
     aMetrics->subscriptOffset = aMetrics->xHeight;
 }
 
 // Snap a line to pixels while keeping the center and size of the
 // line as close to the original position as possible.
 static void SnapLineToPixels(gfxFloat& aOffset, gfxFloat& aSize)
 {
-    gfxFloat snappedSize = PR_MAX(NS_floor(aSize + 0.5), 1.0);
+    gfxFloat snappedSize = NS_MAX(NS_floor(aSize + 0.5), 1.0);
     // Correct offset for change in size
     gfxFloat offset = aOffset - 0.5 * (aSize - snappedSize);
     // Snap offset
     aOffset = NS_floor(offset + 0.5);
     aSize = snappedSize;
 }
 
 // gfxOS2Font::GetMetrics()
@@ -235,22 +235,22 @@ const gfxFont::Metrics& gfxOS2Font::GetM
         mAdjustedSize = GetStyle()->GetAdjustedSize(aspect);
         mMetrics->emHeight = mAdjustedSize;
     }
 
     // now load the OS/2 TrueType table to access some more properties
     TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
     if (os2 && os2->version != 0xFFFF) { // should be there if not old Mac font
         // if we are here we can improve the avgCharWidth
-        mMetrics->aveCharWidth = PR_MAX(mMetrics->aveCharWidth,
+        mMetrics->aveCharWidth = NS_MAX(mMetrics->aveCharWidth,
                                         os2->xAvgCharWidth * xScale);
 
-        mMetrics->superscriptOffset = PR_MAX(os2->ySuperscriptYOffset * yScale, 1.0);
+        mMetrics->superscriptOffset = NS_MAX(os2->ySuperscriptYOffset * yScale, 1.0);
         // some fonts have the incorrect sign (from gfxPangoFonts)
-        mMetrics->subscriptOffset   = PR_MAX(fabs(os2->ySubscriptYOffset * yScale),
+        mMetrics->subscriptOffset   = NS_MAX(fabs(os2->ySubscriptYOffset * yScale),
                                              1.0);
         mMetrics->strikeoutOffset   = os2->yStrikeoutPosition * yScale;
         mMetrics->strikeoutSize     = os2->yStrikeoutSize * yScale;
     } else {
         // use fractions of emHeight instead of xHeight for these to be more robust
         mMetrics->superscriptOffset = mMetrics->emHeight * 0.5;
         mMetrics->subscriptOffset   = mMetrics->emHeight * 0.2;
         mMetrics->strikeoutOffset   = mMetrics->emHeight * 0.3;
@@ -262,21 +262,21 @@ const gfxFont::Metrics& gfxOS2Font::GetM
     mMetrics->underlineOffset = face->underline_position * yScale;
     mMetrics->underlineSize   = face->underline_thickness * yScale;
 
     // descents are negative in FT but Thebes wants them positive
     mMetrics->emAscent        = face->ascender * yScale;
     mMetrics->emDescent       = -face->descender * yScale;
     mMetrics->maxHeight       = face->height * yScale;
     // the max units determine frame heights, better be generous
-    mMetrics->maxAscent       = PR_MAX(face->bbox.yMax * yScale,
+    mMetrics->maxAscent       = NS_MAX(face->bbox.yMax * yScale,
                                        mMetrics->emAscent);
-    mMetrics->maxDescent      = PR_MAX(-face->bbox.yMin * yScale,
+    mMetrics->maxDescent      = NS_MAX(-face->bbox.yMin * yScale,
                                        mMetrics->emDescent);
-    mMetrics->maxAdvance      = PR_MAX(face->max_advance_width * xScale,
+    mMetrics->maxAdvance      = NS_MAX(face->max_advance_width * xScale,
                                        mMetrics->aveCharWidth);
 
     // leadings are not available directly (only for WinFNTs);
     // better compute them on our own, to get integer values and make
     // layout happy (see // LockedFTFace::GetMetrics in gfxPangoFonts.cpp)
     mMetrics->internalLeading = NS_floor(mMetrics->maxHeight
                                          - mMetrics->emHeight + 0.5);
     gfxFloat lineHeight = NS_floor(mMetrics->maxHeight + 0.5);
--- a/gfx/thebes/gfxRect.h
+++ b/gfx/thebes/gfxRect.h
@@ -33,16 +33,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef GFX_RECT_H
 #define GFX_RECT_H
 
+#include "nsAlgorithm.h"
 #include "gfxTypes.h"
 #include "gfxPoint.h"
 #include "gfxCore.h"
 #include "nsDebug.h"
 #include "mozilla/BaseMargin.h"
 #include "mozilla/BaseRect.h"
 #include "nsRect.h"
 
--- a/gfx/thebes/gfxSkipChars.cpp
+++ b/gfx/thebes/gfxSkipChars.cpp
@@ -235,17 +235,17 @@ gfxSkipCharsIterator::IsOriginalCharSkip
 void
 gfxSkipCharsBuilder::FlushRun()
 {
     NS_ASSERTION((mBuffer.Length() & 1) == mRunSkipped,
                  "out of sync?");
     // Fill in buffer entries starting at mBufferLength, as many as necessary
     PRUint32 charCount = mRunCharCount;
     for (;;) {
-        PRUint32 chars = PR_MIN(255, charCount);
+        PRUint32 chars = NS_MIN<PRUint32>(255, charCount);
         if (!mBuffer.AppendElement(chars)) {
             mInErrorState = PR_TRUE;
             return;
         }
         charCount -= chars;
         if (charCount == 0)
             break;
         if (!mBuffer.AppendElement(0)) {
--- a/intl/uconv/src/nsConverterInputStream.cpp
+++ b/intl/uconv/src/nsConverterInputStream.cpp
@@ -243,17 +243,17 @@ nsConverterInputStream::Fill(nsresult * 
     if (NS_FAILED(*aErrorCode) && mReplacementChar) {
       NS_ASSERTION(0 < mUnicharData->GetBufferSize() - mUnicharDataLength,
                    "Decoder returned an error but filled the output buffer! "
                    "Should not happen.");
       mUnicharData->GetBuffer()[mUnicharDataLength++] = mReplacementChar;
       ++srcConsumed;
       // XXX this is needed to make sure we don't underrun our buffer;
       // bug 160784 again
-      srcConsumed = PR_MAX(srcConsumed, 0);
+      srcConsumed = NS_MAX<PRUint32>(srcConsumed, 0);
       mConverter->Reset();
     }
     NS_ASSERTION(srcConsumed <= mByteData->GetLength(),
                  "Whoa.  The converter should have returned NS_OK_UDEC_MOREINPUT before this point!");
   } while (mReplacementChar &&
            NS_FAILED(*aErrorCode) &&
            mUnicharData->GetBufferSize() > mUnicharDataLength);
 
--- a/intl/uconv/src/nsUTF8ToUnicode.cpp
+++ b/intl/uconv/src/nsUTF8ToUnicode.cpp
@@ -30,16 +30,17 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+#include "nsAlgorithm.h"
 #include "nsUCSupport.h"
 #include "nsUTF8ToUnicode.h"
 #include "mozilla/SSE.h"
 
 #define UNICODE_BYTE_ORDER_MARK    0xFEFF
 
 static PRUnichar* EmitSurrogatePair(PRUint32 ucs4, PRUnichar* aDest)
 {
@@ -244,17 +245,17 @@ NS_IMETHODIMP nsUTF8ToUnicode::Convert(c
   if (mFirst && aSrcLen && (0 == (0x80 & (*aSrc))))
     mFirst = PR_FALSE;
 
   for (in = aSrc; ((in < inend) && (out < outend)); ++in) {
     if (0 == mState) {
       // When mState is zero we expect either a US-ASCII character or a
       // multi-octet sequence.
       if (0 == (0x80 & (*in))) {
-        PRInt32 max_loops = PR_MIN(inend - in, outend - out);
+        PRInt32 max_loops = NS_MIN(inend - in, outend - out);
         Convert_ascii_run(in, out, max_loops);
         --in; // match the rest of the cases
         mBytes = 1;
       } else if (0xC0 == (0xE0 & (*in))) {
         // First octet of 2 octet sequence
         mUcs4 = (PRUint32)(*in);
         mUcs4 = (mUcs4 & 0x1F) << 6;
         mState = 1;
--- a/intl/uconv/util/nsUCSupport.cpp
+++ b/intl/uconv/util/nsUCSupport.cpp
@@ -32,16 +32,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "pratom.h"
+#include "nsAlgorithm.h"
 #include "nsIComponentManager.h"
 #include "nsUCSupport.h"
 #include "nsUnicodeDecodeHelper.h"
 #include "nsUnicodeEncodeHelper.h"
 
 #define DEFAULT_BUFFER_CAPACITY 16
 
 // XXX review the buffer growth limitation code
@@ -101,17 +102,17 @@ nsBufferDecoderSupport::nsBufferDecoderS
 
 nsBufferDecoderSupport::~nsBufferDecoderSupport()
 {
   delete [] mBuffer;
 }
 
 void nsBufferDecoderSupport::FillBuffer(const char ** aSrc, PRInt32 aSrcLength)
 {
-  PRInt32 bcr = PR_MIN(mBufferCapacity - mBufferLength, aSrcLength);
+  PRInt32 bcr = NS_MIN(mBufferCapacity - mBufferLength, aSrcLength);
   memcpy(mBuffer + mBufferLength, *aSrc, bcr);
   mBufferLength += bcr;
   (*aSrc) += bcr;
 }
 
 //----------------------------------------------------------------------
 // Subclassing of nsBasicDecoderSupport class [implementation]
 
--- a/layout/base/nsCSSColorUtils.h
+++ b/layout/base/nsCSSColorUtils.h
@@ -42,17 +42,17 @@
 
 #include "nsColor.h"
 
 // "Sufficient contrast" is determined by
 // "Techniques For Accessibility Evalution And Repair Tools".
 // See http://www.w3.org/TR/AERT#color-contrast
 #define NS_SUFFICIENT_LUMINOSITY_DIFFERENCE 125000
 #define NS_LUMINOSITY_DIFFERENCE(a, b) \
-          PR_ABS(NS_GetLuminosity(a) - NS_GetLuminosity(b))
+          NS_ABS(NS_GetLuminosity(a) - NS_GetLuminosity(b))
 
 // To determine colors based on the background brightness and border color
 void NS_GetSpecial3DColors(nscolor aResult[2],
                            nscolor aBackgroundColor,
                            nscolor aBorderColor);
 
 // Determins brightness for a specific color
 int NS_GetBrightness(PRUint8 aRed, PRUint8 aGreen, PRUint8 aBlue);
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -1820,20 +1820,20 @@ ComputeRadialGradientLine(nsPresContext*
       ConvertGradientValueToPixels(aGradient->mBgPosX, aBoxSize.width,
                                    appUnitsPerPixel),
       ConvertGradientValueToPixels(aGradient->mBgPosY, aBoxSize.height,
                                    appUnitsPerPixel));
   }
 
   // Compute gradient shape: the x and y radii of an ellipse.
   double radiusX, radiusY;
-  double leftDistance = PR_ABS(aLineStart->x);
-  double rightDistance = PR_ABS(aBoxSize.width - aLineStart->x);
-  double topDistance = PR_ABS(aLineStart->y);
-  double bottomDistance = PR_ABS(aBoxSize.height - aLineStart->y);
+  double leftDistance = NS_ABS(aLineStart->x);
+  double rightDistance = NS_ABS(aBoxSize.width - aLineStart->x);
+  double topDistance = NS_ABS(aLineStart->y);
+  double bottomDistance = NS_ABS(aBoxSize.height - aLineStart->y);
   switch (aGradient->mSize) {
   case NS_STYLE_GRADIENT_SIZE_CLOSEST_SIDE:
     radiusX = NS_MIN(leftDistance, rightDistance);
     radiusY = NS_MIN(topDistance, bottomDistance);
     if (aGradient->mShape == NS_STYLE_GRADIENT_SHAPE_CIRCULAR) {
       radiusX = radiusY = NS_MIN(radiusX, radiusY);
     }
     break;
--- a/layout/mathml/nsMathMLChar.cpp
+++ b/layout/mathml/nsMathMLChar.cpp
@@ -883,26 +883,26 @@ static PRBool
 IsSizeOK(nsPresContext* aPresContext, nscoord a, nscoord b, PRUint32 aHint)
 {
   // Normal: True if 'a' is around +/-10% of the target 'b' (10% is
   // 1-DelimiterFactor). This often gives a chance to the base size to
   // win, especially in the context of <mfenced> without tall elements
   // or in sloppy markups without protective <mrow></mrow>
   PRBool isNormal =
     (aHint & NS_STRETCH_NORMAL)
-    && PRBool(float(PR_ABS(a - b))
+    && PRBool(float(NS_ABS(a - b))
               < (1.0f - NS_MATHML_DELIMITER_FACTOR) * float(b));
   // Nearer: True if 'a' is around max{ +/-10% of 'b' , 'b' - 5pt },
   // as documented in The TeXbook, Ch.17, p.152.
   // i.e. within 10% and within 5pt
   PRBool isNearer = PR_FALSE;
   if (aHint & (NS_STRETCH_NEARER | NS_STRETCH_LARGEOP)) {
     float c = NS_MAX(float(b) * NS_MATHML_DELIMITER_FACTOR,
                      float(b) - nsPresContext::CSSPointsToAppUnits(NS_MATHML_DELIMITER_SHORTFALL_POINTS));
-    isNearer = PRBool(float(PR_ABS(b - a)) <= (float(b) - c));
+    isNearer = PRBool(float(NS_ABS(b - a)) <= (float(b) - c));
   }
   // Smaller: Mainly for transitory use, to compare two candidate
   // choices
   PRBool isSmaller =
     (aHint & NS_STRETCH_SMALLER)
     && PRBool((float(a) >= (NS_MATHML_DELIMITER_FACTOR * float(b)))
               && (a <= b));
   // Larger: Critical to the sqrt code to ensure that the radical
@@ -919,17 +919,17 @@ IsSizeBetter(nscoord a, nscoord olda, ns
   if (0 == olda)
     return PR_TRUE;
   if (aHint & (NS_STRETCH_LARGER | NS_STRETCH_LARGEOP))
     return (a >= olda) ? (olda < b) : (a >= b);
   if (aHint & NS_STRETCH_SMALLER)
     return (a <= olda) ? (olda > b) : (a <= b);
 
   // XXXkt prob want log scale here i.e. 1.5 is closer to 1 than 0.5
-  return PR_ABS(a - b) < PR_ABS(olda - b);
+  return NS_ABS(a - b) < NS_ABS(olda - b);
 }
 
 // We want to place the glyphs even when they don't fit at their
 // full extent, i.e., we may clip to tolerate a small amount of
 // overlap between the parts. This is important to cater for fonts
 // with long glues.
 static nscoord
 ComputeSizeFromParts(nsPresContext* aPresContext,
--- a/layout/style/nsStyleAnimation.cpp
+++ b/layout/style/nsStyleAnimation.cpp
@@ -277,34 +277,34 @@ nsStyleAnimation::ComputeDistance(nsCSSP
       return PR_FALSE;
 
     case eUnit_Enumerated:
       switch (aProperty) {
         case eCSSProperty_font_stretch: {
           // just like eUnit_Integer.
           PRInt32 startInt = aStartValue.GetIntValue();
           PRInt32 endInt = aEndValue.GetIntValue();
-          aDistance = PR_ABS(endInt - startInt);
+          aDistance = NS_ABS(endInt - startInt);
           return PR_TRUE;
         }
         default:
           return PR_FALSE;
       }
    case eUnit_Visibility: {
       PRInt32 startVal =
         aStartValue.GetIntValue() == NS_STYLE_VISIBILITY_VISIBLE;
       PRInt32 endVal =
         aEndValue.GetIntValue() == NS_STYLE_VISIBILITY_VISIBLE;
-      aDistance = PR_ABS(startVal - endVal);
+      aDistance = NS_ABS(startVal - endVal);
       return PR_TRUE;
     }
     case eUnit_Integer: {
       PRInt32 startInt = aStartValue.GetIntValue();
       PRInt32 endInt = aEndValue.GetIntValue();
-      aDistance = PR_ABS(endInt - startInt);
+      aDistance = NS_ABS(endInt - startInt);
       return PR_TRUE;
     }
     case eUnit_Coord: {
       nscoord startCoord = aStartValue.GetCoordValue();
       nscoord endCoord = aEndValue.GetCoordValue();
       aDistance = fabs(double(endCoord - startCoord));
       return PR_TRUE;
     }
@@ -1105,17 +1105,17 @@ DecomposeMatrix(const nsStyleTransformMa
   D -= B * XYshear;
 
   float scaleY = sqrt(C * C + D * D);
   C /= scaleY;
   D /= scaleY;
   XYshear /= scaleY;
 
  // A*D - B*C should now be 1 or -1
-  NS_ASSERTION(0.99 < PR_ABS(A*D - B*C) && PR_ABS(A*D - B*C) < 1.01,
+  NS_ASSERTION(0.99 < NS_ABS(A*D - B*C) && NS_ABS(A*D - B*C) < 1.01,
                "determinant should now be 1 or -1");
   if (A * D < B * C) {
     A = -A;
     B = -B;
     C = -C;
     D = -D;
     XYshear = -XYshear;
     scaleX = -scaleX;
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -6267,17 +6267,17 @@ BCPaintBorderIterator::SetDamageArea(nsR
       if (!colFrame) ABORT1(PR_FALSE);
       nsSize size = colFrame->GetSize();
       mInitialOffsetX += mColInc * size.width;
     }
   }
   if (!haveIntersect)
     return PR_FALSE;
   mDamageArea = nsRect(startColIndex, startRowIndex,
-                       1 + PR_ABS(PRInt32(endColIndex - startColIndex)),
+                       1 + NS_ABS(PRInt32(endColIndex - startColIndex)),
                        1 + endRowIndex - startRowIndex);
 
   Reset();
   mVerInfo = new BCVerticalSeg[mDamageArea.width + 1];
   if (!mVerInfo)
     return PR_FALSE;
   return PR_TRUE;
 }
@@ -6606,17 +6606,17 @@ BCVerticalSeg::Start(BCPaintBorderIterat
   mozilla::css::Side ownerSide   = NS_SIDE_TOP;
   PRPackedBool bevel       = PR_FALSE;
 
 
   nscoord cornerSubWidth  = (aIter.mBCData) ?
                                aIter.mBCData->GetCorner(ownerSide, bevel) : 0;
 
   PRBool  topBevel        = (aVerSegWidth > 0) ? bevel : PR_FALSE;
-  BCPixelSize maxHorSegHeight = PR_MAX(aIter.mPrevHorSegHeight, aHorSegHeight);
+  BCPixelSize maxHorSegHeight = NS_MAX(aIter.mPrevHorSegHeight, aHorSegHeight);
   nscoord offset          = CalcVerCornerOffset(ownerSide, cornerSubWidth,
                                                 maxHorSegHeight, PR_TRUE,
                                                 topBevel);
 
   mTopBevelOffset   = (topBevel) ?
                       nsPresContext::CSSPixelsToAppUnits(maxHorSegHeight): 0;
   // XXX this assumes that only corners where 2 segments join can be beveled
   mTopBevelSide     = (aHorSegHeight > 0) ? NS_SIDE_RIGHT : NS_SIDE_LEFT;
@@ -6668,17 +6668,17 @@ BCVerticalSeg::GetBottomCorner(BCPaintBo
 {
    mozilla::css::Side ownerSide = NS_SIDE_TOP;
    nscoord cornerSubWidth = 0;
    PRPackedBool bevel = PR_FALSE;
    if (aIter.mBCData) {
      cornerSubWidth = aIter.mBCData->GetCorner(ownerSide, bevel);
    }
    mIsBottomBevel = (mWidth > 0) ? bevel : PR_FALSE;
-   mBottomHorSegHeight = PR_MAX(aIter.mPrevHorSegHeight, aHorSegHeight);
+   mBottomHorSegHeight = NS_MAX(aIter.mPrevHorSegHeight, aHorSegHeight);
    mBottomOffset = CalcVerCornerOffset(ownerSide, cornerSubWidth,
                                     mBottomHorSegHeight,
                                     PR_FALSE, mIsBottomBevel);
    mLength += mBottomOffset;
 }
 
 /**
  * Paint the vertical segment
@@ -6810,17 +6810,17 @@ BCHorizontalSeg::Start(BCPaintBorderIter
 
   mOwner = aBorderOwner;
   nscoord cornerSubWidth  = (aIter.mBCData) ?
                              aIter.mBCData->GetCorner(cornerOwnerSide,
                                                        bevel) : 0;
 
   PRBool  leftBevel = (aHorSegHeight > 0) ? bevel : PR_FALSE;
   PRInt32 relColIndex = aIter.GetRelativeColIndex();
-  nscoord maxVerSegWidth = PR_MAX(aIter.mVerInfo[relColIndex].mWidth,
+  nscoord maxVerSegWidth = NS_MAX(aIter.mVerInfo[relColIndex].mWidth,
                                   aBottomVerSegWidth);
   nscoord offset = CalcHorCornerOffset(cornerOwnerSide, cornerSubWidth,
                                        maxVerSegWidth, PR_TRUE, leftBevel,
                                        aIter.mTableIsLTR);
   mLeftBevelOffset = (leftBevel && (aHorSegHeight > 0)) ? maxVerSegWidth : 0;
   // XXX this assumes that only corners where 2 segments join can be beveled
   mLeftBevelSide   = (aBottomVerSegWidth > 0) ? NS_SIDE_BOTTOM : NS_SIDE_TOP;
   if (aIter.mTableIsLTR) {
@@ -6850,17 +6850,17 @@ BCHorizontalSeg::GetRightCorner(BCPaintB
   nscoord cornerSubWidth = 0;
   PRPackedBool bevel = PR_FALSE;
   if (aIter.mBCData) {
     cornerSubWidth = aIter.mBCData->GetCorner(ownerSide, bevel);
   }
 
   mIsRightBevel = (mWidth > 0) ? bevel : 0;
   PRInt32 relColIndex = aIter.GetRelativeColIndex();
-  nscoord verWidth = PR_MAX(aIter.mVerInfo[relColIndex].mWidth, aLeftSegWidth);
+  nscoord verWidth = NS_MAX(aIter.mVerInfo[relColIndex].mWidth, aLeftSegWidth);
   mEndOffset = CalcHorCornerOffset(ownerSide, cornerSubWidth, verWidth,
                                    PR_FALSE, mIsRightBevel, aIter.mTableIsLTR);
   mLength += mEndOffset;
   mRightBevelOffset = (mIsRightBevel) ?
                        nsPresContext::CSSPixelsToAppUnits(verWidth) : 0;
   mRightBevelSide = (aLeftSegWidth > 0) ? NS_SIDE_BOTTOM : NS_SIDE_TOP;
 }
 
--- a/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
+++ b/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
@@ -1839,17 +1839,17 @@ nsTreeBodyFrame::RowCountChanged(PRInt32
 
   mRowCount += aCount;
 #ifdef DEBUG
   PRInt32 rowCount = mRowCount;
   mView->GetRowCount(&rowCount);
   NS_ASSERTION(rowCount == mRowCount, "row count did not change by the amount suggested, check caller");
 #endif
 
-  PRInt32 count = PR_ABS(aCount);
+  PRInt32 count = NS_ABS(aCount);
   PRInt32 last = GetLastVisibleRow();
   if (aIndex >= mTopRowIndex && aIndex <= last)
     InvalidateRange(aIndex, last);
     
   ScrollParts parts = GetScrollParts();
 
   if (mTopRowIndex == 0) {    
     // Just update the scrollbar and return.
--- a/modules/libpr0n/decoders/nsBMPDecoder.cpp
+++ b/modules/libpr0n/decoders/nsBMPDecoder.cpp
@@ -419,17 +419,17 @@ nsBMPDecoder::WriteInternal(const char* 
                         if (mStateData != RLE_ESCAPE) { // encoded mode
                             // Encoded mode consists of two bytes: 
                             // the first byte (mStateData) specifies the
                             // number of consecutive pixels to be drawn 
                             // using the color index contained in
                             // the second byte
                             // Work around bitmaps that specify too many pixels
                             mState = eRLEStateInitial;
-                            PRUint32 pixelsNeeded = PR_MIN((PRUint32)(mBIH.width - mCurPos), mStateData);
+                            PRUint32 pixelsNeeded = NS_MIN<PRUint32>(mBIH.width - mCurPos, mStateData);
                             if (pixelsNeeded) {
                                 PRUint32* d = mImageData + PIXEL_OFFSET(mCurLine, mCurPos);
                                 mCurPos += pixelsNeeded;
                                 if (mBIH.compression == BI_RLE8) {
                                     do {
                                         SetPixel(d, byte, mColors);
                                         pixelsNeeded --;
                                     } while (pixelsNeeded);
@@ -499,17 +499,17 @@ nsBMPDecoder::WriteInternal(const char* 
                         mState = eRLEStateNeedYDelta;
                         continue;
 
                     case eRLEStateNeedYDelta:
                         // Get the Y Delta and then "handle" the move
                         byte = *aBuffer++;
                         aCount--;
                         mState = eRLEStateInitial;
-                        mCurLine -= PR_MIN(byte, mCurLine);
+                        mCurLine -= NS_MIN<PRInt32>(byte, mCurLine);
                         break;
 
                     case eRLEStateAbsoluteMode: // Absolute Mode
                     case eRLEStateAbsoluteModePadded:
                         if (mStateData) {
                             // In absolute mode, the second byte (mStateData)
                             // represents the number of pixels 
                             // that follow, each of which contains 
--- a/modules/libpr0n/decoders/nsGIFDecoder2.cpp
+++ b/modules/libpr0n/decoders/nsGIFDecoder2.cpp
@@ -622,17 +622,17 @@ nsGIFDecoder2::WriteInternal(const char 
   // Add what we have sofar to the block
   // If previous call to me left something in the hold first complete current block
   // Or if we are filling the colormaps, first complete the colormap
   PRUint8* p = (mGIFStruct.state == gif_global_colormap) ? (PRUint8*)mGIFStruct.global_colormap :
                (mGIFStruct.state == gif_image_colormap) ? (PRUint8*)mColormap :
                (mGIFStruct.bytes_in_hold) ? mGIFStruct.hold : nsnull;
   if (p) {
     // Add what we have sofar to the block
-    PRUint32 l = PR_MIN(len, mGIFStruct.bytes_to_consume);
+    PRUint32 l = NS_MIN(len, mGIFStruct.bytes_to_consume);
     memcpy(p+mGIFStruct.bytes_in_hold, buf, l);
 
     if (l < mGIFStruct.bytes_to_consume) {
       // Not enough in 'buf' to complete current block, get more
       mGIFStruct.bytes_in_hold += l;
       mGIFStruct.bytes_to_consume -= l;
       return;
     }
--- a/modules/libpr0n/decoders/nsICODecoder.cpp
+++ b/modules/libpr0n/decoders/nsICODecoder.cpp
@@ -428,17 +428,17 @@ nsICODecoder::WriteInternal(const char* 
     NS_ASSERTION(mRow, "mRow is null");
     NS_ASSERTION(mImageData, "mImageData is null");
     if (!mRow || !mImageData) {
       PostDataError();
       return;
     }
 
     while (mCurLine > 0 && aCount > 0) {
-      PRUint32 toCopy = PR_MIN(rowSize - mRowBytes, aCount);
+      PRUint32 toCopy = NS_MIN(rowSize - mRowBytes, aCount);
       if (toCopy) {
         memcpy(mRow + mRowBytes, aBuffer, toCopy);
         aCount -= toCopy;
         aBuffer += toCopy;
         mRowBytes += toCopy;
       }
       if (rowSize == mRowBytes) {
         mCurLine--;
--- a/modules/libpr0n/decoders/nsIconDecoder.cpp
+++ b/modules/libpr0n/decoders/nsIconDecoder.cpp
@@ -128,17 +128,17 @@ nsIconDecoder::WriteInternal(const char 
         aBuffer++;
         aCount--;
         mState = iconStateReadPixels;
         break;
 
       case iconStateReadPixels:
 
         // How many bytes are we reading?
-        bytesToRead = PR_MIN(aCount, mPixBytesTotal - mPixBytesRead);
+        bytesToRead = NS_MIN(aCount, mPixBytesTotal - mPixBytesRead);
 
         // Copy the bytes
         memcpy(mImageData + mPixBytesRead, aBuffer, bytesToRead);
 
         // Invalidate
         PostInvalidation(r);
 
         // Book Keeping
--- a/modules/libpr0n/decoders/nsPNGDecoder.cpp
+++ b/modules/libpr0n/decoders/nsPNGDecoder.cpp
@@ -301,17 +301,17 @@ nsPNGDecoder::WriteInternal(const char *
   // If we only want width/height, we don't need to go through libpng
   if (IsSizeDecode()) {
 
     // Are we done?
     if (mHeaderBytesRead == BYTES_NEEDED_FOR_DIMENSIONS)
       return;
 
     // Read data into our header buffer
-    PRUint32 bytesToRead = PR_MIN(aCount, BYTES_NEEDED_FOR_DIMENSIONS -
+    PRUint32 bytesToRead = NS_MIN(aCount, BYTES_NEEDED_FOR_DIMENSIONS -
                                   mHeaderBytesRead);
     memcpy(mHeaderBuf + mHeaderBytesRead, aBuffer, bytesToRead);
     mHeaderBytesRead += bytesToRead;
 
     // If we're done now, verify the data and set up the container
     if (mHeaderBytesRead == BYTES_NEEDED_FOR_DIMENSIONS) {
 
       // Check that the signature bytes are right
--- a/modules/libpr0n/src/RasterImage.cpp
+++ b/modules/libpr0n/src/RasterImage.cpp
@@ -1919,18 +1919,18 @@ RasterImage::DrawFrameTo(imgFrame *aSrc,
   }
   // Outside the destination frame, skip it
   if ((aSrcRect.x > dstRect.width) || (aSrcRect.y > dstRect.height)) {
     return NS_OK;
   }
 
   if (aSrc->GetIsPaletted()) {
     // Larger than the destination frame, clip it
-    PRInt32 width = PR_MIN(aSrcRect.width, dstRect.width - aSrcRect.x);
-    PRInt32 height = PR_MIN(aSrcRect.height, dstRect.height - aSrcRect.y);
+    PRInt32 width = NS_MIN(aSrcRect.width, dstRect.width - aSrcRect.x);
+    PRInt32 height = NS_MIN(aSrcRect.height, dstRect.height - aSrcRect.y);
 
     // The clipped image must now fully fit within destination image frame
     NS_ASSERTION((aSrcRect.x >= 0) && (aSrcRect.y >= 0) &&
                  (aSrcRect.x + width <= dstRect.width) &&
                  (aSrcRect.y + height <= dstRect.height),
                 "RasterImage::DrawFrameTo: Invalid aSrcRect");
 
     // clipped image size may be smaller than source, but not larger
@@ -2572,17 +2572,17 @@ RasterImage::DecodeSomeData(PRUint32 aMa
   NS_ABORT_IF_FALSE(mDecoder, "trying to decode without decoder!");
 
   // If we have nothing to decode, return
   if (mBytesDecoded == mSourceData.Length())
     return NS_OK;
 
 
   // write the proper amount of data
-  PRUint32 bytesToDecode = PR_MIN(aMaxBytes,
+  PRUint32 bytesToDecode = NS_MIN(aMaxBytes,
                                   mSourceData.Length() - mBytesDecoded);
   nsresult rv = WriteToDecoder(mSourceData.Elements() + mBytesDecoded,
                                bytesToDecode);
 
   return rv;
 }
 
 // There are various indicators that tell us we're finished with the decode
--- a/modules/libpr0n/src/imgRequest.cpp
+++ b/modules/libpr0n/src/imgRequest.cpp
@@ -1118,17 +1118,17 @@ NS_IMETHODIMP imgRequest::OnDataAvailabl
                                             contentLength);
         if (NS_SUCCEEDED(rv)) {
           PRInt32 len = contentLength.ToInteger(&rv);
 
           // Pass anything usable on so that the RasterImage can preallocate
           // its source buffer
           if (len > 0) {
             PRUint32 sizeHint = (PRUint32) len;
-            sizeHint = PR_MIN(sizeHint, 20000000); /* Bound by something reasonable */
+            sizeHint = NS_MIN<PRUint32>(sizeHint, 20000000); /* Bound by something reasonable */
             RasterImage* rasterImage = static_cast<RasterImage*>(mImage.get());
             rasterImage->SetSourceSizeHint(sizeHint);
           }
         }
       }
     }
 
     if (imageType == imgIContainer::TYPE_RASTER) {
--- a/modules/libpref/src/prefapi.cpp
+++ b/modules/libpref/src/prefapi.cpp
@@ -470,17 +470,17 @@ nsresult PREF_GetCharPref(const char *pr
             stringVal = pref->userPref.stringVal;
 
         if (stringVal)
         {
             if (*length <= 0)
                 *length = PL_strlen(stringVal) + 1;
             else
             {
-                PL_strncpy(return_buffer, stringVal, PR_MIN((size_t)*length - 1, PL_strlen(stringVal) + 1));
+                PL_strncpy(return_buffer, stringVal, NS_MIN<size_t>(*length - 1, PL_strlen(stringVal) + 1));
                 return_buffer[*length - 1] = '\0';
             }
             rv = NS_OK;
         }
     }
 
     return rv;
 }
--- a/netwerk/base/src/nsBufferedStreams.cpp
+++ b/netwerk/base/src/nsBufferedStreams.cpp
@@ -33,16 +33,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "IPC/IPCMessageUtils.h"
 #include "mozilla/net/NeckoMessageUtils.h"
 
+#include "nsAlgorithm.h"
 #include "nsBufferedStreams.h"
 #include "nsStreamUtils.h"
 #include "nsCRT.h"
 #include "nsNetCID.h"
 #include "nsIClassInfoImpl.h"
 
 #ifdef DEBUG_brendan
 # define METERING
@@ -340,17 +341,17 @@ nsBufferedInputStream::ReadSegments(nsWr
 {
     *result = 0;
 
     if (!mStream)
         return NS_OK;
 
     nsresult rv = NS_OK;
     while (count > 0) {
-        PRUint32 amt = PR_MIN(count, mFillPoint - mCursor);
+        PRUint32 amt = NS_MIN(count, mFillPoint - mCursor);
         if (amt > 0) {
             PRUint32 read = 0;
             rv = writer(this, closure, mBuffer + mCursor, *result, amt, &read);
             if (NS_FAILED(rv)) {
                 // errors returned from the writer end here!
                 rv = NS_OK;
                 break;
             }
@@ -572,17 +573,17 @@ nsBufferedOutputStream::Close()
 }
 
 NS_IMETHODIMP
 nsBufferedOutputStream::Write(const char *buf, PRUint32 count, PRUint32 *result)
 {
     nsresult rv = NS_OK;
     PRUint32 written = 0;
     while (count > 0) {
-        PRUint32 amt = PR_MIN(count, mBufferSize - mCursor);
+        PRUint32 amt = NS_MIN(count, mBufferSize - mCursor);
         if (amt > 0) {
             memcpy(mBuffer + mCursor, buf + written, amt);
             written += amt;
             count -= amt;
             mCursor += amt;
             if (mFillPoint < mCursor)
                 mFillPoint = mCursor;
         }
@@ -663,34 +664,34 @@ nsBufferedOutputStream::WriteFrom(nsIInp
 }
 
 NS_IMETHODIMP
 nsBufferedOutputStream::WriteSegments(nsReadSegmentFun reader, void * closure, PRUint32 count, PRUint32 *_retval)
 {
     *_retval = 0;
     nsresult rv;
     while (count > 0) {
-        PRUint32 left = PR_MIN(count, mBufferSize - mCursor);
+        PRUint32 left = NS_MIN(count, mBufferSize - mCursor);
         if (left == 0) {
             rv = Flush();
             if (NS_FAILED(rv))
               return rv;
 
             continue;
         }
 
         PRUint32 read = 0;
         rv = reader(this, closure, mBuffer + mCursor, *_retval, left, &read);
 
         if (NS_FAILED(rv)) // If we have written some data, return ok
             return (*_retval > 0) ? NS_OK : rv;
         mCursor += read;
         *_retval += read;
         count -= read;
-        mFillPoint = PR_MAX(mFillPoint, mCursor);
+        mFillPoint = NS_MAX(mFillPoint, mCursor);
     }
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsBufferedOutputStream::IsNonBlocking(PRBool *aNonBlocking)
 {
     if (mStream)
--- a/netwerk/base/src/nsFileStreams.h
+++ b/netwerk/base/src/nsFileStreams.h
@@ -33,16 +33,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsFileStreams_h__
 #define nsFileStreams_h__
 
+#include "nsAlgorithm.h"
 #include "nsIFileStreams.h"
 #include "nsIFile.h"
 #include "nsIInputStream.h"
 #include "nsIOutputStream.h"
 #include "nsISafeOutputStream.h"
 #include "nsISeekableStream.h"
 #include "nsILineInputStream.h"
 #include "nsCOMPtr.h"
@@ -188,17 +189,17 @@ public:
     NS_IMETHOD Read(char* aBuf, PRUint32 aCount, PRUint32* aResult);
     NS_IMETHOD Seek(PRInt32 aWhence, PRInt64 aOffset);
 
     static nsresult
     Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
 
 private:
     PRUint32 TruncateSize(PRUint32 aSize) {
-          return (PRUint32)PR_MIN(mLength - mPosition, (PRUint64)aSize);
+          return (PRUint32)NS_MIN<PRUint64>(mLength - mPosition, aSize);
     }
 
     PRUint64 mStart;
     PRUint64 mLength;
     PRUint64 mPosition;
 };
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/netwerk/base/src/nsIncrementalDownload.cpp
+++ b/netwerk/base/src/nsIncrementalDownload.cpp
@@ -691,17 +691,17 @@ NS_IMETHODIMP
 nsIncrementalDownload::OnDataAvailable(nsIRequest *request,
                                        nsISupports *context,
                                        nsIInputStream *input,
                                        PRUint32 offset,
                                        PRUint32 count)
 {
   while (count) {
     PRUint32 space = mChunkSize - mChunkLen;
-    PRUint32 n, len = PR_MIN(space, count);
+    PRUint32 n, len = NS_MIN(space, count);
 
     nsresult rv = input->Read(mChunk + mChunkLen, len, &n);
     if (NS_FAILED(rv))
       return rv;
     if (n != len)
       return NS_ERROR_UNEXPECTED;
 
     count -= n;
--- a/netwerk/base/src/nsSocketTransport2.cpp
+++ b/netwerk/base/src/nsSocketTransport2.cpp
@@ -1945,17 +1945,17 @@ nsSocketTransport::GetTimeout(PRUint32 t
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::SetTimeout(PRUint32 type, PRUint32 value)
 {
     NS_ENSURE_ARG_MAX(type, nsISocketTransport::TIMEOUT_READ_WRITE);
     // truncate overly large timeout values.
-    mTimeouts[type] = (PRUint16) PR_MIN(value, PR_UINT16_MAX);
+    mTimeouts[type] = (PRUint16) NS_MIN(value, PR_UINT16_MAX);
     PostEvent(MSG_TIMEOUT_CHANGED);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::SetQoSBits(PRUint8 aQoSBits)
 {
     // Don't do any checking here of bits.  Why?  Because as of RFC-4594
@@ -2077,17 +2077,17 @@ DumpBytesToFile(const char *path, const 
     FILE *fp = fopen(path, "a");
 
     fprintf(fp, "\n%s [%d bytes]\n", header, n);
 
     const unsigned char *p;
     while (n) {
         p = (const unsigned char *) buf;
 
-        PRInt32 i, row_max = PR_MIN(16, n);
+        PRInt32 i, row_max = NS_MIN(16, n);
 
         for (i = 0; i < row_max; ++i)
             fprintf(fp, "%02x  ", *p++);
         for (i = row_max; i < 16; ++i)
             fprintf(fp, "    ");
 
         p = (const unsigned char *) buf;
         for (i = 0; i < row_max; ++i, ++p) {
--- a/netwerk/base/src/nsStandardURL.cpp
+++ b/netwerk/base/src/nsStandardURL.cpp
@@ -1035,17 +1035,17 @@ nsStandardURL::GetAsciiSpec(nsACString &
     }
 
     if (mSpecEncoding == eEncoding_ASCII) {
         result = mSpec;
         return NS_OK;
     }
 
     // try to guess the capacity required for result...
-    result.SetCapacity(mSpec.Length() + PR_MIN(32, mSpec.Length()/10));
+    result.SetCapacity(mSpec.Length() + NS_MIN<PRUint32>(32, mSpec.Length()/10));
 
     result = Substring(mSpec, 0, mScheme.mLen + 3);
 
     NS_EscapeURL(Userpass(PR_TRUE), esc_OnlyNonASCII | esc_AlwaysCopy, result);
 
     // get escaped host
     nsCAutoString escHostport;
     if (mHost.mLen > 0) {
--- a/netwerk/base/src/nsSyncStreamListener.cpp
+++ b/netwerk/base/src/nsSyncStreamListener.cpp
@@ -173,17 +173,17 @@ nsSyncStreamListener::Read(char     *buf
         *result = 0;
         return NS_OK;
     }
 
     PRUint32 avail;
     if (NS_FAILED(Available(&avail)))
         return mStatus;
 
-    avail = PR_MIN(avail, bufLen);
+    avail = NS_MIN(avail, bufLen);
     mStatus = mPipeIn->Read(buf, avail, result);
     return mStatus;
 }
 
 NS_IMETHODIMP
 nsSyncStreamListener::ReadSegments(nsWriteSegmentFun  writer,
                                    void              *closure,
                                    PRUint32           count,
@@ -193,17 +193,17 @@ nsSyncStreamListener::ReadSegments(nsWri
         *result = 0;
         return NS_OK;
     }
 
     PRUint32 avail;
     if (NS_FAILED(Available(&avail)))
         return mStatus;
 
-    avail = PR_MIN(avail, count);
+    avail = NS_MIN(avail, count);
     mStatus = mPipeIn->ReadSegments(writer, closure, avail, result);
     return mStatus;
 }
 
 NS_IMETHODIMP
 nsSyncStreamListener::IsNonBlocking(PRBool *result)
 {
     *result = PR_FALSE;
--- a/netwerk/cache/nsCacheService.cpp
+++ b/netwerk/cache/nsCacheService.cpp
@@ -352,17 +352,17 @@ nsCacheProfilePrefObserver::Remove()
         return;
     for (unsigned int i=0; i<NS_ARRAY_LENGTH(prefList); i++)
         prefs->RemoveObserver(prefList[i], this); // remove cache pref observers
 }
 
 void
 nsCacheProfilePrefObserver::SetDiskCacheCapacity(PRInt32 capacity)
 {
-    mDiskCacheCapacity = PR_MAX(0, capacity);
+    mDiskCacheCapacity = NS_MAX(0, capacity);
 }
 
 
 NS_IMETHODIMP
 nsCacheProfilePrefObserver::Observe(nsISupports *     subject,
                                     const char *      topic,
                                     const PRUnichar * data_unicode)
 {
@@ -413,17 +413,17 @@ nsCacheProfilePrefObserver::Observe(nsIS
             }
 
         } else if (!strcmp(DISK_CACHE_CAPACITY_PREF, data.get())) {
 
             PRInt32 capacity = 0;
             rv = branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &capacity);
             if (NS_FAILED(rv))  
                 return rv;
-            mDiskCacheCapacity = PR_MAX(0, capacity);
+            mDiskCacheCapacity = NS_MAX(0, capacity);
             nsCacheService::SetDiskCacheCapacity(mDiskCacheCapacity);
        
         // Update the cache capacity when smart sizing is turned on/off 
         } else if (!strcmp(DISK_CACHE_SMART_SIZE_ENABLED_PREF, data.get())) {
             // Is the update because smartsizing was turned on, or off?
             PRBool smartSizeEnabled;
             rv = branch->GetBoolPref(DISK_CACHE_SMART_SIZE_ENABLED_PREF,
                                      &smartSizeEnabled);
@@ -443,17 +443,17 @@ nsCacheProfilePrefObserver::Observe(nsIS
                 nsCOMPtr<nsIRunnable> event = 
                     new nsGetSmartSizeEvent(false, cachePath);
                 rv = nsCacheService::DispatchToCacheIOThread(event);
             } else {
                 // Smart sizing switched off: use user specified size
                 rv = branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &newCapacity);
                 if (NS_FAILED(rv)) 
                     return rv;
-                mDiskCacheCapacity = PR_MAX(0, newCapacity);
+                mDiskCacheCapacity = NS_MAX(0, newCapacity);
                 nsCacheService::SetDiskCacheCapacity(mDiskCacheCapacity);
             } 
 #if 0            
         } else if (!strcmp(DISK_CACHE_DIR_PREF, data.get())) {
             // XXX We probaby don't want to respond to this pref except after
             // XXX profile changes.  Ideally, there should be somekind of user
             // XXX notification that the pref change won't take effect until
             // XXX the next time the profile changes (browser launch)
@@ -472,17 +472,17 @@ nsCacheProfilePrefObserver::Observe(nsIS
                 nsCacheService::SetOfflineCacheEnabled(OfflineCacheEnabled());
             }
 
         } else if (!strcmp(OFFLINE_CACHE_CAPACITY_PREF, data.get())) {
 
             PRInt32 capacity = 0;
             rv = branch->GetIntPref(OFFLINE_CACHE_CAPACITY_PREF, &capacity);
             if (NS_FAILED(rv))  return rv;
-            mOfflineCacheCapacity = PR_MAX(0, capacity);
+            mOfflineCacheCapacity = NS_MAX(0, capacity);
             nsCacheService::SetOfflineCacheCapacity(mOfflineCacheCapacity);
 #if 0
         } else if (!strcmp(OFFLINE_CACHE_DIR_PREF, data.get())) {
             // XXX We probaby don't want to respond to this pref except after
             // XXX profile changes.  Ideally, there should be some kind of user
             // XXX notification that the pref change won't take effect until
             // XXX the next time the profile changes (browser launch)
 #endif
@@ -575,17 +575,17 @@ nsCacheProfilePrefObserver::GetSmartCach
   PRInt64 bytesAvailable;
   rv = cacheDirectory->GetDiskSpaceAvailable(&bytesAvailable);
   if (NS_FAILED(rv))
     return DEFAULT_CACHE_SIZE;
   PRInt64 kBytesAvail = bytesAvailable / 1024;
   
   // 0 MB <= Available < 500 MB: Use between 50MB and 200MB
   if (kBytesAvail < DEFAULT_CACHE_SIZE * 2) 
-    return PR_MAX(MIN_CACHE_SIZE, kBytesAvail * 4 / 10);
+    return NS_MAX<PRInt64>(MIN_CACHE_SIZE, kBytesAvail * 4 / 10);
   
   // 500MB <= Available < 2.5 GB: Use 250MB 
   if (kBytesAvail < static_cast<PRInt64>(DEFAULT_CACHE_SIZE) * 10) 
     return DEFAULT_CACHE_SIZE;
 
   // 2.5 GB <= Available < 5 GB: Use between 250MB and 500MB
   if (kBytesAvail < static_cast<PRInt64>(DEFAULT_CACHE_SIZE) * 20) 
     return kBytesAvail / 10;
@@ -649,17 +649,17 @@ nsCacheProfilePrefObserver::ReadPrefs(ns
     // read disk cache device prefs
     if (!mInPrivateBrowsing) {
         mDiskCacheEnabled = PR_TRUE;  // presume disk cache is enabled
         (void) branch->GetBoolPref(DISK_CACHE_ENABLE_PREF, &mDiskCacheEnabled);
     }
 
     mDiskCacheCapacity = DISK_CACHE_CAPACITY;
     (void)branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &mDiskCacheCapacity);
-    mDiskCacheCapacity = PR_MAX(0, mDiskCacheCapacity);
+    mDiskCacheCapacity = NS_MAX(0, mDiskCacheCapacity);
 
     (void) branch->GetComplexValue(DISK_CACHE_DIR_PREF,     // ignore error
                                    NS_GET_IID(nsILocalFile),
                                    getter_AddRefs(mDiskCacheParentDirectory));
     
     if (!mDiskCacheParentDirectory) {
         nsCOMPtr<nsIFile>  directory;
 
@@ -745,17 +745,17 @@ nsCacheProfilePrefObserver::ReadPrefs(ns
         mOfflineCacheEnabled = PR_TRUE;  // presume offline cache is enabled
         (void) branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
                                    &mOfflineCacheEnabled);
     }
 
     mOfflineCacheCapacity = OFFLINE_CACHE_CAPACITY;
     (void)branch->GetIntPref(OFFLINE_CACHE_CAPACITY_PREF,
                              &mOfflineCacheCapacity);
-    mOfflineCacheCapacity = PR_MAX(0, mOfflineCacheCapacity);
+    mOfflineCacheCapacity = NS_MAX(0, mOfflineCacheCapacity);
 
     (void) branch->GetComplexValue(OFFLINE_CACHE_DIR_PREF,     // ignore error
                                    NS_GET_IID(nsILocalFile),
                                    getter_AddRefs(mOfflineCacheParentDirectory));
 
     if (!mOfflineCacheParentDirectory) {
         nsCOMPtr<nsIFile>  directory;
 
--- a/netwerk/cache/nsDiskCacheBlockFile.cpp
+++ b/netwerk/cache/nsDiskCacheBlockFile.cpp
@@ -388,18 +388,18 @@ nsDiskCacheBlockFile::Write(PRInt32 offs
         if (upTo > maxPreallocate) {
             // grow the file as a multiple of minPreallocate
             mFileSize = ((upTo + minPreallocate - 1) / minPreallocate) * minPreallocate;
         } else {
             // Grow quickly between 1MB to 20MB
             if (mFileSize)
                 while(mFileSize < upTo)
                     mFileSize *= 2;
-            mFileSize = PR_MIN(maxPreallocate, PR_MAX(mFileSize, minPreallocate));
+            mFileSize = NS_MIN(maxPreallocate, NS_MAX(mFileSize, minPreallocate));
         }
-        mFileSize = PR_MIN(mFileSize, maxFileSize);
+        mFileSize = NS_MIN(mFileSize, maxFileSize);
         //  Appears to cause bug 617123?  Disabled for now.
         //mozilla::fallocate(mFD, mFileSize);
     }
     if (PR_Seek(mFD, offset, PR_SEEK_SET) != offset)
         return false;
     return PR_Write(mFD, buf, amount) == amount;
 }
--- a/netwerk/cache/nsDiskCacheMap.cpp
+++ b/netwerk/cache/nsDiskCacheMap.cpp
@@ -1134,14 +1134,14 @@ nsDiskCacheMap::EnsureBuffer(PRUint32 bu
 
 void
 nsDiskCacheMap::NotifyCapacityChange(PRUint32 capacity)
 {
   // Heuristic 1. average cache entry size is probably around 1KB
   // Heuristic 2. we don't want more than 32MB reserved to store the record
   //              map in memory.
   const PRInt32 RECORD_COUNT_LIMIT = 32 * 1024 * 1024 / sizeof(nsDiskCacheRecord);
-  PRInt32 maxRecordCount = PR_MIN(PRInt32(capacity), RECORD_COUNT_LIMIT);
+  PRInt32 maxRecordCount = NS_MIN(PRInt32(capacity), RECORD_COUNT_LIMIT);
   if (mMaxRecordCount < maxRecordCount) {
     // We can only grow
     mMaxRecordCount = maxRecordCount;
   }
 }
--- a/netwerk/cache/nsMemoryCacheDevice.cpp
+++ b/netwerk/cache/nsMemoryCacheDevice.cpp
@@ -400,19 +400,19 @@ nsMemoryCacheDevice::EvictionList(nsCach
 {
     // favor items which never expire by putting them in the lowest-index queue
     if (entry->ExpirationTime() == nsICache::NO_EXPIRATION_TIME)
         return 0;
 
     // compute which eviction queue this entry should go into,
     // based on floor(log2(size/nref))
     PRInt32  size       = deltaSize + (PRInt32)entry->Size();
-    PRInt32  fetchCount = PR_MAX(1, entry->FetchCount());
+    PRInt32  fetchCount = NS_MAX(1, entry->FetchCount());
 
-    return PR_MIN(PR_FloorLog2(size / fetchCount), kQueueCount - 1);
+    return NS_MIN(PR_FloorLog2(size / fetchCount), kQueueCount - 1);
 }
 
 
 nsresult
 nsMemoryCacheDevice::Visit(nsICacheVisitor * visitor)
 {
     nsMemoryCacheDeviceInfo * deviceInfo = new nsMemoryCacheDeviceInfo(this);
     nsCOMPtr<nsICacheDeviceInfo> deviceRef(deviceInfo);
--- a/netwerk/protocol/about/nsAboutCacheEntry.cpp
+++ b/netwerk/protocol/about/nsAboutCacheEntry.cpp
@@ -60,17 +60,17 @@ HexDump(PRUint32 *state, const char *buf
   const unsigned char *p;
   while (n) {
     PR_snprintf(temp, sizeof(temp), "%08x:  ", *state);
     result.Append(temp);
     *state += HEXDUMP_MAX_ROWS;
 
     p = (const unsigned char *) buf;
 
-    PRInt32 i, row_max = PR_MIN(HEXDUMP_MAX_ROWS, n);
+    PRInt32 i, row_max = NS_MIN(HEXDUMP_MAX_ROWS, n);
 
     // print hex codes:
     for (i = 0; i < row_max; ++i) {
       PR_snprintf(temp, sizeof(temp), "%02x  ", *p++);
       result.Append(temp);
     }
     for (i = row_max; i < HEXDUMP_MAX_ROWS; ++i) {
       result.AppendLiteral("    ");
@@ -400,17 +400,17 @@ nsAboutCacheEntry::WriteCacheEntryDescri
         nsCOMPtr<nsIInputStream> stream;
         descriptor->OpenInputStream(0, getter_AddRefs(stream));
         if (stream) {
             buffer.AssignLiteral("<hr/>\n"
                                  "<pre>");
             PRUint32 hexDumpState = 0;
             char chunk[4096];
             while (dataSize) {
-                PRUint32 count = PR_MIN(dataSize, sizeof(chunk));
+                PRUint32 count = NS_MIN<PRUint32>(dataSize, sizeof(chunk));
                 if (NS_FAILED(stream->Read(chunk, count, &n)) || n == 0)
                     break;
                 dataSize -= n;
                 HexDump(&hexDumpState, chunk, n, buffer);
                 outputStream->Write(buffer.get(), buffer.Length(), &n);
                 buffer.Truncate();
             }
             buffer.AssignLiteral("</pre>\n");
--- a/netwerk/protocol/file/nsFileChannel.cpp
+++ b/netwerk/protocol/file/nsFileChannel.cpp
@@ -113,17 +113,17 @@ nsFileCopyEvent::DoCopy()
 
   PRInt64 len = mLen, progress = 0;
   while (len) {
     // If we've been interrupted, then stop copying.
     rv = mInterruptStatus;
     if (NS_FAILED(rv))
       break;
 
-    PRInt32 num = PR_MIN((PRInt32) len, chunk);
+    PRInt32 num = NS_MIN((PRInt32) len, chunk);
 
     PRUint32 result;
     rv = mSource->ReadSegments(NS_CopySegmentToStream, mDest, num, &result);
     if (NS_FAILED(rv))
       break;
     if (result != (PRUint32) num) {
       rv = NS_ERROR_FILE_DISK_FULL;  // stopped prematurely (out of disk space)
       break;
--- a/netwerk/protocol/http/HttpBaseChannel.cpp
+++ b/netwerk/protocol/http/HttpBaseChannel.cpp
@@ -1020,17 +1020,17 @@ HttpBaseChannel::GetRedirectionLimit(PRU
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HttpBaseChannel::SetRedirectionLimit(PRUint32 value)
 {
   ENSURE_CALLED_BEFORE_ASYNC_OPEN();
 
-  mRedirectionLimit = PR_MIN(value, 0xff);
+  mRedirectionLimit = NS_MIN<PRUint32>(value, 0xff);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HttpBaseChannel::IsNoStoreResponse(PRBool *value)
 {
   if (!mResponseHead)
     return NS_ERROR_NOT_AVAILABLE;
--- a/netwerk/protocol/http/nsHttpChunkedDecoder.cpp
+++ b/netwerk/protocol/http/nsHttpChunkedDecoder.cpp
@@ -71,17 +71,17 @@ nsHttpChunkedDecoder::HandleChunkedConte
     //   trailer         = *(entity-header CRLF)
     //
     // the chunk-size field is a string of hex digits indicating the size of the
     // chunk.  the chunked encoding is ended by any chunk whose size is zero, 
     // followed by the trailer, which is terminated by an empty line.
 
     while (count) {
         if (mChunkRemaining) {
-            PRUint32 amt = PR_MIN(mChunkRemaining, count);
+            PRUint32 amt = NS_MIN(mChunkRemaining, count);
 
             count -= amt;
             mChunkRemaining -= amt;
 
             *contentRead += amt;
             buf += amt;
         }
         else if (mReachedEOF)
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -465,17 +465,17 @@ nsHttpConnectionMgr::PruneDeadConnection
         for (PRInt32 i=count-1; i>=0; --i) {
             nsHttpConnection *conn = ent->mIdleConns[i];
             if (!conn->CanReuse()) {
                 ent->mIdleConns.RemoveElementAt(i);
                 conn->Close(NS_ERROR_ABORT);
                 NS_RELEASE(conn);
                 self->mNumIdleConns--;
             } else {
-                timeToNextExpire = PR_MIN(timeToNextExpire, conn->TimeToLive());
+                timeToNextExpire = NS_MIN(timeToNextExpire, conn->TimeToLive());
             }
         }
     }
 
     // If time to next expire found is shorter than time to next wake-up, we need to
     // change the time for next wake-up.
     PRUint32 now = NowInSeconds();
     if (0 < ent->mIdleConns.Length()) {
--- a/netwerk/protocol/http/nsHttpResponseHead.cpp
+++ b/netwerk/protocol/http/nsHttpResponseHead.cpp
@@ -264,17 +264,17 @@ nsHttpResponseHead::ComputeCurrentAge(PR
     }
 
     // Compute apparent age
     if (now > dateValue)
         *result = now - dateValue;
 
     // Compute corrected received age
     if (NS_SUCCEEDED(GetAgeValue(&ageValue)))
-        *result = PR_MAX(*result, ageValue);
+        *result = NS_MAX(*result, ageValue);
 
     NS_ASSERTION(now >= requestTime, "bogus request time");
 
     // Compute current age
     *result += (now - requestTime);
     return NS_OK;
 }
 
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -729,17 +729,17 @@ nsHttpTransaction::LocateHttpStart(char 
     static const PRUint32 HTTP2HeaderLen = sizeof(HTTP2Header) - 1;
     
     if (aAllowPartialMatch && (len < HTTPHeaderLen))
         return (PL_strncasecmp(buf, HTTPHeader, len) == 0) ? buf : nsnull;
 
     // mLineBuf can contain partial match from previous search
     if (!mLineBuf.IsEmpty()) {
         NS_ASSERTION(mLineBuf.Length() < HTTPHeaderLen, "ouch");
-        PRInt32 checkChars = PR_MIN(len, HTTPHeaderLen - mLineBuf.Length());
+        PRInt32 checkChars = NS_MIN(len, HTTPHeaderLen - mLineBuf.Length());
         if (PL_strncasecmp(buf, HTTPHeader + mLineBuf.Length(),
                            checkChars) == 0) {
             mLineBuf.Append(buf, checkChars);
             if (mLineBuf.Length() == HTTPHeaderLen) {
                 // We've found whole HTTPHeader sequence. Return pointer at the
                 // end of matched sequence since it is stored in mLineBuf.
                 return (buf + checkChars);
             }
@@ -748,17 +748,17 @@ nsHttpTransaction::LocateHttpStart(char 
         }
         // Previous partial match together with new data doesn't match the
         // pattern. Start the search again.
         mLineBuf.Truncate();
     }
 
     PRBool firstByte = PR_TRUE;
     while (len > 0) {
-        if (PL_strncasecmp(buf, HTTPHeader, PR_MIN(len, HTTPHeaderLen)) == 0) {
+        if (PL_strncasecmp(buf, HTTPHeader, NS_MIN<PRUint32>(len, HTTPHeaderLen)) == 0) {
             if (len < HTTPHeaderLen) {
                 // partial HTTPHeader sequence found
                 // save partial match to mLineBuf
                 mLineBuf.Assign(buf, len);
                 return 0;
             }
 
             // whole HTTPHeader sequence found
@@ -882,17 +882,17 @@ nsHttpTransaction::ParseHead(char *buf,
         // Normally we insist on seeing HTTP/1.x in the first few bytes,
         // but if we are on a persistent connection and the previous transaction
         // was not supposed to have any content then we need to be prepared
         // to skip over a response body that the server may have sent even
         // though it wasn't allowed.
         if (!mConnection || !mConnection->LastTransactionExpectedNoContent()) {
             // tolerate only minor junk before the status line
             mHttpResponseMatched = PR_TRUE;
-            char *p = LocateHttpStart(buf, PR_MIN(count, 11), PR_TRUE);
+            char *p = LocateHttpStart(buf, NS_MIN<PRUint32>(count, 11), PR_TRUE);
             if (!p) {
                 // Treat any 0.9 style response of a put as a failure.
                 if (mRequestHead->Method() == nsHttp::Put)
                     return NS_ERROR_ABORT;
 
                 mResponseHead->ParseStatusLine("");
                 mHaveStatusLine = PR_TRUE;
                 mHaveAllHeaders = PR_TRUE;
@@ -1106,17 +1106,17 @@ nsHttpTransaction::HandleContent(char *b
         *contentRead = count;
     }
 
     if (*contentRead) {
         // update count of content bytes read and report progress...
         mContentRead += *contentRead;
         /* when uncommenting, take care of 64-bit integers w/ PR_MAX...
         if (mProgressSink)
-            mProgressSink->OnProgress(nsnull, nsnull, mContentRead, PR_MAX(0, mContentLength));
+            mProgressSink->OnProgress(nsnull, nsnull, mContentRead, NS_MAX(0, mContentLength));
         */
     }
 
     LOG(("nsHttpTransaction::HandleContent [this=%x count=%u read=%u mContentRead=%lld mContentLength=%lld]\n",
         this, count, *contentRead, mContentRead, mContentLength));
 
     // check for end-of-file
     if ((mContentRead == mContentLength) ||
--- a/netwerk/streamconv/converters/nsBinHexDecoder.cpp
+++ b/netwerk/streamconv/converters/nsBinHexDecoder.cpp
@@ -158,17 +158,17 @@ nsBinHexDecoder::OnDataAvailable(nsIRequ
 {
   nsresult rv = NS_OK;
 
   if (mOutputStream && mDataBuffer && aCount > 0)
   {
     PRUint32 numBytesRead = 0;
     while (aCount > 0) // while we still have bytes to copy...
     {
-      aStream->Read(mDataBuffer, PR_MIN(aCount, nsIOService::gDefaultSegmentSize - 1), &numBytesRead);
+      aStream->Read(mDataBuffer, NS_MIN(aCount, nsIOService::gDefaultSegmentSize - 1), &numBytesRead);
       if (aCount >= numBytesRead)
         aCount -= numBytesRead; // subtract off the number of bytes we just read
       else
         aCount = 0;
 
       // Process this new chunk of bin hex data...
       ProcessNextChunk(request, aCtxt, numBytesRead);
     }
--- a/netwerk/streamconv/converters/nsIndexedToHTML.cpp
+++ b/netwerk/streamconv/converters/nsIndexedToHTML.cpp
@@ -853,17 +853,17 @@ nsIndexedToHTML::OnIndexAvailable(nsIReq
         if (NS_FAILED(rv)) return rv;
 
         //XXX this potentially truncates after a combining char (bug 391472)
         nsXPIDLString descriptionAffix;
         descriptionAffix.Assign(description);
         descriptionAffix.Cut(0, descriptionAffix.Length() - 25);
         if (NS_IS_LOW_SURROGATE(descriptionAffix.First()))
             descriptionAffix.Cut(0, 1);
-        description.Truncate(PR_MIN(71, description.Length() - 28));
+        description.Truncate(NS_MIN<PRUint32>(71, description.Length() - 28));
         if (NS_IS_HIGH_SURROGATE(description.Last()))
             description.Truncate(description.Length() - 1);
 
         escapedShort.Adopt(nsEscapeHTML2(description.get(), description.Length()));
 
         escapedShort.Append(mEscapedEllipsis);
         // add ZERO WIDTH SPACE (U+200B) for wrapping
         escapedShort.AppendLiteral("&#8203;");
--- a/netwerk/streamconv/converters/nsMultiMixedConv.cpp
+++ b/netwerk/streamconv/converters/nsMultiMixedConv.cpp
@@ -601,17 +601,17 @@ nsMultiMixedConv::OnDataAvailable(nsIReq
     else if (bufLen) {
         // if the data ends in a linefeed, and we're in the middle
         // of a "part" (ie. mPartChannel exists) don't bother
         // buffering, go ahead and send the data we have. Otherwise
         // if we don't have a channel already, then we don't even
         // have enough info to start a part, go ahead and buffer
         // enough to collect a boundary token.
         if (!mPartChannel || !(cursor[bufLen-1] == nsCRT::LF) )
-            bufAmt = PR_MIN(mTokenLen - 1, bufLen);
+            bufAmt = NS_MIN(mTokenLen - 1, bufLen);
     }
 
     if (bufAmt) {
         rv = BufferData(cursor + (bufLen - bufAmt), bufAmt);
         if (NS_FAILED(rv)) ERR_OUT
         bufLen -= bufAmt;
     }
 
--- a/netwerk/streamconv/converters/nsTXTToHTMLConv.cpp
+++ b/netwerk/streamconv/converters/nsTXTToHTMLConv.cpp
@@ -195,18 +195,18 @@ nsTXTToHTMLConv::OnDataAvailable(nsIRequ
                 cursor = front;
                 break;
             }
             // found the end of the token.
             cursor = CatHTML(front, back);
         }
 
         PRInt32 end = mBuffer.RFind(TOKEN_DELIMITERS, mBuffer.Length());
-        mBuffer.Left(pushBuffer, PR_MAX(cursor, end));
-        mBuffer.Cut(0, PR_MAX(cursor, end));
+        mBuffer.Left(pushBuffer, NS_MAX(cursor, end));
+        mBuffer.Cut(0, NS_MAX(cursor, end));
         cursor = 0;
 
         if (!pushBuffer.IsEmpty()) {
             nsCOMPtr<nsIInputStream> inputData;
 
             rv = NS_NewStringInputStream(getter_AddRefs(inputData), pushBuffer);
             if (NS_FAILED(rv))
                 return rv;
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -1929,17 +1929,17 @@ NS_IMETHODIMP nsExternalAppHandler::OnDa
   {
     PRUint32 numBytesRead = 0; 
     PRUint32 numBytesWritten = 0;
     mProgress += count;
     PRBool readError = PR_TRUE;
     while (NS_SUCCEEDED(rv) && count > 0) // while we still have bytes to copy...
     {
       readError = PR_TRUE;
-      rv = inStr->Read(mDataBuffer, PR_MIN(count, mBufferSize - 1), &numBytesRead);
+      rv = inStr->Read(mDataBuffer, NS_MIN(count, mBufferSize - 1), &numBytesRead);
       if (NS_SUCCEEDED(rv))
       {
         if (count >= numBytesRead)
           count -= numBytesRead; // subtract off the number of bytes we just read
         else
           count = 0;
         readError = PR_FALSE;
         // Write out the data until something goes wrong, or, it is
--- a/widget/src/android/nsWindow.cpp
+++ b/widget/src/android/nsWindow.cpp
@@ -1650,17 +1650,17 @@ nsWindow::OnIMEEvent(AndroidGeckoEvent *
             ALOGIME("IME: IME_SET_SELECTION: o=%u, l=%d", ae->Offset(), ae->Count());
 
             nsSelectionEvent selEvent(PR_TRUE, NS_SELECTION_SET, this);
             InitEvent(selEvent, nsnull);
 
             selEvent.mOffset = PRUint32(ae->Count() >= 0 ?
                                         ae->Offset() :
                                         ae->Offset() + ae->Count());
-            selEvent.mLength = PRUint32(PR_ABS(ae->Count()));
+            selEvent.mLength = PRUint32(NS_ABS(ae->Count()));
             selEvent.mReversed = ae->Count() >= 0 ? PR_FALSE : PR_TRUE;
 
             DispatchEvent(&selEvent);
         }
         return;
     case AndroidGeckoEvent::IME_GET_SELECTION:
         {
             ALOGIME("IME: IME_GET_SELECTION");
--- a/widget/src/gtk2/nsNativeKeyBindings.cpp
+++ b/widget/src/gtk2/nsNativeKeyBindings.cpp
@@ -121,17 +121,17 @@ delete_from_cursor_cb(GtkWidget *w, GtkD
       gCurrentCallback("cmd_endLine", gCurrentCallbackData);
     }
   }
 
   const char *cmd = sDeleteCommands[del_type][forward];
   if (!cmd)
     return; // unsupported command
 
-  count = PR_ABS(count);
+  count = NS_ABS(count);
   for (int i = 0; i < count; ++i) {
     gCurrentCallback(cmd, gCurrentCallbackData);
   }
 }
 
 static const char *const sMoveCommands[][2][2] = {
   // non-extend { backward, forward }, extend { backward, forward }
   // GTK differentiates between logical position, which is prev/next,
@@ -191,17 +191,17 @@ move_cursor_cb(GtkWidget *w, GtkMovement
     return;
   }
 
   const char *cmd = sMoveCommands[step][extend_selection][forward];
   if (!cmd)
     return; // unsupported command
 
   
-  count = PR_ABS(count);
+  count = NS_ABS(count);
   for (int i = 0; i < count; ++i) {
     gCurrentCallback(cmd, gCurrentCallbackData);
   }
 }
 
 static void
 paste_clipboard_cb(GtkWidget *w, gpointer user_data)
 {
--- a/widget/src/gtk2/nsNativeThemeGTK.cpp
+++ b/widget/src/gtk2/nsNativeThemeGTK.cpp
@@ -181,18 +181,18 @@ static GtkTextDirection GetTextDirection
 // Returns positive for negative margins (otherwise 0).
 gint
 nsNativeThemeGTK::GetTabMarginPixels(nsIFrame* aFrame)
 {
   nscoord margin =
     IsBottomTab(aFrame) ? aFrame->GetUsedMargin().top
     : aFrame->GetUsedMargin().bottom;
 
-  return PR_MIN(MOZ_GTK_TAB_MARGIN_MASK,
-                PR_MAX(0,
+  return NS_MIN<gint>(MOZ_GTK_TAB_MARGIN_MASK,
+                NS_MAX(0,
                        aFrame->PresContext()->AppUnitsToDevPixels(-margin)));
 }
 
 PRBool
 nsNativeThemeGTK::GetGtkWidgetAndState(PRUint8 aWidgetType, nsIFrame* aFrame,
                                        GtkThemeWidgetType& aGtkWidgetType,
                                        GtkWidgetState* aState,
                                        gint* aWidgetFlags)
@@ -1075,21 +1075,21 @@ nsNativeThemeGTK::GetMinimumWidgetSize(n
          * Setting aIsOverridable to PR_TRUE has no effect for thumbs. */
         aFrame->GetMargin(margin);
         rect.Deflate(margin);
         aFrame->GetParent()->GetBorderAndPadding(margin);
         rect.Deflate(margin);
 
         if (aWidgetType == NS_THEME_SCROLLBAR_THUMB_VERTICAL) {
           aResult->width = metrics.slider_width;
-          aResult->height = PR_MIN(NSAppUnitsToIntPixels(rect.height, p2a),
+          aResult->height = NS_MIN(NSAppUnitsToIntPixels(rect.height, p2a),
                                    metrics.min_slider_size);
         } else {
           aResult->height = metrics.slider_width;
-          aResult->width = PR_MIN(NSAppUnitsToIntPixels(rect.width, p2a),
+          aResult->width = NS_MIN(NSAppUnitsToIntPixels(rect.width, p2a),
                                   metrics.min_slider_size);
         }
 
         *aIsOverridable = PR_FALSE;
       }
       break;
     case NS_THEME_SCALE_THUMB_HORIZONTAL:
     case NS_THEME_SCALE_THUMB_VERTICAL:
--- a/widget/src/gtk2/nsPrintSettingsGTK.cpp
+++ b/widget/src/gtk2/nsPrintSettingsGTK.cpp
@@ -280,17 +280,17 @@ nsPrintSettingsGTK::GetStartPageRange(PR
   // Make sure we got a range.
   if (ctRanges < 1) {
     *aStartPageRange = 1;
   } else {
     // GTK supports multiple page ranges; gecko only supports 1. So find
     // the lowest start page.
     PRInt32 start(lstRanges[0].start);
     for (gint ii = 1; ii < ctRanges; ii++) {
-      start = PR_MIN(lstRanges[ii].start, start);
+      start = NS_MIN(lstRanges[ii].start, start);
     }
     *aStartPageRange = start + 1;
   }
 
   g_free(lstRanges);
   return NS_OK;
 }
 NS_IMETHODIMP
@@ -315,17 +315,17 @@ nsPrintSettingsGTK::GetEndPageRange(PRIn
   gint ctRanges;
   GtkPageRange* lstRanges = gtk_print_settings_get_page_ranges(mPrintSettings, &ctRanges);
 
   if (ctRanges < 1) {
     *aEndPageRange = 1;
   } else {
     PRInt32 end(lstRanges[0].end);
     for (gint ii = 1; ii < ctRanges; ii++) {
-      end = PR_MAX(lstRanges[ii].end, end);
+      end = NS_MAX(lstRanges[ii].end, end);
     }
     *aEndPageRange = end + 1;
   }
 
   g_free(lstRanges);
   return NS_OK;
 }
 NS_IMETHODIMP
--- a/widget/src/gtk2/nsWindow.cpp
+++ b/widget/src/gtk2/nsWindow.cpp
@@ -4730,18 +4730,18 @@ nsWindow::ResizeTransparencyBitmap(PRInt
         mTransparencyBitmapWidth = 0;
         mTransparencyBitmapHeight = 0;
         return;
     }
     // fill new mask with "opaque", first
     memset(newBits, 255, newSize);
 
     // Now copy the intersection of the old and new areas into the new mask
-    PRInt32 copyWidth = PR_MIN(aNewWidth, mTransparencyBitmapWidth);
-    PRInt32 copyHeight = PR_MIN(aNewHeight, mTransparencyBitmapHeight);
+    PRInt32 copyWidth = NS_MIN(aNewWidth, mTransparencyBitmapWidth);
+    PRInt32 copyHeight = NS_MIN(aNewHeight, mTransparencyBitmapHeight);
     PRInt32 oldRowBytes = (mTransparencyBitmapWidth+7)/8;
     PRInt32 newRowBytes = (aNewWidth+7)/8;
     PRInt32 copyBytes = (copyWidth+7)/8;
 
     PRInt32 i;
     gchar* fromPtr = mTransparencyBitmap;
     gchar* toPtr = newBits;
     for (i = 0; i < copyHeight; i++) {
@@ -6534,18 +6534,18 @@ nsWindow::GetThebesSurface()
     GdkDrawable* d;
     gint x_offset, y_offset;
     gdk_window_get_internal_paint_info(mGdkWindow, &d, &x_offset, &y_offset);
 
 #ifdef MOZ_X11
     gint width, height;
     gdk_drawable_get_size(d, &width, &height);
     // Owen Taylor says this is the right thing to do!
-    width = PR_MIN(32767, width);
-    height = PR_MIN(32767, height);
+    width = NS_MIN(32767, width);
+    height = NS_MIN(32767, height);
     gfxIntSize size(width, height);
     Visual* visual = GDK_VISUAL_XVISUAL(gdk_drawable_get_visual(d));
 
 #  ifdef MOZ_HAVE_SHMIMAGE
     PRBool usingShm = PR_FALSE;
     if (nsShmImage::UseShm()) {
         // EnsureShmImage() is a dangerous interface, but we guarantee
         // that the thebes surface and the shmimage have the same
--- a/widget/src/os2/nsIdleServiceOS2.cpp
+++ b/widget/src/os2/nsIdleServiceOS2.cpp
@@ -71,17 +71,17 @@ nsIdleServiceOS2::PollIdleTime(PRUint32 
 
   ULONG mouse, keyboard;
   if (DSSaver_GetInactivityTime(&mouse, &keyboard) != SSCORE_NOERROR) {
     return false;
   }
 
   // we are only interested in activity in general, so take the minimum
   // of both timers
-  *aIdleTime = PR_MIN(mouse, keyboard);
+  *aIdleTime = NS_MIN(mouse, keyboard);
   return true;
 }
 
 bool
 nsIdleServiceOS2::UsePollMode()
 {
   return mInitialized;
 }
--- a/widget/src/windows/KeyboardLayout.cpp
+++ b/widget/src/windows/KeyboardLayout.cpp
@@ -30,20 +30,22 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+#include "KeyboardLayout.h"
+
 #include "nsMemory.h"
-#include "KeyboardLayout.h"
 #include "nsToolkit.h"
 #include "nsQuickSort.h"
+#include "nsAlgorithm.h"
 
 #include <winuser.h>
 
 #ifndef WINABLEAPI
 #include <winable.h>
 #endif
 
 namespace mozilla {
@@ -324,17 +326,17 @@ KeyboardLayout::OnKeyDown(PRUint8 aVirtu
   DeactivateDeadKeyState();
 }
 
 PRUint32
 KeyboardLayout::GetUniChars(PRUnichar* aUniChars,
                             PRUint8* aShiftStates,
                             PRUint32 aMaxChars) const
 {
-  PRUint32 chars = PR_MIN(mNumOfChars, aMaxChars);
+  PRUint32 chars = NS_MIN<PRUint32>(mNumOfChars, aMaxChars);
 
   memcpy(aUniChars, mChars, chars * sizeof(PRUnichar));
   memcpy(aShiftStates, mShiftStates, chars);
 
   return chars;
 }
 
 PRUint32
@@ -346,17 +348,17 @@ KeyboardLayout::GetUniCharsWithShiftStat
   PRInt32 key = GetKeyIndex(aVirtualKey);
   if (key < 0) {
     return 0;
   }
   PRUint8 finalShiftState;
   PRUnichar uniChars[5];
   PRUint32 numOfBaseChars =
     mVirtualKeys[key].GetUniChars(aShiftStates, uniChars, &finalShiftState);
-  PRUint32 chars = PR_MIN(numOfBaseChars, aMaxChars);
+  PRUint32 chars = NS_MIN(numOfBaseChars, aMaxChars);
   memcpy(aUniChars, uniChars, chars * sizeof(PRUnichar));
   return chars;
 }
 
 void
 KeyboardLayout::LoadLayout(HKL aLayout)
 {
   if (mKeyboardLayout == aLayout) {
--- a/widget/src/windows/nsIMM32Handler.cpp
+++ b/widget/src/windows/nsIMM32Handler.cpp
@@ -1851,17 +1851,17 @@ nsIMM32Handler::GetCharacterRectOfSelect
   PRBool useCaretRect = selection.mReply.mString.IsEmpty();
   if (useCaretRect && ShouldDrawCompositionStringOurselves() &&
       mIsComposing && !mCompositionString.IsEmpty()) {
     // There is not a normal selection, but we have composition string.
     // XXX mnakano - Should we implement NS_QUERY_IME_SELECTED_TEXT?
     useCaretRect = PR_FALSE;
     if (mCursorPosition != NO_IME_CARET) {
       PRUint32 cursorPosition =
-        PR_MIN(PRUint32(mCursorPosition), mCompositionString.Length());
+        NS_MIN<PRUint32>(mCursorPosition, mCompositionString.Length());
       offset -= cursorPosition;
       NS_ASSERTION(offset >= 0, "offset is negative!");
     }
   }
 
   nsIntRect r;
   if (!useCaretRect) {
     nsQueryContentEvent charRect(PR_TRUE, NS_QUERY_TEXT_RECT, aWindow);
--- a/widget/src/windows/nsNativeThemeWin.cpp
+++ b/widget/src/windows/nsNativeThemeWin.cpp
@@ -204,18 +204,18 @@ static SIZE GetGutterSize(HANDLE theme, 
     SIZE gutterSize;
     nsUXThemeData::getThemePartSize(theme, hdc, MENU_POPUPGUTTER, 0, NULL, TS_TRUE, &gutterSize);
 
     SIZE checkboxBGSize(GetCheckboxBGBounds(theme, hdc));
 
     SIZE itemSize;
     nsUXThemeData::getThemePartSize(theme, hdc, MENU_POPUPITEM, MPI_NORMAL, NULL, TS_TRUE, &itemSize);
 
-    int width = PR_MAX(itemSize.cx, checkboxBGSize.cx + gutterSize.cx);
-    int height = PR_MAX(itemSize.cy, checkboxBGSize.cy);
+    int width = NS_MAX(itemSize.cx, checkboxBGSize.cx + gutterSize.cx);
+    int height = NS_MAX(itemSize.cy, checkboxBGSize.cy);
     SIZE ret;
     ret.cx = width;
     ret.cy = height;
     return ret;
 }
 
 static HRESULT DrawThemeBGRTLAware(HANDLE theme, HDC hdc, int part, int state,
                                    const RECT *widgetRect, const RECT *clipRect,
--- a/widget/src/windows/nsTextStore.cpp
+++ b/widget/src/windows/nsTextStore.cpp
@@ -764,31 +764,31 @@ nsTextStore::SendTextEventForComposition
   // At this time, mCompositionSelection range is same as the composition
   // string range.  Other applications set a wide caret which covers the
   // composition string, however, Gecko doesn't support the wide caret drawing
   // now (Gecko doesn't support XOR drawing), unfortunately.  For now, we should
   // change the range style to undefined.
   if (mCompositionSelection.acpStart != mCompositionSelection.acpEnd &&
       textRanges.Length() == 1) {
     nsTextRange& range = textRanges[0];
-    LONG start = PR_MIN(mCompositionSelection.acpStart,
+    LONG start = NS_MIN(mCompositionSelection.acpStart,
                         mCompositionSelection.acpEnd);
-    LONG end = PR_MAX(mCompositionSelection.acpStart,
+    LONG end = NS_MAX(mCompositionSelection.acpStart,
                       mCompositionSelection.acpEnd);
     if ((LONG)range.mStartOffset == start - mCompositionStart &&
         (LONG)range.mEndOffset == end - mCompositionStart &&
         range.mRangeStyle.IsNoChangeStyle()) {
       range.mRangeStyle.Clear();
       // The looks of selected type is better than others.
       range.mRangeType = NS_TEXTRANGE_SELECTEDRAWTEXT;
     }
   }
 
   // The caret position has to be collapsed.
-  LONG caretPosition = PR_MAX(mCompositionSelection.acpStart,
+  LONG caretPosition = NS_MAX(mCompositionSelection.acpStart,
                               mCompositionSelection.acpEnd);
   caretPosition -= mCompositionStart;
   nsTextRange caretRange;
   caretRange.mStartOffset = caretRange.mEndOffset = PRUint32(caretPosition);
   caretRange.mRangeType = NS_TEXTRANGE_CARETPOSITION;
   textRanges.AppendElement(caretRange);
 
   event.theText = mCompositionString;
@@ -887,21 +887,21 @@ nsTextStore::GetText(LONG acpStart,
   }
   if (length) {
     LONG compNewStart = 0, compOldEnd = 0, compNewEnd = 0;
     if (mCompositionView) {
       // Sometimes GetText gets called between InsertTextAtSelection and
       // OnUpdateComposition. In this case the returned text would
       // be out of sync because we haven't sent NS_TEXT_TEXT in
       // OnUpdateComposition yet. Manually resync here.
-      compOldEnd = PR_MIN(LONG(length) + acpStart,
+      compOldEnd = NS_MIN(LONG(length) + acpStart,
                        mCompositionLength + mCompositionStart);
-      compNewEnd = PR_MIN(LONG(length) + acpStart,
+      compNewEnd = NS_MIN(LONG(length) + acpStart,
                        LONG(mCompositionString.Length()) + mCompositionStart);
-      compNewStart = PR_MAX(acpStart, mCompositionStart);
+      compNewStart = NS_MAX(acpStart, mCompositionStart);
       // Check if the range is affected
       if (compOldEnd > compNewStart || compNewEnd > compNewStart) {
         NS_ASSERTION(compOldEnd >= mCompositionStart &&
             compNewEnd >= mCompositionStart, "Range end is less than start\n");
         length = PRUint32(LONG(length) + compOldEnd - compNewEnd);
       }
     }
     // Send NS_QUERY_TEXT_CONTENT to get text content
@@ -909,25 +909,25 @@ nsTextStore::GetText(LONG acpStart,
     mWindow->InitEvent(event);
     event.InitForQueryTextContent(PRUint32(acpStart), length);
     mWindow->DispatchWindowEvent(&event);
     NS_ENSURE_TRUE(event.mSucceeded, E_FAIL);
 
     if (compOldEnd > compNewStart || compNewEnd > compNewStart) {
       // Resync composition string
       const PRUnichar* compStrStart = mCompositionString.BeginReading() +
-          PR_MAX(compNewStart - mCompositionStart, 0);
+          NS_MAX<LONG>(compNewStart - mCompositionStart, 0);
       event.mReply.mString.Replace(compNewStart - acpStart,
           compOldEnd - mCompositionStart, compStrStart,
           compNewEnd - mCompositionStart);
       length = PRUint32(LONG(length) - compOldEnd + compNewEnd);
     }
     NS_ENSURE_TRUE(-1 == acpEnd || event.mReply.mString.Length() == length,
                    TS_E_INVALIDPOS);
-    length = PR_MIN(length, event.mReply.mString.Length());
+    length = NS_MIN(length, event.mReply.mString.Length());
 
     if (pchPlain && cchPlainReq) {
       memcpy(pchPlain, event.mReply.mString.BeginReading(),
              length * sizeof(*pchPlain));
       pchPlain[length] = 0;
       *pcchPlainOut = length;
     }
     if (prgRunInfo && ulRunInfoReq) {
@@ -1448,19 +1448,19 @@ nsTextStore::OnFocusChange(PRBool aFocus
 }
 
 nsresult
 nsTextStore::OnTextChangeInternal(PRUint32 aStart,
                                   PRUint32 aOldEnd,
                                   PRUint32 aNewEnd)
 {
   if (!mLock && mSink && 0 != (mSinkMask & TS_AS_TEXT_CHANGE)) {
-    mTextChange.acpStart = PR_MIN(mTextChange.acpStart, LONG(aStart));
-    mTextChange.acpOldEnd = PR_MAX(mTextChange.acpOldEnd, LONG(aOldEnd));
-    mTextChange.acpNewEnd = PR_MAX(mTextChange.acpNewEnd, LONG(aNewEnd));
+    mTextChange.acpStart = NS_MIN(mTextChange.acpStart, LONG(aStart));
+    mTextChange.acpOldEnd = NS_MAX(mTextChange.acpOldEnd, LONG(aOldEnd));
+    mTextChange.acpNewEnd = NS_MAX(mTextChange.acpNewEnd, LONG(aNewEnd));
     ::PostMessageW(mWindow->GetWindowHandle(),
                    WM_USER_TSF_TEXTCHANGE, 0, 0);
   }
   return NS_OK;
 }
 
 void
 nsTextStore::OnTextChangeMsgInternal(void)
--- a/widget/src/xpwidgets/nsBaseDragService.cpp
+++ b/widget/src/xpwidgets/nsBaseDragService.cpp
@@ -589,19 +589,19 @@ nsBaseDragService::DrawDragForImage(nsPr
   nsDeviceContext* deviceContext = aPresContext->DeviceContext();
   nsRect maxSize;
   deviceContext->GetClientRect(maxSize);
   nscoord maxWidth = aPresContext->AppUnitsToDevPixels(maxSize.width >> 1);
   nscoord maxHeight = aPresContext->AppUnitsToDevPixels(maxSize.height >> 1);
   if (destSize.width > maxWidth || destSize.height > maxHeight) {
     float scale = 1.0;
     if (destSize.width > maxWidth)
-      scale = PR_MIN(scale, float(maxWidth) / destSize.width);
+      scale = NS_MIN(scale, float(maxWidth) / destSize.width);
     if (destSize.height > maxHeight)
-      scale = PR_MIN(scale, float(maxHeight) / destSize.height);
+      scale = NS_MIN(scale, float(maxHeight) / destSize.height);
 
     destSize.width = NSToIntFloor(float(destSize.width) * scale);
     destSize.height = NSToIntFloor(float(destSize.height) * scale);
 
     aScreenDragRect->x = NSToIntFloor(aScreenX - float(mImageX) * scale);
     aScreenDragRect->y = NSToIntFloor(aScreenY - float(mImageY) * scale);
     aScreenDragRect->width = destSize.width;
     aScreenDragRect->height = destSize.height;
--- a/widget/src/xpwidgets/nsIdleService.cpp
+++ b/widget/src/xpwidgets/nsIdleService.cpp
@@ -397,17 +397,17 @@ nsIdleService::CheckAwayState(bool aNoTi
         // then add the listener to the list of listeners that should be
         // notified.
         notifyList.AppendObject(curListener.observer);
         // This listener is now idle.
         curListener.isIdle = true;
       } else {
         // If it hasn't expired yet, then we should note the time when it should
         // expire.
-        nextWaitTime = PR_MIN(nextWaitTime, curListener.reqIdleTime);
+        nextWaitTime = NS_MIN(nextWaitTime, curListener.reqIdleTime);
       }
     }
 
     // Remember if anyone becomes idle (it's safe to do this as a binary compare
     // as we are or'ing).
     anyOneIdle |= curListener.isIdle;
   }
 
--- a/widget/src/xpwidgets/nsNativeTheme.cpp
+++ b/widget/src/xpwidgets/nsNativeTheme.cpp
@@ -514,17 +514,17 @@ nsNativeTheme::QueueAnimatedContentForRe
                                               PRUint32 aMinimumFrameRate)
 {
   NS_ASSERTION(aContent, "Null pointer!");
   NS_ASSERTION(aMinimumFrameRate, "aMinimumFrameRate must be non-zero!");
   NS_ASSERTION(aMinimumFrameRate <= 1000,
                "aMinimumFrameRate must be less than 1000!");
 
   PRUint32 timeout = PRUint32(NS_floor(1000 / aMinimumFrameRate));
-  timeout = PR_MIN(mAnimatedContentTimeout, timeout);
+  timeout = NS_MIN(mAnimatedContentTimeout, timeout);
 
   if (!mAnimatedContentTimer) {
     mAnimatedContentTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
     NS_ENSURE_TRUE(mAnimatedContentTimer, PR_FALSE);
   }
 
   if (mAnimatedContentList.IsEmpty() || timeout != mAnimatedContentTimeout) {
     nsresult rv;
--- a/widget/src/xpwidgets/nsNativeTheme.h
+++ b/widget/src/xpwidgets/nsNativeTheme.h
@@ -35,16 +35,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 // This defines a common base class for nsITheme implementations, to reduce
 // code duplication.
 
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "nsIAtom.h"
 #include "nsCOMPtr.h"
 #include "nsString.h"
 #include "nsMargin.h"
 #include "nsILookAndFeel.h"
 #include "nsWidgetAtoms.h"
 #include "nsEventStates.h"
 #include "nsTArray.h"
--- a/widget/tests/TestWinTSF.cpp
+++ b/widget/tests/TestWinTSF.cpp
@@ -727,18 +727,18 @@ public: // ITfReadOnlyProperty
       HRESULT hr = GetRegularExtent(mRanges[i], start, end);
       NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
       if (pTargetRange) {
         // If pTargetRange is not null and the current range is not overlapped
         // with it, we don't need to add range.
         if (targetStart > end || targetEnd < start)
           continue;
         // Otherwise, shrink to the target range.
-        start = PR_MAX(targetStart, start);
-        end = PR_MIN(targetEnd, end);
+        start = NS_MAX(targetStart, start);
+        end = NS_MIN(targetEnd, end);
       }
       nsRefPtr<TSFRangeImpl> range = new TSFRangeImpl(start, end - start);
       NS_ENSURE_TRUE(range, E_OUTOFMEMORY);
       er->mRanges.AppendElement(range);
     }
     *ppEnum = er;
     (*ppEnum)->AddRef();
     return S_OK;
@@ -947,18 +947,18 @@ public: // ITfCompositionView
   {
     NS_ENSURE_TRUE(ppRange, E_INVALIDARG);
     NS_ENSURE_TRUE(mAttrProp->mRanges.Length() > 0, E_FAIL);
     LONG start = LONG_MAX, end = 0;
     for (PRUint32 i = 0; i < mAttrProp->mRanges.Length(); i++) {
       LONG tmpStart, tmpEnd;
       HRESULT hr = GetRegularExtent(mAttrProp->mRanges[i], tmpStart, tmpEnd);
       NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
-      start = PR_MIN(start, tmpStart);
-      end = PR_MAX(end, tmpEnd);
+      start = NS_MIN(start, tmpStart);
+      end = NS_MAX(end, tmpEnd);
     }
     nsRefPtr<TSFRangeImpl> range = new TSFRangeImpl();
     NS_ENSURE_TRUE(range, E_OUTOFMEMORY);
     HRESULT hr = range->SetExtent(start, end - start);
     NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
     (*ppRange) = range;
     (*ppRange)->AddRef();
     return S_OK;
--- a/xpcom/ds/nsExpirationTracker.h
+++ b/xpcom/ds/nsExpirationTracker.h
@@ -198,17 +198,17 @@ template <class T, PRUint32 K> class nsE
       // 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.
       PRUint32 index = generation.Length();
       for (;;) {
         // Objects could have been removed so index could be outside
         // the array
-        index = PR_MIN(index, generation.Length());
+        index = NS_MIN(index, generation.Length());
         if (index == 0)
           break;
         --index;
         NotifyExpired(generation[index]);
       }
       // Any leftover objects from reapGeneration just end up in the new
       // newest-generation. This is bad form, though, so warn if there are any.
       if (!generation.IsEmpty()) {
--- a/xpcom/glue/nsQuickSort.cpp
+++ b/xpcom/glue/nsQuickSort.cpp
@@ -30,16 +30,17 @@
  */
 
 /* We need this because Solaris' version of qsort is broken and
  * causes array bounds reads.
  */
 
 #include <stdlib.h>
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "nsQuickSort.h"
 
 PR_BEGIN_EXTERN_C
 
 #if !defined(DEBUG) && (defined(__cplusplus) || defined(__gcc))
 # ifndef INLINE
 #  define INLINE inline
 # endif
@@ -159,19 +160,19 @@ loop:	SWAPINIT(a, es);
 		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
 			for (pl = pm; pl > (char *)a && cmp(pl - es, pl, data) > 0;
 			     pl -= es)
 				swap(pl, pl - es);
 		return;
 	}
 
 	pn = (char *)a + n * es;
-	r = PR_MIN(pa - (char *)a, pb - pa);
+	r = NS_MIN(pa - (char *)a, pb - pa);
 	vecswap(a, pb - r, r);
-	r = PR_MIN(pd - pc, (int)(pn - pd - es));
+	r = NS_MIN<size_t>(pd - pc, pn - pd - es);
 	vecswap(pb, pn - r, r);
 	if ((r = pb - pa) > (int)es)
         NS_QuickSort(a, r / es, es, cmp, data);
 	if ((r = pd - pc) > (int)es) {
 		/* Iterate rather than recurse to save stack space */
 		a = pn - r;
 		n = r / es;
 		goto loop;
--- a/xpcom/glue/nsTArray-inl.h
+++ b/xpcom/glue/nsTArray-inl.h
@@ -84,17 +84,17 @@ nsTArray_base<Alloc>::EnsureCapacity(siz
 
     return PR_TRUE;
   }
 
   // Use doubling algorithm when forced to increase available
   // capacity.  (Note that mCapacity is only 31 bits wide, so
   // multiplication promotes its type. We use |2u| instead of |2|
   // to make sure it's promoted to unsigned.)
-  capacity = PR_MAX(capacity, mHdr->mCapacity * 2u);
+  capacity = NS_MAX<size_type>(capacity, mHdr->mCapacity * 2U);
 
   Header *header;
   if (UsesAutoArrayBuffer()) {
     // Malloc() and copy
     header = static_cast<Header*>
              (Alloc::Malloc(sizeof(Header) + capacity * elemSize));
     if (!header)
       return PR_FALSE;
--- a/xpcom/glue/nsTArray.h
+++ b/xpcom/glue/nsTArray.h
@@ -37,16 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsTArray_h__
 #define nsTArray_h__
 
 #include <string.h>
 
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "nscore.h"
 #include "nsQuickSort.h"
 #include "nsDebug.h"
 #include "nsTraceRefcnt.h"
 #include NEW_H
 
 //
 // NB: nsTArray assumes that your "T" can be memmove()d.  This is in
--- a/xpcom/glue/nsVersionComparator.cpp
+++ b/xpcom/glue/nsVersionComparator.cpp
@@ -285,17 +285,17 @@ CompareVP(VersionPart &v1, VersionPart &
 #ifdef XP_WIN
 static PRInt32
 CompareVP(VersionPartW &v1, VersionPartW &v2)
 {
   PRInt32 r = ns_cmp(v1.numA, v2.numA);
   if (r)
     return r;
 
-  r = wcsncmp(v1.strB, v2.strB, PR_MIN(v1.strBlen,v2.strBlen));
+  r = wcsncmp(v1.strB, v2.strB, NS_MIN(v1.strBlen,v2.strBlen));
   if (r)
     return r;
 
   r = ns_cmp(v1.numC, v2.numC);
   if (r)
     return r;
 
   if (!v1.extraD)
--- a/xpcom/glue/nsVoidArray.cpp
+++ b/xpcom/glue/nsVoidArray.cpp
@@ -277,17 +277,17 @@ PRBool nsVoidArray::GrowArrayBy(PRInt32 
   if (newSize >= (PRUint32) kLinearThreshold)
   {
     // newCount includes enough space for at least kMinGrowArrayBy new
     // slots. Select the next power-of-two size in bytes above or
     // equal to that.
     // Also, limit the increase in size to about a VM page or two.
     if (GetArraySize() >= kMaxGrowArrayBy)
     {
-      newCapacity = GetArraySize() + PR_MAX(kMaxGrowArrayBy,aGrowBy);
+      newCapacity = GetArraySize() + NS_MAX(kMaxGrowArrayBy,aGrowBy);
       newSize = SIZEOF_IMPL(newCapacity);
     }
     else
     {
       PR_CEILING_LOG2(newSize, newSize);
       newCapacity = CAPACITYOF_IMPL(PR_BIT(newSize));
     }
   }
@@ -946,17 +946,17 @@ CompareCString(const nsCString* aCString
 {
 #ifdef MOZILLA_INTERNAL_API
   return Compare(*aCString1, *aCString2);
 #else
   const char* s1;
   const char* s2;
   PRUint32 len1 = NS_CStringGetData(*aCString1, &s1);
   PRUint32 len2 = NS_CStringGetData(*aCString2, &s2);
-  int r = memcmp(s1, s2, PR_MIN(len1, len2));
+  int r = memcmp(s1, s2, NS_MIN(len1, len2));
   if (r)
     return r;
 
   if (len1 < len2)
     return -1;
 
   if (len1 > len2)
     return 1;
--- a/xpcom/io/nsFastLoadFile.cpp
+++ b/xpcom/io/nsFastLoadFile.cpp
@@ -33,16 +33,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include <string.h>
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "nscore.h"
 #include "nsDebug.h"
 #include "nsEnumeratorUtils.h"
 #include "nsMemory.h"
 #include "nsXPIDLString.h"
 #include "nsString.h"
 #include "nsReadableUtils.h"
 
@@ -561,17 +562,17 @@ nsFastLoadFileReader::Read(char* aBuffer
 
             NS_ASSERTION(entry->mBytesLeft >= 8, "demux segment length botch!");
             entry->mBytesLeft -= 8;
         }
     }
     if (!mFileData)
         return NS_BASE_STREAM_CLOSED;
 
-    PRUint32 count = PR_MIN(mFileLen - mFilePos, aCount);
+    PRUint32 count = NS_MIN(mFileLen - mFilePos, aCount);
     memcpy(aBuffer, mFileData+mFilePos, count);
     *aBytesRead = count;
     mFilePos += count;
     if (entry) {
         NS_ASSERTION(entry->mBytesLeft >= *aBytesRead, "demux Read underflow!");
         entry->mBytesLeft -= *aBytesRead;
 
 #ifdef NS_DEBUG
@@ -590,17 +591,17 @@ nsFastLoadFileReader::ReadSegments(nsWri
     nsDocumentMapReadEntry* entry = mCurrentDocumentMapEntry;
 
     NS_ASSERTION(!entry || (!entry->mNeedToSeek && entry->mBytesLeft != 0),
                  "ReadSegments called from above nsFastLoadFileReader layer?!");
 
     if (!mFileData)
         return NS_BASE_STREAM_CLOSED;
 
-    PRUint32 count = PR_MIN(mFileLen - mFilePos, aCount);
+    PRUint32 count = NS_MIN(mFileLen - mFilePos, aCount);
 
     // Errors returned from the writer get ignored.
     aWriter(this, aClosure, (char*)(mFileData + mFilePos), 0,
             count, aResult);
     mFilePos += count;
     if (entry) {
         NS_ASSERTION(entry->mBytesLeft >= *aResult,
                      "demux ReadSegments underflow!");
--- a/xpcom/io/nsFastLoadFile.h
+++ b/xpcom/io/nsFastLoadFile.h
@@ -40,16 +40,17 @@
 #define nsFastLoadFile_h___
 
 /**
  * Mozilla FastLoad file format and helper types.
  */
 
 #include "prtypes.h"
 #include "pldhash.h"
+#include "nsAlgorithm.h"
 
 #include "nsBinaryStream.h"
 #include "nsCOMPtr.h"
 #include "nsDebug.h"
 #include "nsID.h"
 #include "nsMemory.h"
 
 #include "nsIFastLoadFileControl.h"
@@ -278,17 +279,17 @@ class nsFastLoadFileReader
     // nsISupports methods
     NS_DECL_ISUPPORTS_INHERITED
 
     // overridden nsIObjectInputStream methods
     NS_IMETHOD ReadObject(PRBool aIsStrongRef, nsISupports* *_retval);
     NS_IMETHOD ReadID(nsID *aResult);
 
     void SeekTo(PRInt64 aOffset) {
-        mFilePos = PR_MAX(0, PR_MIN(aOffset, mFileLen));
+        mFilePos = NS_MAX<PRInt64>(0, NS_MIN<PRInt64>(aOffset, mFileLen));
         NS_ASSERTION(aOffset == mFilePos, "Attempt to seek out of bounds");
     }
 
     // nsIFastLoadFileControl methods
     NS_DECL_NSIFASTLOADFILECONTROL
 
     // nsIFastLoadReadControl methods
     NS_DECL_NSIFASTLOADREADCONTROL
--- a/xpcom/io/nsPipe3.cpp
+++ b/xpcom/io/nsPipe3.cpp
@@ -42,16 +42,17 @@
 #include "nsIProgrammingLanguage.h"
 #include "nsSegmentedBuffer.h"
 #include "nsStreamUtils.h"
 #include "nsCOMPtr.h"
 #include "nsCRT.h"
 #include "prlog.h"
 #include "nsIClassInfoImpl.h"
 #include "nsAtomicRefcnt.h"
+#include "nsAlgorithm.h"
 
 using namespace mozilla;
 
 #if defined(PR_LOGGING)
 //
 // set NSPR_LOG_MODULES=nsPipe:5
 //
 static PRLogModuleInfo *gPipeLog = PR_NewLogModule("nsPipe");
@@ -953,17 +954,17 @@ nsPipeInputStream::Search(const char *fo
             *found = PR_FALSE;
             *offsetSearchedTo = offset - strLen + 1;
             LOG(("  result [found=%u offset=%u]\n", *found, *offsetSearchedTo));
             return NS_OK;
         }
         len2 = limit2 - cursor2;
 
         // check if the string is straddling the next buffer segment
-        PRUint32 lim = PR_MIN(strLen, len2 + 1);
+        PRUint32 lim = NS_MIN(strLen, len2 + 1);
         for (i = 0; i < lim; ++i) {
             PRUint32 strPart1Len = strLen - i - 1;
             PRUint32 strPart2Len = strLen - strPart1Len;
             const char* strPart2 = &forString[strLen - strPart2Len];
             PRUint32 bufSeg1Offset = len1 - strPart1Len;
             if (COMPARE(&cursor1[bufSeg1Offset], forString, strPart1Len) == 0 &&
                 COMPARE(cursor2, strPart2, strPart2Len) == 0) {
                 *found = PR_TRUE;
--- a/xpcom/io/nsScriptableInputStream.cpp
+++ b/xpcom/io/nsScriptableInputStream.cpp
@@ -68,17 +68,17 @@ nsScriptableInputStream::Read(PRUint32 a
     PRUint32 count = 0;
     char *buffer = nsnull;
 
     if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
 
     rv = mInputStream->Available(&count);
     if (NS_FAILED(rv)) return rv;
 
-    count = PR_MIN(count, aCount);
+    count = NS_MIN(count, aCount);
     buffer = (char*)nsMemory::Alloc(count+1); // make room for '\0'
     if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
 
     PRUint32 amtRead = 0;
     rv = mInputStream->Read(buffer, count, &amtRead);
     if (NS_FAILED(rv)) {
         nsMemory::Free(buffer);
         return rv;
--- a/xpcom/io/nsStorageStream.cpp
+++ b/xpcom/io/nsStorageStream.cpp
@@ -41,16 +41,17 @@
 /*
  * The storage stream provides an internal buffer that can be filled by a
  * client using a single output stream.  One or more independent input streams
  * can be created to read the data out non-destructively.  The implementation
  * uses a segmented buffer internally to avoid realloc'ing of large buffers,
  * with the attendant performance loss and heap fragmentation.
  */
 
+#include "nsAlgorithm.h"
 #include "nsStorageStream.h"
 #include "nsSegmentedBuffer.h"
 #include "nsStreamUtils.h"
 #include "nsCOMPtr.h"
 #include "prbit.h"
 #include "nsIInputStream.h"
 #include "nsISeekableStream.h"
 #include "prlog.h"
@@ -199,17 +200,17 @@ nsStorageStream::Write(const char *aBuff
             }
             mLastSegmentNum++;
             mSegmentEnd = mWriteCursor + mSegmentSize;
             availableInSegment = mSegmentEnd - mWriteCursor;
             LOG(("nsStorageStream [%p] Write (new seg) mWriteCursor=%x mSegmentEnd=%x\n",
                 this, mWriteCursor, mSegmentEnd));
         }
 	
-        count = PR_MIN(availableInSegment, remaining);
+        count = NS_MIN(availableInSegment, remaining);
         memcpy(mWriteCursor, readCursor, count);
         remaining -= count;
         readCursor += count;
         mWriteCursor += count;
         LOG(("nsStorageStream [%p] Writing mWriteCursor=%x mSegmentEnd=%x count=%d\n",
             this, mWriteCursor, mSegmentEnd, count));
     };
 
@@ -436,21 +437,21 @@ nsStorageInputStream::ReadSegments(nsWri
     while (remainingCapacity) {
         availableInSegment = mSegmentEnd - mReadCursor;
         if (!availableInSegment) {
             PRUint32 available = mStorageStream->mLogicalLength - mLogicalCursor;
             if (!available)
                 goto out;
 
             mReadCursor = mStorageStream->mSegmentedBuffer->GetSegment(++mSegmentNum);
-            mSegmentEnd = mReadCursor + PR_MIN(mSegmentSize, available);
+            mSegmentEnd = mReadCursor + NS_MIN(mSegmentSize, available);
             availableInSegment = mSegmentEnd - mReadCursor;
         }
 	
-        count = PR_MIN(availableInSegment, remainingCapacity);
+        count = NS_MIN(availableInSegment, remainingCapacity);
         rv = writer(this, closure, mReadCursor, aCount - remainingCapacity,
                     count, &bytesConsumed);
         if (NS_FAILED(rv) || (bytesConsumed == 0))
           break;
         remainingCapacity -= bytesConsumed;
         mReadCursor += bytesConsumed;
         mLogicalCursor += bytesConsumed;
     };
@@ -532,17 +533,17 @@ nsStorageInputStream::Seek(PRUint32 aPos
     if (length == 0)
         return NS_OK;
 
     mSegmentNum = SegNum(aPosition);
     PRUint32 segmentOffset = SegOffset(aPosition);
     mReadCursor = mStorageStream->mSegmentedBuffer->GetSegment(mSegmentNum) +
         segmentOffset;
     PRUint32 available = length - aPosition;
-    mSegmentEnd = mReadCursor + PR_MIN(mSegmentSize - segmentOffset, available);
+    mSegmentEnd = mReadCursor + NS_MIN(mSegmentSize - segmentOffset, available);
     mLogicalCursor = aPosition;
     return NS_OK;
 }
 
 NS_COM nsresult
 NS_NewStorageStream(PRUint32 segmentSize, PRUint32 maxSize, nsIStorageStream **result)
 {
     NS_ENSURE_ARG(result);
--- a/xpcom/io/nsUnicharInputStream.cpp
+++ b/xpcom/io/nsUnicharInputStream.cpp
@@ -95,17 +95,17 @@ NS_IMETHODIMP
 StringUnicharInputStream::ReadSegments(nsWriteUnicharSegmentFun aWriter,
                                        void* aClosure,
                                        PRUint32 aCount, PRUint32 *aReadCount)
 {
   PRUint32 bytesWritten;
   PRUint32 totalBytesWritten = 0;
 
   nsresult rv;
-  aCount = PR_MIN(mString.Length() - mPos, aCount);
+  aCount = NS_MIN(mString.Length() - mPos, aCount);
   
   nsAString::const_iterator iter;
   mString.BeginReading(iter);
   
   while (aCount) {
     rv = aWriter(this, aClosure, iter.get() + mPos,
                  totalBytesWritten, aCount, &bytesWritten);
     
--- a/xpcom/string/public/nsAlgorithm.h
+++ b/xpcom/string/public/nsAlgorithm.h
@@ -49,32 +49,49 @@
   // for |PRUint32|...
 #endif
 
 #ifndef nsDebug_h___
 #include "nsDebug.h"
   // for NS_ASSERTION
 #endif
 
+
+template <class T>
+inline
+T
+NS_ROUNDUP( const T& a, const T& b )
+  {
+    return ((a + (b - 1)) / b) * b;
+  }
+
 template <class T>
 inline
 const T&
 NS_MIN( const T& a, const T& b )
   {
     return b < a ? b : a;
   }
 
 template <class T>
 inline
 const T&
 NS_MAX( const T& a, const T& b )
   {
     return a > b ? a : b;
   }
 
+template <class T>
+inline
+T
+NS_ABS( const T& a )
+  {
+    return a < 0 ? -a : a;
+  }
+
 template <class InputIterator, class T>
 inline
 PRUint32
 NS_COUNT( InputIterator& first, const InputIterator& last, const T& value )
   {
     PRUint32 result = 0;
     for ( ; first != last; ++first )
       if ( *first == value )
--- a/xpcom/string/src/nsReadableUtils.cpp
+++ b/xpcom/string/src/nsReadableUtils.cpp
@@ -632,17 +632,17 @@ class CopyToUpperCase
       CopyToUpperCase( nsACString::iterator& aDestIter )
         : mIter(aDestIter)
         {
         }
 
       PRUint32
       write( const char* aSource, PRUint32 aSourceLength )
         {
-          PRUint32 len = PR_MIN(PRUint32(mIter.size_forward()), aSourceLength);
+          PRUint32 len = NS_MIN(PRUint32(mIter.size_forward()), aSourceLength);
           char* cp = mIter.get();
           const char* end = aSource + len;
           while (aSource != end) {
             char ch = *aSource;
             if ((ch >= 'a') && (ch <= 'z'))
               *cp = ch - ('a' - 'A');
             else
               *cp = ch;
@@ -713,17 +713,17 @@ class CopyToLowerCase
       CopyToLowerCase( nsACString::iterator& aDestIter )
         : mIter(aDestIter)
         {
         }
 
       PRUint32
       write( const char* aSource, PRUint32 aSourceLength )
         {
-          PRUint32 len = PR_MIN(PRUint32(mIter.size_forward()), aSourceLength);
+          PRUint32 len = NS_MIN(PRUint32(mIter.size_forward()), aSourceLength);
           char* cp = mIter.get();
           const char* end = aSource + len;
           while (aSource != end) {
             char ch = *aSource;
             if ((ch >= 'A') && (ch <= 'Z'))
               *cp = ch + ('a' - 'A');
             else
               *cp = ch;
--- a/xpcom/string/src/nsTSubstring.cpp
+++ b/xpcom/string/src/nsTSubstring.cpp
@@ -449,17 +449,17 @@ nsTSubstring_CharT::Adopt( char_type* da
       }
   }
 
 
   // This version of Replace is optimized for single-character replacement.
 void
 nsTSubstring_CharT::Replace( index_type cutStart, size_type cutLength, char_type c )
   {
-    cutStart = PR_MIN(cutStart, Length());
+    cutStart = NS_MIN(cutStart, Length());
 
     if (ReplacePrep(cutStart, cutLength, 1))
       mData[cutStart] = c;
   }
 
 
 void
 nsTSubstring_CharT::Replace( index_type cutStart, size_type cutLength, const char_type* data, size_type length )
@@ -477,17 +477,17 @@ nsTSubstring_CharT::Replace( index_type 
         if (IsDependentOn(data, data + length))
           {
             nsTAutoString_CharT temp(data, length);
             Replace(cutStart, cutLength, temp);
             return;
           }
       }
 
-    cutStart = PR_MIN(cutStart, Length());
+    cutStart = NS_MIN(cutStart, Length());
 
     if (ReplacePrep(cutStart, cutLength, length) && length > 0)
       char_traits::copy(mData + cutStart, data, length);
   }
 
 void
 nsTSubstring_CharT::ReplaceASCII( index_type cutStart, size_type cutLength, const char* data, size_type length )
   {
@@ -500,17 +500,17 @@ nsTSubstring_CharT::ReplaceASCII( index_
     if (IsDependentOn(data, data + length))
       {
         nsTAutoString_CharT temp(data, length);
         Replace(cutStart, cutLength, temp);
         return;
       }
 #endif
 
-    cutStart = PR_MIN(cutStart, Length());
+    cutStart = NS_MIN(cutStart, Length());
 
     if (ReplacePrep(cutStart, cutLength, length) && length > 0)
       char_traits::copyASCII(mData + cutStart, data, length);
   }
 
 void
 nsTSubstring_CharT::Replace( index_type cutStart, size_type cutLength, const substring_tuple_type& tuple )
   {
@@ -518,17 +518,17 @@ nsTSubstring_CharT::Replace( index_type 
       {
         nsTAutoString_CharT temp(tuple);
         Replace(cutStart, cutLength, temp);
         return;
       }
 
     size_type length = tuple.Length();
 
-    cutStart = PR_MIN(cutStart, Length());
+    cutStart = NS_MIN(cutStart, Length());
 
     if (ReplacePrep(cutStart, cutLength, length) && length > 0)
       tuple.WriteTo(mData + cutStart, length);
   }
 
 PRBool
 nsTSubstring_CharT::SetCapacity( size_type capacity )
   {
--- a/xpcom/tests/TestPipes.cpp
+++ b/xpcom/tests/TestPipes.cpp
@@ -310,17 +310,17 @@ TestShortWrites(nsIInputStream* in, nsIO
     if (NS_FAILED(rv)) return rv;
 
     PRUint32 total = 0;
     for (PRUint32 i = 0; i < ITERATIONS; i++) {
         PRUint32 writeCount;
         char* buf = PR_smprintf("%d %s", i, kTestPattern);
         PRUint32 len = strlen(buf);
         len = len * rand() / RAND_MAX;
-        len = PR_MAX(1, len);
+        len = NS_MAX(1, len);
         rv = WriteAll(out, buf, len, &writeCount);
         if (NS_FAILED(rv)) return rv;
         NS_ASSERTION(writeCount == len, "didn't write enough");
         total += writeCount;
 
         if (gTrace)
             printf("wrote %d bytes: %s\n", writeCount, buf);
         PR_smprintf_free(buf);
@@ -419,17 +419,17 @@ TestChainedPipes()
     if (NS_FAILED(rv)) return rv;
 
     PRUint32 total = 0;
     for (PRUint32 i = 0; i < ITERATIONS; i++) {
         PRUint32 writeCount;
         char* buf = PR_smprintf("%d %s", i, kTestPattern);
         PRUint32 len = strlen(buf);
         len = len * rand() / RAND_MAX;
-        len = PR_MAX(1, len);
+        len = NS_MAX(1, len);
         rv = WriteAll(out1, buf, len, &writeCount);
         if (NS_FAILED(rv)) return rv;
         NS_ASSERTION(writeCount == len, "didn't write enough");
         total += writeCount;
 
         if (gTrace)
             printf("wrote %d bytes: %s\n", writeCount, buf);
 
--- a/xpfe/appshell/src/nsXULWindow.cpp
+++ b/xpfe/appshell/src/nsXULWindow.cpp
@@ -1337,18 +1337,18 @@ void nsXULWindow::StaggerPosition(PRInt3
       windowList->GetNext(getter_AddRefs(supportsWindow));
 
       nsCOMPtr<nsIXULWindow> listXULWindow(do_QueryInterface(supportsWindow));
       if (listXULWindow != ourXULWindow) {
         PRInt32 listX, listY;
         nsCOMPtr<nsIBaseWindow> listBaseWindow(do_QueryInterface(supportsWindow));
         listBaseWindow->GetPosition(&listX, &listY);
 
-        if (PR_ABS(listX - aRequestedX) <= kSlop &&
-            PR_ABS(listY - aRequestedY) <= kSlop) {
+        if (NS_ABS(listX - aRequestedX) <= kSlop &&
+            NS_ABS(listY - aRequestedY) <= kSlop) {
           // collision! offset and start over
           if (bouncedX & 0x1)
             aRequestedX -= kOffset;
           else
             aRequestedX += kOffset;
           aRequestedY += kOffset;
 
           if (gotScreen) {
--- a/xpinstall/src/CertReader.cpp
+++ b/xpinstall/src/CertReader.cpp
@@ -161,17 +161,17 @@ CertReader::OnDataAvailable(nsIRequest *
     return NS_BINDING_ABORTED;
 
   char buf[4096];
   PRUint32 amt, size;
   nsresult rv;
 
   while (aLength)
   {
-    size = PR_MIN(aLength, sizeof(buf));
+    size = NS_MIN(aLength, sizeof(buf));
 
     rv = aIStream->Read(buf, size, &amt);
     if (NS_FAILED(rv))
       return rv;
 
     aLength -= amt;
 
     mLeftoverBuffer.Append(buf, amt);
--- a/xpinstall/src/nsXPInstallManager.cpp
+++ b/xpinstall/src/nsXPInstallManager.cpp
@@ -1224,17 +1224,17 @@ nsXPInstallManager::OnStopRequest(nsIReq
 
 NS_IMETHODIMP
 nsXPInstallManager::OnDataAvailable(nsIRequest* request, nsISupports *ctxt,
                                     nsIInputStream *pIStream,
                                     PRUint32 sourceOffset,
                                     PRUint32 length)
 {
 #define XPI_ODA_BUFFER_SIZE 8*1024
-    PRUint32 amt = PR_MIN(XPI_ODA_BUFFER_SIZE, length);
+    PRUint32 amt = NS_MIN(XPI_ODA_BUFFER_SIZE, length);
     nsresult err;
     char buffer[XPI_ODA_BUFFER_SIZE];
     PRUint32 writeCount;
 
     if (mCancelled)
     {
         // We must cancel this download in progress. We may get extra
         // OnData calls if they were already queued so beware
@@ -1251,17 +1251,17 @@ nsXPInstallManager::OnDataAvailable(nsIR
 
         err = mItem->mOutStream->Write( buffer, amt, &writeCount);
         if (NS_FAILED(err) || writeCount != amt)
         {
             return NS_ERROR_FAILURE;
         }
         length -= amt;
 
-        amt = PR_MIN(XPI_ODA_BUFFER_SIZE, length);
+        amt = NS_MIN(XPI_ODA_BUFFER_SIZE, length);
 
     } while (length > 0);
 
     return NS_OK;
 }
 
 
 NS_IMETHODIMP