Bug 661584 - Code cleanup, substitute more PR_(MAX|MIN|ABS|ROUNDUP) macro calls; r=roc,ted
authorEd Morley <bmo@edmorley.co.uk>
Sat, 25 Jun 2011 16:06:02 +0200
changeset 71786 fc776fa4afb78d940418997eab4a958c6a5a4d48
parent 71785 28e4374838c43d6ce192380dd9136b8ca2b84d62
child 71787 52292b725188c20b09cf816ab3763524be0783ee
push idunknown
push userunknown
push dateunknown
reviewersroc, ted
bugs661584
milestone7.0a1
Bug 661584 - Code cleanup, substitute more PR_(MAX|MIN|ABS|ROUNDUP) macro calls; r=roc,ted
content/base/src/nsTextFragment.cpp
content/base/src/nsTextFragmentSSE2.cpp
content/canvas/src/CustomQS_Canvas2D.h
content/html/content/src/nsHTMLProgressElement.cpp
content/media/nsAudioStream.cpp
content/media/nsBuiltinDecoderStateMachine.cpp
content/media/nsMediaCache.cpp
content/media/wave/nsWaveReader.cpp
docshell/shistory/src/nsSHEntry.cpp
dom/plugins/test/testplugin/nptest_macosx.mm
extensions/gio/nsGIOProtocolHandler.cpp
gfx/src/nsBoundingMetrics.h
gfx/src/nsCoord.h
gfx/src/nsDeviceContext.cpp
gfx/src/nsFontMetrics.cpp
gfx/src/nsRegion.cpp
gfx/src/nsRenderingContext.cpp
gfx/thebes/gfxFont.cpp
gfx/thebes/gfxFont.h
gfx/thebes/gfxMacPlatformFontList.mm
layout/base/nsCSSRendering.cpp
layout/base/nsPresShell.cpp
layout/generic/nsGfxScrollFrame.cpp
layout/generic/nsTextFrameThebes.cpp
netwerk/base/src/nsUnicharStreamLoader.cpp
netwerk/cache/nsDiskCacheStreams.cpp
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/test/TestHttp.cpp
netwerk/test/TestMCTransport.cpp
netwerk/test/TestOverlappedIO.cpp
netwerk/test/TestPageLoad.cpp
netwerk/test/TestPerf.cpp
netwerk/test/TestProtocols.cpp
netwerk/test/TestStreamChannel.cpp
netwerk/test/TestStreamPump.cpp
netwerk/test/TestThreadedIO.cpp
netwerk/test/TestUpload.cpp
testing/mochitest/ssltunnel/Makefile.in
testing/mochitest/ssltunnel/ssltunnel.cpp
widget/src/cocoa/GfxInfo.mm
widget/src/cocoa/nsNativeThemeCocoa.mm
widget/src/qt/nsWindow.cpp
widget/src/windows/nsIMM32Handler.cpp
widget/src/windows/nsWindow.cpp
xpcom/string/src/nsUTF8UtilsSSE2.cpp
--- a/content/base/src/nsTextFragment.cpp
+++ b/content/base/src/nsTextFragment.cpp
@@ -160,17 +160,17 @@ Is8BitUnvectorized(const PRUnichar *str,
 #error Unknown platform!
 #endif
 
   const PRInt32 len = end - str;
   PRInt32 i = 0;
 
   // Align ourselves to a word boundary.
   PRInt32 alignLen =
-    PR_MIN(len, PRInt32(((-NS_PTR_TO_UINT32(str)) & alignMask) / sizeof(PRUnichar)));
+    NS_MIN(len, PRInt32(((-NS_PTR_TO_INT32(str)) & alignMask) / sizeof(PRUnichar)));
   for (; i < alignLen; i++) {
     if (str[i] > 255)
       return PR_FALSE;
   }
 
   // Check one word at a time.
   const PRInt32 wordWalkEnd = ((len - i) / numUnicharsPerWord) * numUnicharsPerWord;
   for (; i < wordWalkEnd; i += numUnicharsPerWord) {
--- a/content/base/src/nsTextFragmentSSE2.cpp
+++ b/content/base/src/nsTextFragmentSSE2.cpp
@@ -1,13 +1,14 @@
 // This file should only be compiled if you're on x86 or x86_64.  Additionally,
 // you'll need to compile this file with -msse2 if you're using gcc.
 
 #include <emmintrin.h>
 #include "nscore.h"
+#include "nsAlgorithm.h"
 
 namespace mozilla {
 namespace SSE2 {
 
 static inline bool
 is_zero (__m128i x)
 {
   return
@@ -30,17 +31,17 @@ Is8Bit(const PRUnichar *str, const PRUni
 #endif
 
   const PRInt32 len = end - str;
   PRInt32 i = 0;
 
   // Align ourselves to a 16-byte boundary, as required by _mm_load_si128
   // (i.e. MOVDQA).
   PRInt32 alignLen =
-    PR_MIN(len, PRInt32(((-NS_PTR_TO_UINT32(str)) & 0xf) / sizeof(PRUnichar)));
+    NS_MIN(len, PRInt32(((-NS_PTR_TO_INT32(str)) & 0xf) / sizeof(PRUnichar)));
   for (; i < alignLen; i++) {
     if (str[i] > 255)
       return PR_FALSE;
   }
 
   // Check one XMM register (16 bytes) at a time.
   const PRInt32 vectWalkEnd = ((len - i) / numUnicharsPerVector) * numUnicharsPerVector;
   __m128i vectmask = _mm_set1_epi16(0xff00);
--- a/content/canvas/src/CustomQS_Canvas2D.h
+++ b/content/canvas/src/CustomQS_Canvas2D.h
@@ -282,18 +282,18 @@ nsIDOMCanvasRenderingContext2D_CreateIma
         return xpc_qsThrow(cx, NS_ERROR_DOM_NOT_SUPPORTED_ERR);
 
     if (!width || !height)
         return xpc_qsThrow(cx, NS_ERROR_DOM_INDEX_SIZE_ERR);
 
     int32 wi = JS_DoubleToInt32(width);
     int32 hi = JS_DoubleToInt32(height);
 
-    uint32 w = PR_ABS(wi);
-    uint32 h = PR_ABS(hi);
+    uint32 w = NS_ABS(wi);
+    uint32 h = NS_ABS(hi);
     return CreateImageData(cx, w, h, NULL, 0, 0, vp);
 }
 
 static JSBool
 nsIDOMCanvasRenderingContext2D_GetImageData(JSContext *cx, uintN argc, jsval *vp)
 {
     XPC_QS_ASSERT_CONTEXT_OK(cx);
 
--- a/content/html/content/src/nsHTMLProgressElement.cpp
+++ b/content/html/content/src/nsHTMLProgressElement.cpp
@@ -181,17 +181,17 @@ nsHTMLProgressElement::GetValue(double* 
     return NS_OK;
   }
 
   *aValue = attrValue->GetDoubleValue();
 
   double max;
   GetMax(&max);
 
-  *aValue = PR_MIN(*aValue, max);
+  *aValue = NS_MIN(*aValue, max);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLProgressElement::SetValue(double aValue)
 {
   return SetDoubleAttr(nsGkAtoms::value, aValue);
--- a/content/media/nsAudioStream.cpp
+++ b/content/media/nsAudioStream.cpp
@@ -324,17 +324,17 @@ static double gVolumeScale = 1.0;
 
 static int VolumeScaleChanged(const char* aPref, void *aClosure) {
   nsAdoptingString value = Preferences::GetString("media.volume_scale");
   mozilla::MutexAutoLock lock(*gVolumeScaleLock);
   if (value.IsEmpty()) {
     gVolumeScale = 1.0;
   } else {
     NS_ConvertUTF16toUTF8 utf8(value);
-    gVolumeScale = PR_MAX(0, PR_strtod(utf8.get(), nsnull));
+    gVolumeScale = NS_MAX<double>(0, PR_strtod(utf8.get(), nsnull));
   }
   return 0;
 }
 
 static double GetVolumeScale() {
   mozilla::MutexAutoLock lock(*gVolumeScaleLock);
   return gVolumeScale;
 }
--- a/content/media/nsBuiltinDecoderStateMachine.cpp
+++ b/content/media/nsBuiltinDecoderStateMachine.cpp
@@ -1530,17 +1530,17 @@ void nsBuiltinDecoderStateMachine::Advan
         mState == DECODER_STATE_COMPLETED) {
       mDecoder->GetReentrantMonitor().Wait();
     }
   }
 }
 
 void nsBuiltinDecoderStateMachine::Wait(PRInt64 aUsecs) {
   mDecoder->GetReentrantMonitor().AssertCurrentThreadIn();
-  TimeStamp end = TimeStamp::Now() + UsecsToDuration(PR_MAX(USECS_PER_MS, aUsecs));
+  TimeStamp end = TimeStamp::Now() + UsecsToDuration(NS_MAX<PRInt64>(USECS_PER_MS, aUsecs));
   TimeStamp now;
   while ((now = TimeStamp::Now()) < end &&
          mState != DECODER_STATE_SHUTDOWN &&
          mState != DECODER_STATE_SEEKING)
   {
     PRInt64 ms = static_cast<PRInt64>(NS_round((end - now).ToSeconds() * 1000));
     if (ms == 0 || ms > PR_UINT32_MAX) {
       break;
--- a/content/media/nsMediaCache.cpp
+++ b/content/media/nsMediaCache.cpp
@@ -736,18 +736,18 @@ nsMediaCache::WriteCacheFile(PRInt64 aOf
 
 static PRInt32 GetMaxBlocks()
 {
   // We look up the cache size every time. This means dynamic changes
   // to the pref are applied.
   // Cache size is in KB
   PRInt32 cacheSize = Preferences::GetInt("media.cache_size", 500*1024);
   PRInt64 maxBlocks = static_cast<PRInt64>(cacheSize)*1024/nsMediaCache::BLOCK_SIZE;
-  maxBlocks = PR_MAX(maxBlocks, 1);
-  return PRInt32(PR_MIN(maxBlocks, PR_INT32_MAX));
+  maxBlocks = NS_MAX<PRInt64>(maxBlocks, 1);
+  return PRInt32(NS_MIN<PRInt64>(maxBlocks, PR_INT32_MAX));
 }
 
 PRInt32
 nsMediaCache::FindBlockForIncomingData(TimeStamp aNow,
                                        nsMediaCacheStream* aStream)
 {
   mReentrantMonitor.AssertCurrentThreadIn();
 
--- a/content/media/wave/nsWaveReader.cpp
+++ b/content/media/wave/nsWaveReader.cpp
@@ -376,17 +376,17 @@ nsWaveReader::ScanForwardUntil(PRUint32 
 
     // RIFF chunks are two-byte aligned, so round up if necessary.
     chunkSize += chunkSize % 2;
 
     static const unsigned int MAX_CHUNK_SIZE = 1 << 16;
     PR_STATIC_ASSERT(MAX_CHUNK_SIZE < UINT_MAX / sizeof(char));
     nsAutoArrayPtr<char> chunk(new char[MAX_CHUNK_SIZE]);
     while (chunkSize > 0) {
-      PRUint32 size = PR_MIN(chunkSize, MAX_CHUNK_SIZE);
+      PRUint32 size = NS_MIN(chunkSize, MAX_CHUNK_SIZE);
       if (!ReadAll(chunk.get(), size)) {
         return PR_FALSE;
       }
       chunkSize -= size;
     }
   }
 }
 
@@ -540,18 +540,18 @@ PRInt64
 nsWaveReader::GetDataLength()
 {
   PRInt64 length = mWaveLength;
   // If the decoder has a valid content length, and it's shorter than the
   // expected length of the PCM data, calculate the playback duration from
   // the content length rather than the expected PCM data length.
   PRInt64 streamLength = mDecoder->GetCurrentStream()->GetLength();
   if (streamLength >= 0) {
-    PRInt64 dataLength = PR_MAX(0, streamLength - mWavePCMOffset);
-    length = PR_MIN(dataLength, length);
+    PRInt64 dataLength = NS_MAX<PRInt64>(0, streamLength - mWavePCMOffset);
+    length = NS_MIN(dataLength, length);
   }
   return length;
 }
 
 PRInt64
 nsWaveReader::GetPosition()
 {
   return mDecoder->GetCurrentStream()->Tell();
--- a/docshell/shistory/src/nsSHEntry.cpp
+++ b/docshell/shistory/src/nsSHEntry.cpp
@@ -651,17 +651,17 @@ nsSHEntry::AddChild(nsISHEntry * aChild,
       aChild->SetParent(nsnull);
       return NS_ERROR_FAILURE;
     }
   } else {
     // If the new child isn't dynamically added, it should be set to aOffset.
     // If there are dynamically added children before that, those must be
     // moved to be after aOffset.
     if (mChildren.Count() > 0) {
-      PRInt32 start = PR_MIN(mChildren.Count() - 1, aOffset);
+      PRInt32 start = NS_MIN(mChildren.Count() - 1, aOffset);
       PRInt32 dynEntryIndex = -1;
       nsISHEntry* dynEntry = nsnull;
       for (PRInt32 i = start; i >= 0; --i) {
         nsISHEntry* entry = mChildren[i];
         if (entry) {
           PRBool dyn = PR_FALSE;
           entry->IsDynamicallyAdded(&dyn);
           if (dyn) {
--- a/dom/plugins/test/testplugin/nptest_macosx.mm
+++ b/dom/plugins/test/testplugin/nptest_macosx.mm
@@ -27,16 +27,17 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  * 
  * Contributor(s):
  *   Josh Aas <josh@mozilla.com>
  * 
  * ***** END LICENSE BLOCK ***** */
 
 #include "nptest_platform.h"
+#include "nsAlgorithm.h"
 #include <CoreServices/CoreServices.h>
 
 using namespace std;
 
 bool
 pluginSupportsWindowMode()
 {
   return false;
@@ -186,18 +187,18 @@ pluginDraw(InstanceData* instanceData, N
     CGContextSetLineWidth(cgContext, 6.0);
     CGContextStrokePath(cgContext);
 
     // draw the UA string using Core Text
     CGContextSetTextMatrix(cgContext, CGAffineTransformIdentity);
 
     // Initialize a rectangular path.
     CGMutablePathRef path = CGPathCreateMutable();
-    CGRect bounds = CGRectMake(10.0, 10.0, PR_MAX(0.0, windowWidth - 20.0),
-                               PR_MAX(0.0, windowHeight - 20.0));
+    CGRect bounds = CGRectMake(10.0, 10.0, NS_MAX(0.0, windowWidth - 20.0),
+                               NS_MAX(0.0, windowHeight - 20.0));
     CGPathAddRect(path, NULL, bounds);
 
     // Initialize an attributed string.
     CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
     CFAttributedStringReplaceString(attrString, CFRangeMake(0, 0), uaCFString);
 
     // Create a color and add it as an attribute to the string.
     CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
--- a/extensions/gio/nsGIOProtocolHandler.cpp
+++ b/extensions/gio/nsGIOProtocolHandler.cpp
@@ -476,17 +476,17 @@ nsGIOInputStream::DoRead(char *aBuf, PRU
   else if (mDirOpen) {
     // directory read
     while (aCount && rv != NS_BASE_STREAM_CLOSED)
     {
       // 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/gfx/src/nsBoundingMetrics.h
+++ b/gfx/src/nsBoundingMetrics.h
@@ -103,16 +103,16 @@ struct nsBoundingMetrics {
             ascent = bm.ascent;
             descent = bm.descent;
             leftBearing = width + bm.leftBearing;
             rightBearing = width + bm.rightBearing;
         }
         else {
             if (ascent < bm.ascent) ascent = bm.ascent;
             if (descent < bm.descent) descent = bm.descent;
-            leftBearing = PR_MIN(leftBearing, width + bm.leftBearing);
-            rightBearing = PR_MAX(rightBearing, width + bm.rightBearing);
+            leftBearing = NS_MIN(leftBearing, width + bm.leftBearing);
+            rightBearing = NS_MAX(rightBearing, width + bm.rightBearing);
         }
         width += bm.width;
     }
 };
 
 #endif // __nsBoundingMetrics_h
--- a/gfx/src/nsCoord.h
+++ b/gfx/src/nsCoord.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 NSCOORD_H
 #define NSCOORD_H
 
+#include "nsAlgorithm.h"
 #include "nscore.h"
 #include "nsMathUtils.h"
 #include <math.h>
 #include <float.h>
 
 #include "nsDebug.h"
 
 /*
@@ -137,18 +138,18 @@ inline nscoord _nscoordSaturatingMultipl
                     ? aCoord > 0
                     : (aCoord > 0) == (aScale > 0))
                    ? floorf(aCoord * aScale) < nscoord_MAX
                    : ceilf(aCoord * aScale) > nscoord_MIN,
                    "nscoord multiplication capped");
 
   float product = aCoord * aScale;
   if (requireNotNegative ? aCoord > 0 : (aCoord > 0) == (aScale > 0))
-    return NSToCoordRoundWithClamp(PR_MIN(nscoord_MAX, product));
-  return NSToCoordRoundWithClamp(PR_MAX(nscoord_MIN, product));
+    return NSToCoordRoundWithClamp(NS_MIN<float>(nscoord_MAX, product));
+  return NSToCoordRoundWithClamp(NS_MAX<float>(nscoord_MIN, product));
 #endif
 }
 
 /**
  * Returns aCoord * aScale, capping the product to nscoord_MAX or nscoord_MIN as
  * appropriate for the sign of aCoord.  This method requires aScale to not be
  * negative; use this method when you know that aScale should never be
  * negative to get a sanity check of that invariant in debug builds.
@@ -213,23 +214,23 @@ NSCoordSaturatingAdd(nscoord a, nscoord 
     // infinity + anything = anything + infinity = infinity
     return nscoord_MAX;
   } else {
     // a + b = a + b
     NS_ASSERTION(a < nscoord_MAX && b < nscoord_MAX,
                  "Doing nscoord addition with values > nscoord_MAX");
     NS_ASSERTION((PRInt64)a + (PRInt64)b > (PRInt64)nscoord_MIN,
                  "nscoord addition will reach or pass nscoord_MIN");
-    // This one's only a warning because the PR_MIN below means that
+    // This one's only a warning because the NS_MIN below means that
     // we'll handle this case correctly.
     NS_WARN_IF_FALSE((PRInt64)a + (PRInt64)b < (PRInt64)nscoord_MAX,
                      "nscoord addition capped to nscoord_MAX");
 
     // Cap the result, just in case we're dealing with numbers near nscoord_MAX
-    return PR_MIN(nscoord_MAX, a + b);
+    return NS_MIN(nscoord_MAX, a + b);
   }
 #endif
 }
 
 /**
  * Returns a - b, gracefully handling cases involving nscoord_MAX.
  * This function assumes that neither argument is nscoord_MIN.
  *
@@ -272,23 +273,23 @@ NSCoordSaturatingSubtract(nscoord a, nsc
       // case (c) for integers
       return nscoord_MAX;
     } else {
       // case (d) for integers
       NS_ASSERTION(a < nscoord_MAX && b < nscoord_MAX,
                    "Doing nscoord subtraction with values > nscoord_MAX");
       NS_ASSERTION((PRInt64)a - (PRInt64)b > (PRInt64)nscoord_MIN,
                    "nscoord subtraction will reach or pass nscoord_MIN");
-      // This one's only a warning because the PR_MIN below means that
+      // This one's only a warning because the NS_MIN below means that
       // we'll handle this case correctly.
       NS_WARN_IF_FALSE((PRInt64)a - (PRInt64)b < (PRInt64)nscoord_MAX,
                        "nscoord subtraction capped to nscoord_MAX");
 
       // Cap the result, in case we're dealing with numbers near nscoord_MAX
-      return PR_MIN(nscoord_MAX, a - b);
+      return NS_MIN(nscoord_MAX, a - b);
     }
   }
 #endif
 }
 /** compare against a nscoord "b", which might be unconstrained
   * "a" must not be unconstrained.
   * Every number is smaller than a unconstrained one
   */
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -376,17 +376,17 @@ nsDeviceContext::SetDPI()
         PRInt32 prefDPI = Preferences::GetInt("layout.css.dpi", -1);
 
         if (prefDPI > 0) {
             dpi = prefDPI;
         } else if (mWidget) {
             dpi = mWidget->GetDPI();
 
             if (prefDPI < 0) {
-                dpi = PR_MAX(96.0f, dpi);
+                dpi = NS_MAX(96.0f, dpi);
             }
         } else {
             dpi = 96.0f;
         }
 
         // The number of device pixels per CSS pixel. A value <= 0 means choose
         // automatically based on the DPI. A positive value is used as-is. This effectively
         // controls the size of a CSS "px".
@@ -401,17 +401,17 @@ nsDeviceContext::SetDPI()
             if (mWidget) {
                 devPixelsPerCSSPixel = mWidget->GetDefaultScale();
             } else {
                 devPixelsPerCSSPixel = 1.0;
             }
         }
 
         mAppUnitsPerDevNotScaledPixel =
-            PR_MAX(1, NS_lround(AppUnitsPerCSSPixel() / devPixelsPerCSSPixel));
+            NS_MAX(1, NS_lround(AppUnitsPerCSSPixel() / devPixelsPerCSSPixel));
     }
 
     NS_ASSERTION(dpi != -1.0, "no dpi set");
 
     mAppUnitsPerPhysicalInch = NS_lround(dpi * mAppUnitsPerDevNotScaledPixel);
     UpdateScaledAppUnits();
 }
 
@@ -831,10 +831,10 @@ nsDeviceContext::SetPixelScale(float aSc
     UpdateScaledAppUnits();
     return oldAppUnitsPerDevPixel != mAppUnitsPerDevPixel;
 }
 
 void
 nsDeviceContext::UpdateScaledAppUnits()
 {
     mAppUnitsPerDevPixel =
-        PR_MAX(1, NSToIntRound(float(mAppUnitsPerDevNotScaledPixel) / mPixelScale));
+        NS_MAX(1, NSToIntRound(float(mAppUnitsPerDevNotScaledPixel) / mPixelScale));
 }
--- a/gfx/src/nsFontMetrics.cpp
+++ b/gfx/src/nsFontMetrics.cpp
@@ -192,17 +192,17 @@ nsFontMetrics::GetUnderline(nscoord& aOf
 // nsCSSRendering::GetTextDecorationRectInternal's.
 
 static gfxFloat ComputeMaxDescent(const gfxFont::Metrics& aMetrics,
                                   gfxFontGroup* aFontGroup)
 {
     gfxFloat offset = NS_floor(-aFontGroup->GetUnderlineOffset() + 0.5);
     gfxFloat size = NS_round(aMetrics.underlineSize);
     gfxFloat minDescent = NS_floor(offset + size + 0.5);
-    return PR_MAX(minDescent, aMetrics.maxDescent);
+    return NS_MAX(minDescent, aMetrics.maxDescent);
 }
 
 static gfxFloat ComputeMaxAscent(const gfxFont::Metrics& aMetrics)
 {
     return NS_floor(aMetrics.maxAscent + 0.5);
 }
 
 nscoord
@@ -274,17 +274,17 @@ nsFontMetrics::SpaceWidth()
 }
 
 PRInt32
 nsFontMetrics::GetMaxStringLength()
 {
     const gfxFont::Metrics& m = GetMetrics();
     const double x = 32767.0 / m.maxAdvance;
     PRInt32 len = (PRInt32)floor(x);
-    return PR_MAX(1, len);
+    return NS_MAX(1, len);
 }
 
 nscoord
 nsFontMetrics::GetWidth(const char* aString, PRUint32 aLength,
                         nsRenderingContext *aContext)
 {
     if (aLength == 0)
         return 0;
--- a/gfx/src/nsRegion.cpp
+++ b/gfx/src/nsRegion.cpp
@@ -66,33 +66,33 @@ inline PRBool nsRegion::nsRectFast::Cont
 inline PRBool nsRegion::nsRectFast::Intersects (const nsRect& aRect) const
 {
   return (PRBool) ((x < aRect.XMost ()) && (y < aRect.YMost ()) &&
                    (aRect.x < XMost ()) && (aRect.y < YMost ()));
 }
 
 inline PRBool nsRegion::nsRectFast::IntersectRect (const nsRect& aRect1, const nsRect& aRect2)
 {
-  const nscoord xmost = PR_MIN (aRect1.XMost (), aRect2.XMost ());
-  x = PR_MAX (aRect1.x, aRect2.x);
+  const nscoord xmost = NS_MIN (aRect1.XMost (), aRect2.XMost ());
+  x = NS_MAX (aRect1.x, aRect2.x);
   width = xmost - x;
   if (width <= 0) return PR_FALSE;
 
-  const nscoord ymost = PR_MIN (aRect1.YMost (), aRect2.YMost ());
-  y = PR_MAX (aRect1.y, aRect2.y);
+  const nscoord ymost = NS_MIN (aRect1.YMost (), aRect2.YMost ());
+  y = NS_MAX (aRect1.y, aRect2.y);
   height = ymost - y;
   if (height <= 0) return PR_FALSE;
 
   return PR_TRUE;
 }
 
 inline void nsRegion::nsRectFast::UnionRect (const nsRect& aRect1, const nsRect& aRect2)
 {
-  const nscoord xmost = PR_MAX (aRect1.XMost (), aRect2.XMost ());
-  const nscoord ymost = PR_MAX (aRect1.YMost (), aRect2.YMost ());
+  const nscoord xmost = NS_MAX (aRect1.XMost (), aRect2.XMost ());
+  const nscoord ymost = NS_MAX (aRect1.YMost (), aRect2.YMost ());
   x = PR_MIN (aRect1.x, aRect2.x);
   y = PR_MIN (aRect1.y, aRect2.y);
   width  = xmost - x;
   height = ymost - y;
 }
 
 
 
--- a/gfx/src/nsRenderingContext.cpp
+++ b/gfx/src/nsRenderingContext.cpp
@@ -73,17 +73,17 @@ static PRInt32 FindSafeLength(const PRUn
     }
     return len;
 }
 
 static PRInt32 FindSafeLength(const char *aString, PRUint32 aLength,
                               PRUint32 aMaxChunkLength)
 {
     // Since it's ASCII, we don't need to worry about clusters or RTL
-    return PR_MIN(aLength, aMaxChunkLength);
+    return NS_MIN(aLength, aMaxChunkLength);
 }
 
 //////////////////////////////////////////////////////////////////////
 //// nsRenderingContext
 
 void
 nsRenderingContext::Init(nsDeviceContext* aContext,
                          gfxASurface *aThebesSurface)
@@ -476,17 +476,17 @@ nsRenderingContext::SetFont(nsFontMetric
     mFontMetrics = aFontMetrics;
 }
 
 PRInt32
 nsRenderingContext::GetMaxChunkLength()
 {
     if (!mFontMetrics)
         return 1;
-    return PR_MIN(mFontMetrics->GetMaxStringLength(), MAX_GFX_TEXT_BUF_SIZE);
+    return NS_MIN(mFontMetrics->GetMaxStringLength(), MAX_GFX_TEXT_BUF_SIZE);
 }
 
 nscoord
 nsRenderingContext::GetWidth(char aC)
 {
     if (aC == ' ' && mFontMetrics) {
         return mFontMetrics->SpaceWidth();
     }
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -49,16 +49,17 @@
 #include "nsILanguageAtomService.h"
 
 #include "gfxFont.h"
 #include "gfxPlatform.h"
 #include "gfxAtoms.h"
 
 #include "prtypes.h"
 #include "gfxTypes.h"
+#include "nsAlgorithm.h"
 #include "gfxContext.h"
 #include "gfxFontMissingGlyphs.h"
 #include "gfxUserFontSet.h"
 #include "gfxPlatformFontList.h"
 #include "gfxScriptItemizer.h"
 #include "gfxUnicodeProperties.h"
 #include "nsMathUtils.h"
 #include "nsBidiUtils.h"
@@ -1014,18 +1015,18 @@ gfxFontCache::DestroyFont(gfxFont *aFont
     NS_ASSERTION(aFont->GetRefCount() == 0,
                  "Destroying with non-zero ref count!");
     delete aFont;
 }
 
 void
 gfxFont::RunMetrics::CombineWith(const RunMetrics& aOther, PRBool aOtherIsOnLeft)
 {
-    mAscent = PR_MAX(mAscent, aOther.mAscent);
-    mDescent = PR_MAX(mDescent, aOther.mDescent);
+    mAscent = NS_MAX(mAscent, aOther.mAscent);
+    mDescent = NS_MAX(mDescent, aOther.mDescent);
     if (aOtherIsOnLeft) {
         mBoundingBox =
             (mBoundingBox + gfxPoint(aOther.mAdvanceWidth, 0)).Union(aOther.mBoundingBox);
     } else {
         mBoundingBox =
             mBoundingBox.Union(aOther.mBoundingBox + gfxPoint(mAdvanceWidth, 0));
     }
     mAdvanceWidth += aOther.mAdvanceWidth;
@@ -1256,18 +1257,18 @@ gfxFont::Draw(gfxTextRun *aTextRun, PRUi
     glyphs.Flush(cr, aDrawToPath, isRTL, PR_TRUE);
 
     *aPt = gfxPoint(x, y);
 }
 
 static void
 UnionRange(gfxFloat aX, gfxFloat* aDestMin, gfxFloat* aDestMax)
 {
-    *aDestMin = PR_MIN(*aDestMin, aX);
-    *aDestMax = PR_MAX(*aDestMax, aX);
+    *aDestMin = NS_MIN(*aDestMin, aX);
+    *aDestMax = NS_MAX(*aDestMax, aX);
 }
 
 // We get precise glyph extents if the textrun creator requested them, or
 // if the font is a user font --- in which case the author may be relying
 // on overflowing glyphs.
 static PRBool
 NeedsGlyphExtents(gfxFont *aFont, gfxTextRun *aTextRun)
 {
@@ -1676,18 +1677,18 @@ gfxFont::InitMetricsFromSfntTables(Metri
     if (NS_SUCCEEDED(mFontEntry->GetFontTable(kOS_2TableTag, os2data))) {
         OS2Table *os2 = reinterpret_cast<OS2Table*>(os2data.Elements());
 
         if (os2data.Length() >= offsetof(OS2Table, sxHeight) +
                                 sizeof(PRInt16) &&
             PRUint16(os2->version) >= 2) {
             // version 2 and later includes the x-height field
             SET_SIGNED(xHeight, os2->sxHeight);
-            // PR_ABS because of negative xHeight seen in Kokonor (Tibetan) font
-            aMetrics.xHeight = PR_ABS(aMetrics.xHeight);
+            // NS_ABS because of negative xHeight seen in Kokonor (Tibetan) font
+            aMetrics.xHeight = NS_ABS(aMetrics.xHeight);
         }
         // this should always be present
         if (os2data.Length() >= offsetof(OS2Table, yStrikeoutPosition) +
                                 sizeof(PRInt16)) {
             SET_SIGNED(aveCharWidth, os2->xAvgCharWidth);
             SET_SIGNED(subscriptOffset, os2->ySubscriptYOffset);
             SET_SIGNED(superscriptOffset, os2->ySuperscriptYOffset);
             SET_SIGNED(strikeoutSize, os2->yStrikeoutSize);
@@ -1772,20 +1773,20 @@ gfxFont::SanitizeMetrics(gfxFont::Metric
         aMetrics->superscriptOffset = aMetrics->xHeight;
     }
     // And also checking the case of sub script offset. The old gfx for win has checked this too.
     if (aMetrics->subscriptOffset <= 0 ||
         aMetrics->subscriptOffset >= aMetrics->maxAscent) {
         aMetrics->subscriptOffset = aMetrics->xHeight;
     }
 
-    aMetrics->underlineSize = PR_MAX(1.0, aMetrics->underlineSize);
-    aMetrics->strikeoutSize = PR_MAX(1.0, aMetrics->strikeoutSize);
-
-    aMetrics->underlineOffset = PR_MIN(aMetrics->underlineOffset, -1.0);
+    aMetrics->underlineSize = NS_MAX(1.0, aMetrics->underlineSize);
+    aMetrics->strikeoutSize = NS_MAX(1.0, aMetrics->strikeoutSize);
+
+    aMetrics->underlineOffset = NS_MIN(aMetrics->underlineOffset, -1.0);
 
     if (aMetrics->maxAscent < 1.0) {
         // We cannot draw strikeout line and overline in the ascent...
         aMetrics->underlineSize = 0;
         aMetrics->underlineOffset = 0;
         aMetrics->strikeoutSize = 0;
         aMetrics->strikeoutOffset = 0;
         return;
@@ -1797,46 +1798,46 @@ gfxFont::SanitizeMetrics(gfxFont::Metric
      * However, if this is system font, we should not do this for the rendering compatibility with
      * another application's UI on the platform.
      * XXX Should not use this hack if the font size is too small?
      *     Such text cannot be read, this might be used for tight CSS rendering? (E.g., Acid2)
      */
     if (!mStyle.systemFont && aIsBadUnderlineFont) {
         // First, we need 2 pixels between baseline and underline at least. Because many CJK characters
         // put their glyphs on the baseline, so, 1 pixel is too close for CJK characters.
-        aMetrics->underlineOffset = PR_MIN(aMetrics->underlineOffset, -2.0);
+        aMetrics->underlineOffset = NS_MIN(aMetrics->underlineOffset, -2.0);
 
         // Next, we put the underline to bottom of below of the descent space.
         if (aMetrics->internalLeading + aMetrics->externalLeading > aMetrics->underlineSize) {
-            aMetrics->underlineOffset = PR_MIN(aMetrics->underlineOffset, -aMetrics->emDescent);
+            aMetrics->underlineOffset = NS_MIN(aMetrics->underlineOffset, -aMetrics->emDescent);
         } else {
-            aMetrics->underlineOffset = PR_MIN(aMetrics->underlineOffset,
+            aMetrics->underlineOffset = NS_MIN(aMetrics->underlineOffset,
                                                aMetrics->underlineSize - aMetrics->emDescent);
         }
     }
     // If underline positioned is too far from the text, descent position is preferred so that underline
     // will stay within the boundary.
     else if (aMetrics->underlineSize - aMetrics->underlineOffset > aMetrics->maxDescent) {
         if (aMetrics->underlineSize > aMetrics->maxDescent)
-            aMetrics->underlineSize = PR_MAX(aMetrics->maxDescent, 1.0);
+            aMetrics->underlineSize = NS_MAX(aMetrics->maxDescent, 1.0);
         // The max underlineOffset is 1px (the min underlineSize is 1px, and min maxDescent is 0px.)
         aMetrics->underlineOffset = aMetrics->underlineSize - aMetrics->maxDescent;
     }
 
     // If strikeout line is overflowed from the ascent, the line should be resized and moved for
     // that being in the ascent space.
     // Note that the strikeoutOffset is *middle* of the strikeout line position.
     gfxFloat halfOfStrikeoutSize = NS_floor(aMetrics->strikeoutSize / 2.0 + 0.5);
     if (halfOfStrikeoutSize + aMetrics->strikeoutOffset > aMetrics->maxAscent) {
         if (aMetrics->strikeoutSize > aMetrics->maxAscent) {
-            aMetrics->strikeoutSize = PR_MAX(aMetrics->maxAscent, 1.0);
+            aMetrics->strikeoutSize = NS_MAX(aMetrics->maxAscent, 1.0);
             halfOfStrikeoutSize = NS_floor(aMetrics->strikeoutSize / 2.0 + 0.5);
         }
         gfxFloat ascent = NS_floor(aMetrics->maxAscent + 0.5);
-        aMetrics->strikeoutOffset = PR_MAX(halfOfStrikeoutSize, ascent / 2.0);
+        aMetrics->strikeoutOffset = NS_MAX(halfOfStrikeoutSize, ascent / 2.0);
     }
 
     // If overline is larger than the ascent, the line should be resized.
     if (aMetrics->underlineSize > aMetrics->maxAscent) {
         aMetrics->underlineSize = aMetrics->maxAscent;
     }
 }
 
@@ -2043,17 +2044,17 @@ gfxFontGroup::BuildFontList()
     }
 
     if (!mStyle.systemFont) {
         for (PRUint32 i = 0; i < mFonts.Length(); ++i) {
             gfxFont* font = mFonts[i];
             if (font->GetFontEntry()->mIsBadUnderlineFont) {
                 gfxFloat first = mFonts[0]->GetMetrics().underlineOffset;
                 gfxFloat bad = font->GetMetrics().underlineOffset;
-                mUnderlineOffset = PR_MIN(first, bad);
+                mUnderlineOffset = NS_MIN(first, bad);
                 break;
             }
         }
     }
 #endif
 }
 
 PRBool
@@ -2992,20 +2993,20 @@ gfxFontStyle::ComputeWeight() const
 PRBool
 gfxTextRun::GlyphRunIterator::NextRun()  {
     if (mNextIndex >= mTextRun->mGlyphRuns.Length())
         return PR_FALSE;
     mGlyphRun = &mTextRun->mGlyphRuns[mNextIndex];
     if (mGlyphRun->mCharacterOffset >= mEndOffset)
         return PR_FALSE;
 
-    mStringStart = PR_MAX(mStartOffset, mGlyphRun->mCharacterOffset);
+    mStringStart = NS_MAX(mStartOffset, mGlyphRun->mCharacterOffset);
     PRUint32 last = mNextIndex + 1 < mTextRun->mGlyphRuns.Length()
         ? mTextRun->mGlyphRuns[mNextIndex + 1].mCharacterOffset : mTextRun->mCharacterCount;
-    mStringEnd = PR_MIN(mEndOffset, last);
+    mStringEnd = NS_MIN(mEndOffset, last);
 
     ++mNextIndex;
     return PR_TRUE;
 }
 
 #ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
 static void
 AccountStorageForTextRun(gfxTextRun *aTextRun, PRInt32 aSign)
@@ -3020,17 +3021,17 @@ AccountStorageForTextRun(gfxTextRun *aTe
     PRInt32 bytes = length * sizeof(gfxTextRun::CompressedGlyph);
     if (aTextRun->GetFlags() & gfxTextRunFactory::TEXT_IS_PERSISTENT) {
       bytes += length * ((aTextRun->GetFlags() & gfxTextRunFactory::TEXT_IS_8BIT) ? 1 : 2);
       bytes += sizeof(gfxTextRun::CompressedGlyph) - 1;
       bytes &= ~(sizeof(gfxTextRun::CompressedGlyph) - 1);
     }
     bytes += sizeof(gfxTextRun);
     gTextRunStorage += bytes*aSign;
-    gTextRunStorageHighWaterMark = PR_MAX(gTextRunStorageHighWaterMark, gTextRunStorage);
+    gTextRunStorageHighWaterMark = NS_MAX(gTextRunStorageHighWaterMark, gTextRunStorage);
 }
 #endif
 
 // Helper for textRun creation to preallocate storage for glyphs and text;
 // this function returns a pointer to the newly-allocated glyph storage,
 // AND modifies the aText parameter if TEXT_IS_PERSISTENT was not set.
 // In that case, the text is appended to the glyph storage, so a single
 // delete[] operation in the textRun destructor will free both.
@@ -3350,27 +3351,27 @@ gfxTextRun::DrawGlyphs(gfxFont *aFont, g
 }
 
 static void
 ClipPartialLigature(gfxTextRun *aTextRun, gfxFloat *aLeft, gfxFloat *aRight,
                     gfxFloat aXOrigin, gfxTextRun::LigatureData *aLigature)
 {
     if (aLigature->mClipBeforePart) {
         if (aTextRun->IsRightToLeft()) {
-            *aRight = PR_MIN(*aRight, aXOrigin);
+            *aRight = NS_MIN(*aRight, aXOrigin);
         } else {
-            *aLeft = PR_MAX(*aLeft, aXOrigin);
+            *aLeft = NS_MAX(*aLeft, aXOrigin);
         }
     }
     if (aLigature->mClipAfterPart) {
         gfxFloat endEdge = aXOrigin + aTextRun->GetDirection()*aLigature->mPartWidth;
         if (aTextRun->IsRightToLeft()) {
-            *aLeft = PR_MAX(*aLeft, endEdge);
+            *aLeft = NS_MAX(*aLeft, endEdge);
         } else {
-            *aRight = PR_MIN(*aRight, endEdge);
+            *aRight = NS_MIN(*aRight, endEdge);
         }
     }    
 }
 
 void
 gfxTextRun::DrawPartialLigature(gfxFont *aFont, gfxContext *aCtx,
                                 PRUint32 aStart, PRUint32 aEnd,
                                 gfxPoint *aPt,
@@ -3727,22 +3728,22 @@ gfxTextRun::BreakAndMeasureText(PRUint32
                                 Metrics *aMetrics,
                                 gfxFont::BoundingBoxType aBoundingBoxType,
                                 gfxContext *aRefContext,
                                 PRBool *aUsedHyphenation,
                                 PRUint32 *aLastBreak,
                                 PRBool aCanWordWrap,
                                 gfxBreakPriority *aBreakPriority)
 {
-    aMaxLength = PR_MIN(aMaxLength, mCharacterCount - aStart);
+    aMaxLength = NS_MIN(aMaxLength, mCharacterCount - aStart);
 
     NS_ASSERTION(aStart + aMaxLength <= mCharacterCount, "Substring out of range");
 
     PRUint32 bufferStart = aStart;
-    PRUint32 bufferLength = PR_MIN(aMaxLength, MEASUREMENT_BUFFER_SIZE);
+    PRUint32 bufferLength = NS_MIN<PRUint32>(aMaxLength, MEASUREMENT_BUFFER_SIZE);
     PropertyProvider::Spacing spacingBuffer[MEASUREMENT_BUFFER_SIZE];
     PRBool haveSpacing = aProvider && (mFlags & gfxTextRunFactory::TEXT_ENABLE_SPACING) != 0;
     if (haveSpacing) {
         GetAdjustedSpacing(this, bufferStart, bufferStart + bufferLength, aProvider,
                            spacingBuffer);
     }
     PRPackedBool hyphenBuffer[MEASUREMENT_BUFFER_SIZE];
     PRBool haveHyphenation = aProvider &&
@@ -3771,17 +3772,17 @@ gfxTextRun::BreakAndMeasureText(PRUint32
     PRUint32 ligatureRunEnd = end;
     ShrinkToLigatureBoundaries(&ligatureRunStart, &ligatureRunEnd);
 
     PRUint32 i;
     for (i = aStart; i < end; ++i) {
         if (i >= bufferStart + bufferLength) {
             // Fetch more spacing and hyphenation data
             bufferStart = i;
-            bufferLength = PR_MIN(aStart + aMaxLength, i + MEASUREMENT_BUFFER_SIZE) - i;
+            bufferLength = NS_MIN(aStart + aMaxLength, i + MEASUREMENT_BUFFER_SIZE) - i;
             if (haveSpacing) {
                 GetAdjustedSpacing(this, bufferStart, bufferStart + bufferLength, aProvider,
                                    spacingBuffer);
             }
             if (haveHyphenation) {
                 aProvider->GetHyphenationBreaks(bufferStart, bufferLength,
                                                 hyphenBuffer);
             }
@@ -4132,17 +4133,17 @@ gfxTextRun::SetMissingGlyph(PRUint32 aIn
         return;
 
     details->mGlyphID = aChar;
     GlyphRun *glyphRun = &mGlyphRuns[FindFirstGlyphRunContaining(aIndex)];
     if (IsDefaultIgnorable(aChar)) {
         // Setting advance width to zero will prevent drawing the hexbox
         details->mAdvance = 0;
     } else {
-        gfxFloat width = PR_MAX(glyphRun->mFont->GetMetrics().aveCharWidth,
+        gfxFloat width = NS_MAX(glyphRun->mFont->GetMetrics().aveCharWidth,
                                 gfxFontMissingGlyphs::GetDesiredMinWidth(aChar));
         details->mAdvance = PRUint32(width*GetAppUnitsPerDevUnit());
     }
     details->mXOffset = 0;
     details->mYOffset = 0;
     mCharacterGlyphs[aIndex].SetMissing(1);
 }
 
--- a/gfx/thebes/gfxFont.h
+++ b/gfx/thebes/gfxFont.h
@@ -37,16 +37,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef GFX_FONT_H
 #define GFX_FONT_H
 
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "gfxTypes.h"
 #include "nsString.h"
 #include "gfxPoint.h"
 #include "gfxFontUtils.h"
 #include "nsTArray.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
 #include "gfxSkipChars.h"
@@ -162,18 +163,18 @@ struct THEBES_API gfxFontStyle {
 
     // custom opentype feature settings
     nsTArray<gfxFontFeature> featureSettings;
 
     // Return the final adjusted font size for the given aspect ratio.
     // Not meant to be called when sizeAdjust = 0.
     gfxFloat GetAdjustedSize(gfxFloat aspect) const {
         NS_ASSERTION(sizeAdjust != 0.0, "Not meant to be called when sizeAdjust = 0");
-        gfxFloat adjustedSize = PR_MAX(NS_round(size*(sizeAdjust/aspect)), 1.0);
-        return PR_MIN(adjustedSize, FONT_MAX_SIZE);
+        gfxFloat adjustedSize = NS_MAX(NS_round(size*(sizeAdjust/aspect)), 1.0);
+        return NS_MIN(adjustedSize, FONT_MAX_SIZE);
     }
 
     PLDHashNumber Hash() const {
         return ((style + (systemFont << 7) +
             (weight << 8)) + PRUint32(size*1000) + PRUint32(sizeAdjust*1000)) ^
             nsISupportsHashKey::HashKey(language);
     }
 
--- a/gfx/thebes/gfxMacPlatformFontList.mm
+++ b/gfx/thebes/gfxMacPlatformFontList.mm
@@ -816,17 +816,17 @@ gfxMacPlatformFontList::GetStandardFamil
 
     // Gecko 1.8 used Quickdraw font api's which produce a slightly different set of "family"
     // names.  Try to resolve based on these names, in case this is stored in an old profile
     // 1.8: "Futura", "Futura Condensed" ==> 1.9: "Futura"
 
     // convert the name to a Pascal-style Str255 to try as Quickdraw name
     Str255 qdname;
     NS_ConvertUTF16toUTF8 utf8name(aFontName);
-    qdname[0] = PR_MAX(255, strlen(utf8name.get()));
+    qdname[0] = NS_MAX<size_t>(255, strlen(utf8name.get()));
     memcpy(&qdname[1], utf8name.get(), qdname[0]);
 
     // look up the Quickdraw name
     ATSFontFamilyRef atsFamily = ::ATSFontFamilyFindFromQuickDrawName(qdname);
     if (atsFamily == (ATSFontFamilyRef)kInvalidFontFamily) {
         return PR_FALSE;
     }
 
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -1120,18 +1120,18 @@ nsCSSRendering::PaintBoxShadowOuter(nsPr
     // XXX this may not be a safe assumption; we should make this go away
     // by optimizing box-shadow drawing more for the cases where we don't have a skip-rect.
     useSkipGfxRect = !aForFrame->IsLeaf();
     nsRect paddingRect =
       aForFrame->GetPaddingRect() - aForFrame->GetPosition() + aFrameArea.TopLeft();
     skipGfxRect = nsLayoutUtils::RectToGfxRect(paddingRect, twipsPerPixel);
   } else if (hasBorderRadius) {
     skipGfxRect.Deflate(gfxMargin(
-        0, PR_MAX(borderRadii[C_TL].height, borderRadii[C_TR].height),
-        0, PR_MAX(borderRadii[C_BL].height, borderRadii[C_BR].height)));
+        0, NS_MAX(borderRadii[C_TL].height, borderRadii[C_TR].height),
+        0, NS_MAX(borderRadii[C_BL].height, borderRadii[C_BR].height)));
   }
 
   for (PRUint32 i = shadows->Length(); i > 0; --i) {
     nsCSSShadowItem* shadowItem = shadows->ShadowAt(i - 1);
     if (shadowItem->mInset)
       continue;
 
     nsRect shadowRect = frameRect;
@@ -1357,18 +1357,18 @@ nsCSSRendering::PaintBoxShadowInner(nsPr
 
     // Set the "skip rect" to the area within the frame that we don't paint in,
     // including after blurring.
     nsRect skipRect = shadowClipRect;
     skipRect.Deflate(blurMargin);
     gfxRect skipGfxRect = nsLayoutUtils::RectToGfxRect(skipRect, twipsPerPixel);
     if (hasBorderRadius) {
       skipGfxRect.Deflate(
-          gfxMargin(0, PR_MAX(clipRectRadii[C_TL].height, clipRectRadii[C_TR].height),
-                    0, PR_MAX(clipRectRadii[C_BL].height, clipRectRadii[C_BR].height)));
+          gfxMargin(0, NS_MAX(clipRectRadii[C_TL].height, clipRectRadii[C_TR].height),
+                    0, NS_MAX(clipRectRadii[C_BL].height, clipRectRadii[C_BR].height)));
     }
 
     // When there's a blur radius, gfxAlphaBoxBlur leaves the skiprect area
     // unchanged. And by construction the gfxSkipRect is not touched by the
     // rendered shadow (even after blurring), so those pixels must be completely
     // transparent in the shadow, so drawing them changes nothing.
     gfxContext* renderContext = aRenderingContext.ThebesContext();
     nsRefPtr<gfxContext> shadowContext;
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -51,16 +51,17 @@
  * identified per MPL Section 3.3
  *
  * Date         Modified by     Description of modification
  * 05/03/2000   IBM Corp.       Observer events for reflow states
  */
 
 /* a presentation of a document, part 2 */
 
+#include "nsAlgorithm.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIContent.h"
 #include "mozilla/dom/Element.h"
 #include "nsIDocument.h"
 #include "nsIDOMXULDocument.h"
 #include "nsStubDocumentObserver.h"
 #include "nsStyleSet.h"
@@ -618,17 +619,17 @@ StackArena::Push()
 
 void*
 StackArena::Allocate(size_t aSize)
 {
   NS_ASSERTION(mStackTop > 0, "Allocate called without Push");
 
   // make sure we are aligned. Beard said 8 was safer then 4. 
   // Round size to multiple of 8
-  aSize = PR_ROUNDUP(aSize, 8);
+  aSize = NS_ROUNDUP<size_t>(aSize, 8);
 
   // if the size makes the stack overflow. Grab another block for the stack
   if (mPos + aSize >= BLOCK_INCREMENT)
   {
     NS_ASSERTION(aSize <= BLOCK_INCREMENT,"Requested memory is greater that our block size!!");
     if (mCurBlock->mNext == nsnull)
       mCurBlock->mNext = new StackBlock();
 
--- a/layout/generic/nsGfxScrollFrame.cpp
+++ b/layout/generic/nsGfxScrollFrame.cpp
@@ -2194,18 +2194,18 @@ nsGfxScrollFrameInner::ScrollBy(nsIntPoi
   nsPoint newPos = mDestination +
     nsPoint(aDelta.x*deltaMultiplier.width, aDelta.y*deltaMultiplier.height);
   ScrollTo(newPos, aMode);
 
   if (aOverflow) {
     nsPoint clampAmount = mDestination - newPos;
     float appUnitsPerDevPixel = mOuter->PresContext()->AppUnitsPerDevPixel();
     *aOverflow = nsIntPoint(
-        NSAppUnitsToIntPixels(PR_ABS(clampAmount.x), appUnitsPerDevPixel),
-        NSAppUnitsToIntPixels(PR_ABS(clampAmount.y), appUnitsPerDevPixel));
+        NSAppUnitsToIntPixels(NS_ABS(clampAmount.x), appUnitsPerDevPixel),
+        NSAppUnitsToIntPixels(NS_ABS(clampAmount.y), appUnitsPerDevPixel));
   }
 }
 
 nsSize
 nsGfxScrollFrameInner::GetLineScrollAmount() const
 {
   const nsStyleFont* font = mOuter->GetStyleFont();
   const nsFont& f = font->mFont;
--- a/layout/generic/nsTextFrameThebes.cpp
+++ b/layout/generic/nsTextFrameThebes.cpp
@@ -2797,17 +2797,17 @@ PropertyProvider::CalcTabWidths(PRUint32
       }
 #endif
       return;
     }
   }
 
   PRUint32 startOffset = mStart.GetSkippedOffset();
   PRUint32 tabsEnd = mTabWidths ?
-    mTabWidths->mLimit : PR_MAX(mTabWidthsAnalyzedLimit, startOffset);
+    mTabWidths->mLimit : NS_MAX(mTabWidthsAnalyzedLimit, startOffset);
 
   if (tabsEnd < aStart + aLength) {
     NS_ASSERTION(mReflowing,
                  "We need precomputed tab widths, but don't have enough.");
 
     gfxFloat tabWidth = -1;
     for (PRUint32 i = tabsEnd; i < aStart + aLength; ++i) {
       Spacing spacing;
@@ -2842,17 +2842,17 @@ PropertyProvider::CalcTabWidths(PRUint32
     if (mTabWidths) {
       mTabWidths->mLimit = aStart + aLength;
     }
   }
 
   if (!mTabWidths) {
     // Delete any stale property that may be left on the frame
     mFrame->Properties().Delete(TabWidthProperty());
-    mTabWidthsAnalyzedLimit = PR_MAX(mTabWidthsAnalyzedLimit,
+    mTabWidthsAnalyzedLimit = NS_MAX(mTabWidthsAnalyzedLimit,
                                      aStart + aLength);
   }
 }
 
 gfxFloat
 PropertyProvider::GetHyphenWidth()
 {
   if (mHyphenWidth < 0) {
@@ -4996,17 +4996,17 @@ nsTextFrame::PaintTextSelectionDecoratio
   nsTextRangeStyle selectedStyle;
   while (iterator.GetNextSegment(&xOffset, &offset, &length, &hyphenWidth,
                                  &type, &selectedStyle)) {
     gfxFloat advance = hyphenWidth +
       mTextRun->GetAdvanceWidth(offset, length, &aProvider);
     if (type == aSelectionType) {
       pt.x = (aFramePt.x + xOffset -
              (mTextRun->IsRightToLeft() ? advance : 0)) / app;
-      gfxFloat width = PR_ABS(advance) / app;
+      gfxFloat width = NS_ABS(advance) / app;
       DrawSelectionDecorations(aCtx, aSelectionType, this, aTextPaintStyle,
                                selectedStyle,
                                pt, width, mAscent / app, decorationMetrics);
     }
     iterator.UpdateWithAdvance(advance);
   }
 }
 
@@ -6204,17 +6204,17 @@ nsTextFrame::AddInlineMinWidthForFlow(ns
   // otherwise we can just pass PR_INT32_MAX to mean "all the text"
   PRInt32 len = PR_INT32_MAX;
   PRBool hyphenating = frag->GetLength() > 0 &&
     (textStyle->mHyphens == NS_STYLE_HYPHENS_AUTO ||
      (textStyle->mHyphens == NS_STYLE_HYPHENS_MANUAL &&
       (mTextRun->GetFlags() & gfxTextRunFactory::TEXT_ENABLE_HYPHEN_BREAKS) != 0));
   if (hyphenating) {
     gfxSkipCharsIterator tmp(iter);
-    len = PR_MIN(GetContentOffset() + GetInFlowContentLength(),
+    len = NS_MIN<PRInt32>(GetContentOffset() + GetInFlowContentLength(),
                  tmp.ConvertSkippedToOriginal(flowEndInTextRun)) - iter.GetOriginalOffset();
   }
   PropertyProvider provider(mTextRun, textStyle, frag, this,
                             iter, len, nsnull, 0);
 
   PRBool collapseWhitespace = !textStyle->WhiteSpaceIsSignificant();
   PRBool preformatNewlines = textStyle->NewlineIsSignificant();
   PRBool preformatTabs = textStyle->WhiteSpaceIsSignificant();
--- a/netwerk/base/src/nsUnicharStreamLoader.cpp
+++ b/netwerk/base/src/nsUnicharStreamLoader.cpp
@@ -251,17 +251,17 @@ nsUnicharStreamLoader::WriteSegmentFun(n
     if (NS_FAILED(rv)) {
       NS_ASSERTION(0 < capacity - haveRead,
                    "Decoder returned an error but filled the output buffer! "
                    "Should not happen.");
       self->mBuffer.BeginWriting()[haveRead++] = 0xFFFD;
       ++consumed;
       // XXX this is needed to make sure we don't underrun our buffer;
       // bug 160784 again
-      consumed = PR_MAX(consumed, 0);
+      consumed = NS_MAX<PRUint32>(consumed, 0);
       self->mDecoder->Reset();
     }
   } while (consumed < aCount);
 
   self->mBuffer.SetLength(haveRead);
   *aWriteCount = aCount;
   return NS_OK;
 }
--- a/netwerk/cache/nsDiskCacheStreams.cpp
+++ b/netwerk/cache/nsDiskCacheStreams.cpp
@@ -751,17 +751,17 @@ nsDiskCacheStreamIO::FlushBufferToFile()
         record->SetDataFileGeneration(mBinding->mGeneration);
         
         // allocate file
         rv = OpenCacheFile(PR_RDWR | PR_CREATE_FILE, &mFD);
         if (NS_FAILED(rv))  return rv;
 
         PRInt64 dataSize = mBinding->mCacheEntry->PredictedDataSize();
         if (dataSize != -1)
-            mozilla::fallocate(mFD, PR_MIN(dataSize, kPreallocateLimit));
+            mozilla::fallocate(mFD, NS_MIN<PRInt64>(dataSize, kPreallocateLimit));
     }
     
     // write buffer
     PRInt32 bytesWritten = PR_Write(mFD, mBuffer, mBufEnd);
     if (PRUint32(bytesWritten) != mBufEnd) {
         NS_WARNING("failed to flush all data");
         return NS_ERROR_UNEXPECTED;     // NS_ErrorAccordingToNSPR()
     }
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -1085,18 +1085,17 @@ nsHttpTransaction::HandleContent(char *b
     }
     else if (mContentLength >= PRInt64(0)) {
         // HTTP/1.0 servers have been known to send erroneous Content-Length
         // headers. So, unless the connection is persistent, we must make
         // allowances for a possibly invalid Content-Length header. Thus, if
         // NOT persistent, we simply accept everything in |buf|.
         if (mConnection->IsPersistent() || mPreserveStream) {
             PRInt64 remaining = mContentLength - mContentRead;
-            PRInt64 count64 = count;
-            *contentRead = PR_MIN(count64, remaining);
+            *contentRead = PRUint32(NS_MIN<PRInt64>(count, remaining));
             *contentRemaining = count - *contentRead;
         }
         else {
             *contentRead = count;
             // mContentLength might need to be increased...
             PRInt64 position = mContentRead + PRInt64(count);
             if (position > mContentLength) {
                 mContentLength = position;
@@ -1108,17 +1107,17 @@ nsHttpTransaction::HandleContent(char *b
         // when we are just waiting for the server to close the connection...
         // (no explicit content-length given)
         *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...
+        /* when uncommenting, take care of 64-bit integers w/ NS_MAX...
         if (mProgressSink)
             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));
 
--- a/netwerk/test/TestHttp.cpp
+++ b/netwerk/test/TestHttp.cpp
@@ -59,17 +59,17 @@ MyListener::OnDataAvailable(nsIRequest *
 {
     printf(">>> OnDataAvailable [count=%u]\n", count);
 
     char buf[256];
     nsresult rv;
     PRUint32 bytesRead=0;
 
     while (count) {
-        PRUint32 amount = PR_MIN(count, sizeof(buf));
+        PRUint32 amount = NS_MIN<PRUint32>(count, sizeof(buf));
 
         rv = stream->Read(buf, amount, &bytesRead);
         if (NS_FAILED(rv)) {
             printf(">>> stream->Read failed with rv=%x\n", rv);
             return rv;
         }
 
         fwrite(buf, 1, bytesRead, stdout);
--- a/netwerk/test/TestMCTransport.cpp
+++ b/netwerk/test/TestMCTransport.cpp
@@ -132,17 +132,17 @@ TestListener::OnDataAvailable(nsIRequest
 
     if (!mFile) return NS_ERROR_FAILURE;
 
     char buf[128];
     nsresult rv;
     PRUint32 nread = 0;
 
     while (count) {
-        PRUint32 amount = PR_MIN(count, sizeof(buf));
+        PRUint32 amount = NS_MIN<PRUint32>(count, sizeof(buf));
 
         rv = is->Read(buf, amount, &nread);
         if (NS_FAILED(rv)) return rv;
 
         fwrite(buf, nread, 1, mFile);
         count -= nread;
     }
     return NS_OK;
--- a/netwerk/test/TestOverlappedIO.cpp
+++ b/netwerk/test/TestOverlappedIO.cpp
@@ -195,17 +195,17 @@ TestProvider::OnDataWritable(nsIRequest 
 {
     LOG(("TestProvider::OnDataWritable [offset=%u, count=%u]\n", offset, count));
 
     // Stop at 5 requests
     if (mRequestCount == 5)
         return NS_BASE_STREAM_CLOSED;
 
     PRUint32 writeCount, amount;
-    amount = PR_MIN(count, mDataLen - mOffset);
+    amount = NS_MIN(count, mDataLen - mOffset);
     nsresult rv = output->Write(mData + mOffset, amount, &writeCount);
     if (NS_SUCCEEDED(rv)) {
         printf("wrote %u bytes\n", writeCount);
         mOffset += writeCount;
         if (mOffset == mDataLen) {
             printf("done sending packet %u\n", mRequestCount);
             mOffset = 0;
             mRequestCount++;
--- a/netwerk/test/TestPageLoad.cpp
+++ b/netwerk/test/TestPageLoad.cpp
@@ -200,17 +200,17 @@ MyListener::OnDataAvailable(nsIRequest *
     PRUint32 bytesRead=0;
     char buf[1024];
 
     if(ctxt == nsnull) {
       bytesRead=0;
       rv = stream->ReadSegments(streamParse, &offset, count, &bytesRead);
     } else {
       while (count) {
-        PRUint32 amount = PR_MIN(count, sizeof(buf));
+        PRUint32 amount = NS_MIN<PRUint32>(count, sizeof(buf));
         rv = stream->Read(buf, amount, &bytesRead);  
         count -= bytesRead;
       }
     }
 
     if (NS_FAILED(rv)) {
       printf(">>> stream->Read failed with rv=%x\n", rv);
       return rv;
--- a/netwerk/test/TestPerf.cpp
+++ b/netwerk/test/TestPerf.cpp
@@ -78,17 +78,17 @@ NS_IMETHODIMP
 MyListener::OnDataAvailable(nsIRequest *req, nsISupports *ctx,
                             nsIInputStream *stream,
                             PRUint32 offset, PRUint32 count)
 {
     nsresult rv;
     char buf[4096];
     PRUint32 n, bytesRead;
     while (count) {
-        n = PR_MIN(count, sizeof(buf));
+        n = NS_MIN<PRUint32>(count, sizeof(buf));
         rv = stream->Read(buf, n, &bytesRead);
         if (NS_FAILED(rv))
             break;
         count -= bytesRead;
         if (bytesRead == 0)
             break;
     }
     return NS_OK;
--- a/netwerk/test/TestProtocols.cpp
+++ b/netwerk/test/TestProtocols.cpp
@@ -512,17 +512,17 @@ InputTestConsumer::OnDataAvailable(nsIRe
                                    PRUint32 aLength)
 {
   char buf[1025];
   PRUint32 amt, size;
   nsresult rv;
   URLLoadInfo* info = (URLLoadInfo*)context;
 
   while (aLength) {
-    size = PR_MIN(aLength, sizeof(buf));
+    size = NS_MIN<PRUint32>(aLength, sizeof(buf));
 
     rv = aIStream->Read(buf, size, &amt);
     if (NS_FAILED(rv)) {
       NS_ASSERTION((NS_BASE_STREAM_WOULD_BLOCK != rv), 
                    "The stream should never block.");
       return rv;
     }
     if (gVerbose) {
--- a/netwerk/test/TestStreamChannel.cpp
+++ b/netwerk/test/TestStreamChannel.cpp
@@ -93,17 +93,17 @@ public:
                                PRUint32 offset, PRUint32 count)
     {
         LOG(("MyListener::OnDataAvailable [offset=%u count=%u]\n", offset, count));
 
         char buf[500];
         nsresult rv;
 
         while (count) {
-            PRUint32 n, amt = PR_MIN(count, sizeof(buf));
+            PRUint32 n, amt = NS_MIN<PRUint32>(count, sizeof(buf));
 
             rv = stream->Read(buf, amt, &n);
             if (NS_FAILED(rv)) {
                 LOG(("  read returned 0x%08x\n", rv));
                 return rv;
             }
 
             LOG(("  read %u bytes\n", n));
--- a/netwerk/test/TestStreamPump.cpp
+++ b/netwerk/test/TestStreamPump.cpp
@@ -91,17 +91,17 @@ public:
                                PRUint32 offset, PRUint32 count)
     {
         LOG(("MyListener::OnDataAvailable [offset=%u count=%u]\n", offset, count));
 
         char buf[500];
         nsresult rv;
 
         while (count) {
-            PRUint32 n, amt = PR_MIN(count, sizeof(buf));
+            PRUint32 n, amt = NS_MIN<PRUint32>(count, sizeof(buf));
 
             rv = stream->Read(buf, amt, &n);
             if (NS_FAILED(rv)) {
                 LOG(("  read returned 0x%08x\n", rv));
                 return rv;
             }
 
             fwrite(buf, n, 1, stdout);
--- a/netwerk/test/TestThreadedIO.cpp
+++ b/netwerk/test/TestThreadedIO.cpp
@@ -170,17 +170,17 @@ TestListener::OnDataAvailable( nsIChanne
     // Write the data to the console.
     // Read a buffer full till aLength bytes have been processed.
     char buffer[ 8192 ];
     unsigned long bytesRemaining = aLength;
     while ( bytesRemaining ) {
         unsigned int bytesRead;
         // Read a buffer full or the number remaining (whichever is smaller).
         rv = aStream->Read( buffer,
-                            PR_MIN( sizeof( buffer ), bytesRemaining ),
+                            NS_MIN( sizeof( buffer ), bytesRemaining ),
                             &bytesRead );
         if ( NS_SUCCEEDED( rv ) ) {
             // Write the bytes just read to the output file.
             fwrite( buffer, 1, bytesRead, mFile );
             bytesRemaining -= bytesRead;
         } else {
             printf( "%s %d: Read error, rv=0x%08X\n",
                     (char*)__FILE__, (int)__LINE__, (int)rv );
--- a/netwerk/test/TestUpload.cpp
+++ b/netwerk/test/TestUpload.cpp
@@ -100,17 +100,17 @@ InputTestConsumer::OnDataAvailable(nsIRe
                                    PRUint32 aSourceOffset,
                                    PRUint32 aLength)
 {
   char buf[1025];
   PRUint32 amt, size;
   nsresult rv;
 
   while (aLength) {
-    size = PR_MIN(aLength, sizeof(buf));
+    size = NS_MIN<PRUint32>(aLength, sizeof(buf));
     rv = aIStream->Read(buf, size, &amt);
     if (NS_FAILED(rv)) {
       NS_ASSERTION((NS_BASE_STREAM_WOULD_BLOCK != rv), 
                    "The stream should never block.");
       return rv;
     }
     aLength -= amt;
   }
--- a/testing/mochitest/ssltunnel/Makefile.in
+++ b/testing/mochitest/ssltunnel/Makefile.in
@@ -51,13 +51,14 @@ PROGRAM = ssltunnel$(BIN_SUFFIX)
 
 CPPSRCS = ssltunnel.cpp
 
 # Use local includes because they are inserted before INCLUDES
 # so that Mozilla's nss.h is used, not glibc's
 LOCAL_INCLUDES += $(NSPR_CFLAGS) $(NSS_CFLAGS)
 
 LIBS = \
-	$(NSPR_LIBS) \
-	$(NSS_LIBS) \
-	$(NULL)
+  $(NSPR_LIBS) \
+  $(NSS_LIBS) \
+  $(MOZALLOC_LIB) \
+  $(NULL)
 
 include $(topsrcdir)/config/rules.mk
--- a/testing/mochitest/ssltunnel/ssltunnel.cpp
+++ b/testing/mochitest/ssltunnel/ssltunnel.cpp
@@ -54,16 +54,17 @@
 #include <stdarg.h>
 #include "prinit.h"
 #include "prerror.h"
 #include "prenv.h"
 #include "prio.h"
 #include "prnetdb.h"
 #include "prtpool.h"
 #include "prtypes.h"
+#include "nsAlgorithm.h"
 #include "nss.h"
 #include "pk11func.h"
 #include "key.h"
 #include "keyt.h"
 #include "ssl.h"
 #include "plhash.h"
 
 using std::string;
@@ -226,18 +227,18 @@ struct relayBuffer
   }
 
   void compact() {
     if (buffertail == bufferhead)
       buffertail = bufferhead = buffer;
   }
 
   bool empty() { return bufferhead == buffertail; }
-  size_t free() { return bufferend - buffertail; }
-  size_t margin() { return free() + BUF_MARGIN; }
+  size_t areafree() { return bufferend - buffertail; }
+  size_t margin() { return areafree() + BUF_MARGIN; }
   size_t present() { return buffertail - bufferhead; }
 };
 
 // A couple of stack classes for managing NSS/NSPR resources
 class AutoCert {
 public:
   AutoCert(CERTCertificate* cert) { cert_ = cert; }
   ~AutoCert() { if (cert_) CERT_DestroyCertificate(cert_); }
@@ -688,27 +689,27 @@ void HandleConnection(void* data)
           socketErrorState[s] = PR_TRUE;
           // We got a fatal error state on the socket. Clear the output buffer
           // for this socket to break the main loop, we will never more be able
           // to send those data anyway.
           buffers[s2].bufferhead = buffers[s2].buffertail = buffers[s2].buffer;
           continue;
         } // PR_POLL_EXCEPT, PR_POLL_ERR, PR_POLL_HUP handling
 
-        if (out_flags & PR_POLL_READ && !buffers[s].free())
+        if (out_flags & PR_POLL_READ && !buffers[s].areafree())
         {
            LOG_DEBUG((" no place in read buffer but got read flag, dropping it now!"));
            in_flags &= ~PR_POLL_READ;
         }
 
-        if (out_flags & PR_POLL_READ && buffers[s].free())
+        if (out_flags & PR_POLL_READ && buffers[s].areafree())
         {
           LOG_DEBUG((" :reading"));
           PRInt32 bytesRead = PR_Recv(sockets[s].fd, buffers[s].buffertail, 
-              buffers[s].free(), 0, PR_INTERVAL_NO_TIMEOUT);
+              buffers[s].areafree(), 0, PR_INTERVAL_NO_TIMEOUT);
 
           if (bytesRead == 0)
           {
             LOG_DEBUG((" socket gracefully closed"));
             client_done = true;
             in_flags &= ~PR_POLL_READ;
           }
           else if (bytesRead < 0)
@@ -783,17 +784,17 @@ void HandleConnection(void* data)
               strcpy(buffers[s2].buffer, "HTTP/1.1 200 Connected\r\nConnection: keep-alive\r\n\r\n");
               buffers[s2].buffertail = buffers[s2].buffer + strlen(buffers[s2].buffer);
 
               LOG_DEBUG((" accepted CONNECT request, connected to the server, sending OK to the client\n"));
               // Send the response to the client socket
               break;
             } // end of CONNECT handling
 
-            if (!buffers[s].free())
+            if (!buffers[s].areafree())
             {
               // Do not poll for read when the buffer is full
               LOG_DEBUG((" no place in our read buffer, stop reading"));
               in_flags &= ~PR_POLL_READ;
             }
 
             if (ssl_updated)
             {
@@ -1278,18 +1279,18 @@ int main(int argc, char** argv)
       "       # Proxy WebSocket traffic to the server at 127.0.0.1:9999,\n"
       "       # instead of the server specified in the 'forward' option.\n"
       "       websocketserver:127.0.0.1:9999\n",
       configFilePath));
     return 1;
   }
 
   // create a thread pool to handle connections
-  threads = PR_CreateThreadPool(PR_MAX(INITIAL_THREADS, servers.size()*2),
-                                PR_MAX(MAX_THREADS, servers.size()*2),
+  threads = PR_CreateThreadPool(NS_MAX<PRInt32>(INITIAL_THREADS, servers.size()*2),
+                                NS_MAX<PRInt32>(MAX_THREADS, servers.size()*2),
                                 DEFAULT_STACKSIZE);
   if (!threads) {
     LOG_ERROR(("Failed to create thread pool\n"));
     return 1;
   }
 
   shutdown_lock = PR_NewLock();
   if (!shutdown_lock) {
--- a/widget/src/cocoa/GfxInfo.mm
+++ b/widget/src/cocoa/GfxInfo.mm
@@ -62,17 +62,17 @@ GfxInfo::Init()
   CGLRendererInfoObj renderer = 0;
   GLint rendererCount = 0;
 
   memset(mRendererIDs, 0, sizeof(mRendererIDs));
 
   if (CGLQueryRendererInfo(0xffffffff, &renderer, &rendererCount) != kCGLNoError)
     return rv;
 
-  rendererCount = (GLint) PR_MIN(rendererCount, (GLint) NS_ARRAY_LENGTH(mRendererIDs));
+  rendererCount = (GLint) NS_MIN(rendererCount, (GLint) NS_ARRAY_LENGTH(mRendererIDs));
   for (GLint i = 0; i < rendererCount; i++) {
     GLint prop = 0;
 
     if (!mRendererIDsString.IsEmpty())
       mRendererIDsString.AppendLiteral(",");
     if (CGLDescribeRenderer(renderer, i, kCGLRPRendererID, &prop) == kCGLNoError) {
 #ifdef kCGLRendererIDMatchingMask
       prop = prop & kCGLRendererIDMatchingMask;
--- a/widget/src/cocoa/nsNativeThemeCocoa.mm
+++ b/widget/src/cocoa/nsNativeThemeCocoa.mm
@@ -723,17 +723,17 @@ nsNativeThemeCocoa::DrawCheckboxOrRadio(
 
   [cell setEnabled:!IsDisabled(aFrame, inState)];
   [cell setShowsFirstResponder:inState.HasState(NS_EVENT_STATE_FOCUS)];
   [cell setState:state];
   [cell setHighlighted:inState.HasAllStates(NS_EVENT_STATE_ACTIVE | NS_EVENT_STATE_HOVER)];
   [cell setControlTint:(FrameIsInActiveWindow(aFrame) ? [NSColor currentControlTint] : NSClearControlTint)];
 
   // Ensure that the control is square.
-  float length = PR_MIN(inBoxRect.size.width, inBoxRect.size.height);
+  float length = NS_MIN(inBoxRect.size.width, inBoxRect.size.height);
   HIRect drawRect = CGRectMake(inBoxRect.origin.x + (int)((inBoxRect.size.width - length) / 2.0f),
                                inBoxRect.origin.y + (int)((inBoxRect.size.height - length) / 2.0f),
                                length, length);
 
   DrawCellWithSnapping(cell, cgContext, drawRect,
                        inCheckbox ? checkboxSettings : radioSettings,
                        VerticalAlignFactor(aFrame), mCellDrawView, NO);
 
@@ -2736,10 +2736,10 @@ nsNativeThemeCocoa::GetProgressMaxValue(
       do_QueryInterface(aFrame->GetContent());
     if (progress) {
       double max;
       progress->GetMax(&max);
       return max;
     }
   }
 
-  return (double)PR_MAX(CheckIntAttr(aFrame, nsWidgetAtoms::max, 100), 1);
+  return (double)NS_MAX(CheckIntAttr(aFrame, nsWidgetAtoms::max, 100), 1);
 }
--- a/widget/src/qt/nsWindow.cpp
+++ b/widget/src/qt/nsWindow.cpp
@@ -304,18 +304,18 @@ UpdateOffScreenBuffers(int aDepth, QSize
     if (gBufferSurface) {
         if (gBufferMaxSize.width < size.width ||
             gBufferMaxSize.height < size.height) {
             gBufferSurface = nsnull;
         } else
             return true;
     }
 
-    gBufferMaxSize.width = PR_MAX(gBufferMaxSize.width, size.width);
-    gBufferMaxSize.height = PR_MAX(gBufferMaxSize.height, size.height);
+    gBufferMaxSize.width = NS_MAX(gBufferMaxSize.width, size.width);
+    gBufferMaxSize.height = NS_MAX(gBufferMaxSize.height, size.height);
 
     // Check if system depth has related gfxImage format
     gfxASurface::gfxImageFormat format =
         _depth_to_gfximage_format(aDepth);
 
     // Use fallback RGB24 format, Qt will do conversion for us
     if (format == gfxASurface::ImageFormatUnknown)
         format = gfxASurface::ImageFormatRGB24;
--- a/widget/src/windows/nsIMM32Handler.cpp
+++ b/widget/src/windows/nsIMM32Handler.cpp
@@ -1196,28 +1196,28 @@ nsIMM32Handler::HandleComposition(nsWind
       // Convert each values of sIMECompClauseArray. The values mean offset of
       // the clauses in ANSI string. But we need the values in Unicode string.
       nsCAutoString compANSIStr;
       if (ConvertToANSIString(mCompositionString, GetKeyboardCodePage(),
                               compANSIStr)) {
         PRUint32 maxlen = compANSIStr.Length();
         mClauseArray[0] = 0; // first value must be 0
         for (PRInt32 i = 1; i < clauseArrayLength; i++) {
-          PRUint32 len = PR_MIN(mClauseArray[i], maxlen);
+          PRUint32 len = NS_MIN(mClauseArray[i], maxlen);
           mClauseArray[i] = ::MultiByteToWideChar(GetKeyboardCodePage(), 
                                                   MB_PRECOMPOSED,
                                                   (LPCSTR)compANSIStr.get(),
                                                   len, NULL, 0);
         }
       }
     }
   }
   // compClauseArrayLength may be negative. I.e., ImmGetCompositionStringW
   // may return an error code.
-  mClauseArray.SetLength(PR_MAX(0, clauseArrayLength));
+  mClauseArray.SetLength(NS_MAX<long>(0, clauseArrayLength));
 
   PR_LOG(gIMM32Log, PR_LOG_ALWAYS,
     ("IMM32: HandleComposition, GCS_COMPCLAUSE, mClauseLength=%ld\n",
      mClauseArray.Length()));
 
   //--------------------------------------------------------
   // 3. Get GCS_COMPATTR
   //--------------------------------------------------------
@@ -1233,17 +1233,17 @@ nsIMM32Handler::HandleComposition(nsWind
     attrArrayLength =
       ::ImmGetCompositionStringW(aIMEContext.get(), GCS_COMPATTR,
                                  mAttributeArray.Elements(),
                                  mAttributeArray.Capacity() * sizeof(PRUint8));
   }
 
   // attrStrLen may be negative. I.e., ImmGetCompositionStringW may return an
   // error code.
-  mAttributeArray.SetLength(PR_MAX(0, attrArrayLength));
+  mAttributeArray.SetLength(NS_MAX<long>(0, attrArrayLength));
 
   PR_LOG(gIMM32Log, PR_LOG_ALWAYS,
     ("IMM32: HandleComposition, GCS_COMPATTR, mAttributeLength=%ld\n",
      mAttributeArray.Length()));
 
   //--------------------------------------------------------
   // 4. Get GCS_CURSOPOS
   //--------------------------------------------------------
--- a/widget/src/windows/nsWindow.cpp
+++ b/widget/src/windows/nsWindow.cpp
@@ -2522,17 +2522,17 @@ void nsWindow::UpdateOpaqueRegion(const 
     // priority is to include the bounds of all plugins.
     nsIntRect largest = aOpaqueRegion.GetLargestRectangle(pluginBounds);
     margins.cxLeftWidth = largest.x;
     margins.cxRightWidth = clientBounds.width - largest.XMost();
     margins.cyBottomHeight = clientBounds.height - largest.YMost();
     if (mCustomNonClient) {
       // The minimum glass height must be the caption buttons height,
       // otherwise the buttons are drawn incorrectly.
-      largest.y = PR_MAX(largest.y,
+      largest.y = NS_MAX<PRUint32>(largest.y,
                          nsUXThemeData::sCommandButtons[CMDBUTTONIDX_BUTTONBOX].cy);
     }
     margins.cyTopHeight = largest.y;
   }
 
   // Only update glass area if there are changes
   if (memcmp(&mGlassMargins, &margins, sizeof mGlassMargins)) {
     mGlassMargins = margins;
@@ -3365,17 +3365,17 @@ NS_IMETHODIMP
 nsWindow::OverrideSystemMouseScrollSpeed(PRInt32 aOriginalDelta,
                                          PRBool aIsHorizontal,
                                          PRInt32 &aOverriddenDelta)
 {
   // The default vertical and horizontal scrolling speed is 3, this is defined
   // on the document of SystemParametersInfo in MSDN.
   const PRUint32 kSystemDefaultScrollingSpeed = 3;
 
-  PRInt32 absOriginDelta = PR_ABS(aOriginalDelta);
+  PRInt32 absOriginDelta = NS_ABS(aOriginalDelta);
 
   // Compute the simple overridden speed.
   PRInt32 absComputedOverriddenDelta;
   nsresult rv =
     nsBaseWidget::OverrideSystemMouseScrollSpeed(absOriginDelta, aIsHorizontal,
                                                  absComputedOverriddenDelta);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -3423,17 +3423,17 @@ nsWindow::OverrideSystemMouseScrollSpeed
 
   // If the given delta is larger than our computed limitation value, the delta
   // was accelerated by the mouse driver.  So, we should do nothing here.
   if (absDeltaLimit <= absOriginDelta) {
     return NS_OK;
   }
 
   absComputedOverriddenDelta =
-    PR_MIN(absComputedOverriddenDelta, absDeltaLimit);
+    NS_MIN(absComputedOverriddenDelta, absDeltaLimit);
 
   aOverriddenDelta = (aOriginalDelta > 0) ? absComputedOverriddenDelta :
                                             -absComputedOverriddenDelta;
   return NS_OK;
 }
 
 /**************************************************************
  **************************************************************
@@ -6932,18 +6932,18 @@ LRESULT nsWindow::OnKeyDown(const MSG &a
             uniChars[0] = ch;
             shiftStates[0] = currentState;
           }
         }
       }
   }
 
   if (numOfUniChars > 0 || numOfShiftedChars > 0 || numOfUnshiftedChars > 0) {
-    PRUint32 num = PR_MAX(numOfUniChars,
-                          PR_MAX(numOfShiftedChars, numOfUnshiftedChars));
+    PRUint32 num = NS_MAX(numOfUniChars,
+                          NS_MAX(numOfShiftedChars, numOfUnshiftedChars));
     PRUint32 skipUniChars = num - numOfUniChars;
     PRUint32 skipShiftedChars = num - numOfShiftedChars;
     PRUint32 skipUnshiftedChars = num - numOfUnshiftedChars;
     UINT keyCode = numOfUniChars == 0 ? DOMKeyCode : 0;
     for (PRUint32 cnt = 0; cnt < num; cnt++) {
       PRUint16 uniChar, shiftedChar, unshiftedChar;
       uniChar = shiftedChar = unshiftedChar = 0;
       if (skipUniChars <= cnt) {
--- a/xpcom/string/src/nsUTF8UtilsSSE2.cpp
+++ b/xpcom/string/src/nsUTF8UtilsSSE2.cpp
@@ -1,22 +1,23 @@
 #include "nscore.h"
+#include "nsAlgorithm.h"
 #include <emmintrin.h>
 #include <nsUTF8Utils.h>
 
 void
 LossyConvertEncoding16to8::write_sse2(const PRUnichar* aSource,
                                       PRUint32 aSourceLength)
 {
   char* dest = mDestination;
 
   // Align source to a 16-byte boundary.
   PRUint32 i = 0;
   PRUint32 alignLen =
-    PR_MIN(aSourceLength, (-NS_PTR_TO_UINT32(aSource) & 0xf) / sizeof(PRUnichar));
+    NS_MIN<PRUint32>(aSourceLength, PRUint32(-NS_PTR_TO_INT32(aSource) & 0xf) / sizeof(PRUnichar));
   for (; i < alignLen; i++) {
     dest[i] = static_cast<unsigned char>(aSource[i]);
   }
 
   // Walk 64 bytes (four XMM registers) at a time.
   __m128i vectmask = _mm_set1_epi16(0x00ff);
   for (; aSourceLength - i > 31; i += 32) {
     __m128i source1 = _mm_load_si128(reinterpret_cast<const __m128i*>(aSource + i));
@@ -59,17 +60,17 @@ LossyConvertEncoding8to16::write_sse2(co
 {
   PRUnichar *dest = mDestination;
 
   // Align source to a 16-byte boundary.  We choose to align source rather than
   // dest because we'd rather have our loads than our stores be fast. You have
   // to wait for a load to complete, but you can keep on moving after issuing a
   // store.
   PRUint32 i = 0;
-  PRUint32 alignLen = PR_MIN(aSourceLength, (-NS_PTR_TO_UINT32(aSource) & 0xf));
+  PRUint32 alignLen = NS_MIN(aSourceLength, PRUint32(-NS_PTR_TO_INT32(aSource) & 0xf));
   for (; i < alignLen; i++) {
     dest[i] = static_cast<unsigned char>(aSource[i]);
   }
 
   // Walk 32 bytes (two XMM registers) at a time.
   for (; aSourceLength - i > 31; i += 32) {
     __m128i source1 = _mm_load_si128(reinterpret_cast<const __m128i*>(aSource + i));
     __m128i source2 = _mm_load_si128(reinterpret_cast<const __m128i*>(aSource + i + 16));