SkVarAlloc::approxBytesAllocated()

This is what I was getting at on the other CL.

BUG=skia:

Committed: https://skia.googlesource.com/skia/+/f27f1bcce50c8f95aea8469684a70b70c9baee09

CQ_EXTRA_TRYBOTS=client.skia.android:Test-Android-Nexus5-Adreno330-Arm7-Release-Trybot

Review URL: https://codereview.chromium.org/730193003
diff --git a/gyp/tests.gypi b/gyp/tests.gypi
index b6a8faa..08277b9 100644
--- a/gyp/tests.gypi
+++ b/gyp/tests.gypi
@@ -212,6 +212,7 @@
     '../tests/TypefaceTest.cpp',
     '../tests/UnicodeTest.cpp',
     '../tests/UtilsTest.cpp',
+    '../tests/VarAllocTest.cpp',
     '../tests/WArrayTest.cpp',
     '../tests/WritePixelsTest.cpp',
     '../tests/Writer32Test.cpp',
diff --git a/src/core/SkVarAlloc.cpp b/src/core/SkVarAlloc.cpp
index 6f5b5a1..8f84b95 100644
--- a/src/core/SkVarAlloc.cpp
+++ b/src/core/SkVarAlloc.cpp
@@ -3,7 +3,7 @@
 // We use non-standard malloc diagnostic methods to make sure our allocations are sized well.
 #if defined(SK_BUILD_FOR_MAC)
     #include <malloc/malloc.h>
-#elif defined(SK_BUILD_FOR_LINUX)
+#elif defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_WIN32)
     #include <malloc.h>
 #endif
 
@@ -56,7 +56,28 @@
 
 #if defined(SK_BUILD_FOR_MAC)
     SkASSERT(alloc == malloc_good_size(alloc));
-#elif defined(SK_BUILD_FOR_LINUX)
-    SkASSERT(alloc == malloc_usable_size(fByte - sizeof(Block)));
+#elif defined(SK_BUILD_FOR_UNIX)
+    // TODO(mtklein): tune so we can assert something like this
+    //SkASSERT(alloc == malloc_usable_size(fBlock));
 #endif
 }
+
+static size_t heap_size(void* p) {
+#if defined(SK_BUILD_FOR_MAC)
+    return malloc_size(p);
+#elif defined(SK_BUILD_FOR_UNIX)
+    return malloc_usable_size(p);
+#elif defined(SK_BUILD_FOR_WIN32)
+    return _msize(p);
+#else
+    return 0;  // Tough luck.
+#endif
+}
+
+size_t SkVarAlloc::approxBytesAllocated() const {
+    size_t sum = 0;
+    for (Block* b = fBlock; b; b = b->prev) {
+        sum += heap_size(b);
+    }
+    return sum;
+}
diff --git a/src/core/SkVarAlloc.h b/src/core/SkVarAlloc.h
index 2b5401b..9eac658 100644
--- a/src/core/SkVarAlloc.h
+++ b/src/core/SkVarAlloc.h
@@ -23,6 +23,10 @@
         return ptr;
     }
 
+    // Returns our best estimate of the number of bytes we've allocated.
+    // (We intentionally do not track this precisely to save space.)
+    size_t approxBytesAllocated() const;
+
 private:
     void makeSpace(size_t bytes, unsigned flags);
 
diff --git a/tests/VarAllocTest.cpp b/tests/VarAllocTest.cpp
new file mode 100644
index 0000000..d6a288d
--- /dev/null
+++ b/tests/VarAllocTest.cpp
@@ -0,0 +1,13 @@
+#include "Test.h"
+#include "SkVarAlloc.h"
+
+DEF_TEST(VarAlloc, r) {
+    SkVarAlloc va;
+    char* p = va.alloc(128, SK_MALLOC_THROW);
+    sk_bzero(p, 128);  // Just checking this is safe.
+
+#ifndef SK_BUILD_FOR_ANDROID
+    // This method will always return 0 on Android.
+    REPORTER_ASSERT(r, va.approxBytesAllocated() >= 128);
+#endif
+}