<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Where&#039;s Walden? &#187; mozilla</title>
	<atom:link href="http://whereswalden.com/tag/mozilla/feed/" rel="self" type="application/rss+xml" />
	<link>http://whereswalden.com</link>
	<description>Mozilla, politics, economics, law, backpacking, cycling, and other random desiderata</description>
	<lastBuildDate>Wed, 25 Jan 2012 18:17:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>SpiderMonkey no longer supports sharp variables</title>
		<link>http://whereswalden.com/2012/01/25/spidermonkey-no-longer-supports-sharp-variables/</link>
		<comments>http://whereswalden.com/2012/01/25/spidermonkey-no-longer-supports-sharp-variables/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 18:17:19 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[sharp variables]]></category>
		<category><![CDATA[spidermonkey]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3701</guid>
		<description><![CDATA[ECMAScript object literals ECMAScript, the standard underlying the JavaScript language, can represent simple objects and arrays using literals. var arr = [1, 2, 3]; var obj = { property: "ohai" }; But it can&#8217;t represent all objects and arrays. Cyclic and non-tree objects ECMAScript literals can&#8217;t represent circular objects and arrays which (perhaps at some [...]]]></description>
			<content:encoded><![CDATA[<h2>ECMAScript object literals</h2>
<p>ECMAScript, the standard underlying the JavaScript language, can represent simple objects and arrays using literals.</p>
<pre class="code" data-language="javascript">
var arr = [1, 2, 3];
var obj = { property: "ohai" };
</pre>
<p>But it can&#8217;t represent all objects and arrays.</p>
<h2>Cyclic and non-tree objects</h2>
<p>ECMAScript literals can&#8217;t represent <em>circular</em> objects and arrays which (perhaps at some nesting distance) have properties referring to themselves (in other words, the objects form cyclic graphs).  Nor can they (faithfully) represent objects which contain some other object multiple times (in other words, the objects form a directed acyclic graph which is not also a tree).</p>
<pre class="code" data-language="javascript">
var arr = [1, "overwritten", 3];
arr[1] = arr; // cyclic
var obj = { property: "ohai", nest: {} };
obj.nest.parent = obj; // cyclic
obj.secondCopy = obj.nest; // non-tree, obj.nest is repeated
</pre>
<h2>Sharp variables</h2>
<p>SpiderMonkey historically supported extension syntax to represent such graphs under the name <dfn>sharp variables</dfn>.  <a href="https://developer.mozilla.org/en/Sharp_variables_in_JavaScript">Sharp variables</a> were inspired by Common Lisp syntax, and they enabled naming an object or array literal before it had been fully evaluated (even, to a limited extent, interacting with it).  Netscape proposed sharp variables for inclusion in <abbr title="ECMAScript, 3rd. edition">ES3</abbr>, but the proposal was rejected as being too domain-specific and being arguably ugly.  Since then the extension has lingered in SpiderMonkey but has seen very little use.</p>
<pre class="code" data-language="javascript">
// Identical semantics using sharp variables
var arr = #1=[1, #1#, 3]; // #n= names an object being created, #n# refers to it
var obj = #1={ property: "ohai", nest: #2={ parent: #1# }, secondCopy: #2# };
</pre>
<p>No other ECMAScript implementer has since shown interest in implementing sharp variables.  And with renewed efforts to evolve ECMAScript syntax, special characters like <code>#</code> are increasingly precious.  Thus we&#8217;ve decided it&#8217;s time to remove sharp variable support from SpiderMonkey.</p>
<p>One benefit to removing sharp variables is that we can remove a good chunk of rarely-used code (and attack surface: sharp variables have been a source of some number of likely vulnerabilities) from SpiderMonkey.  A syntax-removal patch added 79 lines and removed <strong>1112 lines</strong>, including tests; not including tests, it added 42 lines and removed <strong>677 lines</strong>.  A subsequent patch to remove generation of sharp variable syntax from object decompilation added 65 lines and removed <strong>128 lines</strong>.  Removing sharp variables will also permit some simplifications now that evaluating a literal can&#8217;t have side effects beyond those in any nested property initializers.</p</p>
<h2>Alternatives to sharp variables</h2>
<p>Sharp variables may have been sometimes convenient, but they were mere syntactic sugar.  It should be simple to convert any use of sharp variables to an equivalent sequence of property additions.  If you were sufficiently aware of sharp variables to use them to represent non-tree objects, I trust I don&#8217;t have to explain how to do this.</p>
<p>Somewhat more interesting are the cases where decompiling an object produced sharp variable syntax, as when decompiling a cyclic object during debugging.  (It&#8217;s worth noting in passing that decompilation will not infinitely recur: instead, it&#8217;ll bottom out with an empty object or an omitted property.)  <a href="http://blog.mozilla.com/jorendorff/">Jason Orendorff</a> has written a <a href="https://github.com/jorendorff/sharps">sharps mini-library</a> implementing decompilation of cyclic and non-tree objects which may be useful for this task.</p>
<h2>When to expect this change</h2>
<p>The sharp variable <a href="https://developer.mozilla.org/en/JavaScript/Sharp_variables_in_JavaScript">documentation</a> on <a href="https://developer.mozilla.org/">MDN</a> has long noted that sharp variables were deprecated and would likely to be removed; a few months ago that warning was upgraded to a firm statement that they <em>would</em> be removed.  The sharp variable removal patch that landed yesterday completes the process.  The removal will first appear in either today or tomorrow&#8217;s <a href="http://nightly.mozilla.org/">nightly</a>; in a week&#8217;s time it&#8217;ll make its way into the aurora branch, then the beta branch, and finally into Firefox 12.  Versions of Firefox prior to 12 will not be affected by this removal, including the extended-support release Firefox 10.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2012/01/25/spidermonkey-no-longer-supports-sharp-variables/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Introducing mozilla/Assertions.h to mfbt</title>
		<link>http://whereswalden.com/2011/12/26/introducing-mozillaassertions-h-to-mfbt/</link>
		<comments>http://whereswalden.com/2011/12/26/introducing-mozillaassertions-h-to-mfbt/#comments</comments>
		<pubDate>Mon, 26 Dec 2011 17:17:34 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[assertion]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[MOZ_ALWAYS_FALSE]]></category>
		<category><![CDATA[MOZ_ALWAYS_TRUE]]></category>
		<category><![CDATA[MOZ_ASSERT]]></category>
		<category><![CDATA[MOZ_ASSERT_IF]]></category>
		<category><![CDATA[MOZ_NOT_REACHED]]></category>
		<category><![CDATA[MOZ_STATIC_ASSERT]]></category>
		<category><![CDATA[static assertion]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3639</guid>
		<description><![CDATA[Recently I landed changes to the Mozilla Framework Based on Templates (mfbt) implementing Assertions.h, the new canonical assertions implementation in C/C++ Mozilla code. Runtime assertions Using assertions, a developer can efficiently detect when his code goes awry because internal invariants were broken. Mozilla has many assertion facilities. NS_ASSERTION is the oldest, but unfortunately it can [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I landed changes to the Mozilla Framework Based on Templates (<a href="https://developer.mozilla.org/en/mfbt"><abbr title="Mozilla Framework Based on Templates">mfbt</abbr></a>) implementing <a href="http://mxr.mozilla.org/mozilla-central/source/mfbt/Assertions.h"><code>Assertions.h</code></a>, the new canonical assertions implementation in C/C++ Mozilla code.</p>
<h2>Runtime assertions</h2>
<p>Using assertions, a developer can efficiently detect when his code goes awry because internal invariants were broken.  Mozilla has many assertion facilities.  <code>NS_ASSERTION</code> is the oldest, but unfortunately it can be ignored, and therefore historically has been.  We later introduced <code>NS_ABORT_IF_FALSE</code> as as an actual assertion that fails hard, and it&#8217;s now widely used.  But it&#8217;s quite unwieldy, and it can&#8217;t be used by code that doesn&#8217;t want to depend on <abbr title="Cross-platform component object model">XPCOM</abbr>.  (Who would?)</p>
<p>mfbt addresses latent concerns with existing runtime assertions by introducing <code>MOZ_ASSERT</code>, <code>MOZ_ASSERT_IF</code>, <code>MOZ_ALWAYS_TRUE</code>, <code>MOZ_ALWAYS_FALSE</code>, and <code>MOZ_NOT_REACHED</code> macros to make performing true assertions dead simple.</p>
<h3><code>MOZ_ASSERT(expr)</code> and <code>MOZ_ASSERT_IF(ifexpr, expr)</code></h3>
<p><code>MOZ_ASSERT(expr)</code> is straightforward: pass an expression as its sole argument, and in debug builds, if that expression is falsy, the assertion fails and execution halts in a debuggable way.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

void frobnicate(Thing* thing)
{
  MOZ_ASSERT(thing);
  thing->frob();
}
</pre>
<p><code>MOZ_ASSERT_IF(ifexpr, expr)</code> addresses the case when you want to assert something, where the check to decide whether to assert isn&#8217;t otherwise needed.  You&#8217;d rather not muddy up your code by adding an <code>#ifdef</code> and <code>if</code> statement around your assertion.  (<code>MOZ_ASSERT(!ifexpr || expr)</code> is a workaround, but it&#8217;s not very readable.)  SpiderMonkey&#8217;s experience suggests Mozilla code will get good mileage from <code>MOZ_ASSERT_IF</code>.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

class Error
{
    const char* optionalDescription;

  public:
    /* If specified, desc must not be empty. */
    Error(const char* desc = NULL)
    {
      MOZ_ASSERT_IF(desc != NULL, desc[0] != '\0');
      optionalDescription = desc;
    }
};
</pre>
<h3><code>MOZ_ALWAYS_TRUE(expr)</code> and <code>MOZ_ALWAYS_FALSE(expr)</code></h3>
<p>Sometimes the expression for an assertion must always be executed for its side effects, and it can&#8217;t just be executed in debug builds.  <code>MOZ_ALWAYS_TRUE(expr)</code> and <code>MOZ_ALWAYS_FALSE(expr)</code> support this idiom.  These macros always evaluate their argument, and in debug builds that argument is asserted truthy or falsy.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

/* JS_ValueToBoolean was fallible but no longer is. */
MOZ_ALWAYS_TRUE(JS_ValueToBoolean(cx, v, &#038;b));
</pre>
<h3><code>MOZ_NOT_REACHED(reason)</code></h3>
<p><code>MOZ_NOT_REACHED(reason)</code> indicates that the given point can&#8217;t be reached during execution: simply hitting it is a bug.  (Think of it as a more-explicit form of asserting <code>false</code>.)  It takes as an argument an explanation of why that point shouldn&#8217;t have been reachable.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

// ...in a language parser...
void handle(BooleanLiteralNode node)
{
  if (node.isTrue())
    handleTrueLiteral();
  else if (node.isFalse())
    handleFalseLiteral();
  else
    MOZ_NOT_REACHED("boolean literal that's not true or false?");
}
</pre>
<h2>Compile-time assertions</h2>
<p>Most assertions must happen at runtime.  But some assertions are static, depending only on constants, and could be checked during compilation.  A compile time check is better than a runtime check: the developer need not ensure a test exercises that code, because the compiler itself enforces the assertion.  Properly crafted static assertions can never be unwittingly broken.</p>
<h3><code>MOZ_STATIC_ASSERT(cond, reason)</code></h3>
<p><code>MOZ_STATIC_ASSERT(cond, reason)</code> asserts a condition at compile time.  In newer compilers, if the assertion fails, the compiler will also include <code>reason</code> in diagnostics.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

struct S { ... };
MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
                  "S should be a multiple of word size for efficiency");
</pre>
<p><code>MOZ_STATIC_ASSERT</code> is implemented with <a href="http://hg.mozilla.org/mozilla-central/file/45206fca898d/mfbt/Assertions.h#l62">an impressive pile of hacks</a> which should work perfectly everywhere &mdash; except, rarely, gcc 4.2 (the current OS X compiler) when compiling C++ code.  The failure mode requires <code>MOZ_STATIC_ASSERT</code> on line <var>N</var> not in an <code>extern "C"</code> code block and a second <code>MOZ_STATIC_ASSERT</code> on the <em>same</em> line <var>N</var> (in a different file) in an <code>extern "C"</code> block.  <em>And</em> those two files have to be used when compiling a single file, with the <code>extern "C"</code>&#8216;d assertion second.  This seems improbable, so we&#8217;ll risk it til we drop gcc 4.2 support.</p>
<h2>Possible improvements</h2>
<p><code>Assertions.h</code> is reasonably complete, but I have a few ideas I&#8217;ve been considering for improvements.  Let me know what you think of them in comments.</p>
<h3>Add an optional <code>reason</code> argument to <code>MOZ_ASSERT</code>, and maybe to <code>MOZ_ALWAYS_TRUE</code> and <code>MOZ_ALWAYS_FALSE</code></h3>
<p><code>MOZ_ASSERT</code> takes only the condition to test as an argument.  In contrast <code>NS_ASSERTION</code> and <code>NS_ABORT_IF_FALSE</code> take the condition and an explanatory string.  <code>MOZ_ASSERT</code>&#8216;s lack of explanation derives purely from its ancestry in the <code>JS_ASSERT</code> macro: it wasn&#8217;t deliberate.</p>
<p>Would it be helpful if <code>MOZ_ASSERT</code>, <code>MOZ_ALWAYS_TRUE</code>, and <code>MOZ_ALWAYS_FALSE</code> optionally took a reason?  (Optional because some assertions, <abbr title="exempli gratia, for example" lang="la">e.g.</abbr> many non-null assertions, are self-explanatory.)  We&#8217;d have to disable assertions for compilers not implementing variadic macros (I think our supported compilers implement them), or <em>possibly</em> lose the condition expression in the assertion failure message.  A reason would make it easier to convert existing <code>NS_ABORT_IF_FALSE</code>s to <code>MOZ_ASSERT</code>s.  Should we add an optional second argument to <code>MOZ_ASSERT</code> and the others?</p>
<h3>Include <code>__assume(0)</code> or <code>__builtin_unreachable()</code> in <code>MOZ_NOT_REACHED</code></h3>
<p><a href="http://clang.llvm.org/docs/LanguageExtensions.html#__builtin_unreachable"><code>__builtin_unreachable()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/1b3fsfxw.aspx"><code>__assume(0)</code></a> inform the compiler that subsequent code can&#8217;t be executed, providing optimization opportunities.  It&#8217;s unclear how this affects debugging feedback like stack traces.  If the optimizations destroy Breakpad-ability, that may be too big a loss.  More research is needed here.</p>
<p>Another possibility might be to use <a href="http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005ftrap-3216"><code>__builtin_trap()</code></a>.  This may not communicate an optimization opportunity comparable to that provided by the other two options.  (It can&#8217;t be equally informative because execution must be able to continue past a trap.  Thus the two have different impacts on variable lifetimes.  Whether <code>__builtin_trap</code> otherwise communicates &#8220;unlikelihood&#8221; well enough isn&#8217;t clear.)  Perhaps <code>__builtin_trap</code> could be used in debug builds, and <code>__builtin_unreachable</code> could be used in optimized builds.  Again: more research needed.</p>
<h3>Use C11&#8242;s <code>_Static_assert</code> in <code>MOZ_STATIC_ASSERT</code></h3>
<p>New editions of C and C++ include built-in static assertion syntax.  <code>MOZ_STATIC_ASSERT</code> expands to C++11&#8242;s <code>static_assert(2 + 2 == 4, "ya rly")</code> syntax when possible.  It could be made to expand to C11&#8242;s <code>_Static_assert('A' == 'A', "no wai")</code> syntax in some other cases, but frankly I don&#8217;t hack enough C code to care as long as the static assertion actually happens.  <img src='http://whereswalden.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />   This is <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=713531">bug 713531</a> if you&#8217;re interested in investigating.</p>
<h2>Want more information?</h2>
<p>Read <a href="http://mxr.mozilla.org/mozilla-central/source/mfbt/Assertions.h"><code>Assertions.h</code></a>.  mfbt code has a high standard for code comments in interface descriptions, and for file names (the current <code>Util.h</code> being a notable exception <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=713082">which will be fixed</a>).  We want it to be reasonably obvious where to find what you need and how to use it by skimming <a href="http://mxr.mozilla.org/mozilla-central/source/mfbt/"><code>mfbt/</code></a>&#8216;s contents and then skimming a few files&#8217; contents.  Good comments are key to that.  You should find <code>Assertions.h</code> quite readable; please <a href="https://bugzilla.mozilla.org/enter_bug.cgi?product=Core&amp;product=MFBT">file a bug</a> if you have improvements to suggest.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/12/26/introducing-mozillaassertions-h-to-mfbt/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Seen during a recent compile of mozilla-central with Clang, offered without comment</title>
		<link>http://whereswalden.com/2011/12/15/seen-during-a-recent-compile-of-mozilla-central-with-clang-offered-without-comment/</link>
		<comments>http://whereswalden.com/2011/12/15/seen-during-a-recent-compile-of-mozilla-central-with-clang-offered-without-comment/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 03:56:15 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[beard]]></category>
		<category><![CDATA[building]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[offered without comment]]></category>
		<category><![CDATA[warning]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3633</guid>
		<description><![CDATA[TestStartupCache.cpp /home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:119:15: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings] char* buf = "Market opportunities for BeardBook"; ^ /home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:120:14: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings] char* id = "id"; ^ /home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:148:15: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings] char* buf = "BeardBook competitive [...]]]></description>
			<content:encoded><![CDATA[<pre class="code">
TestStartupCache.cpp
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:119:15</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* buf = "Market opportunities for BeardBook";
              ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:120:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:148:15</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* buf = "BeardBook competitive analysis";
              ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:149:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:197:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:288:15</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* buf = "Find your soul beardmate on BeardBook";
              ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:289:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:323:12</strong>: warning: unused variable 'rv2' [-Wunused-variable]
  nsresult rv2;
           ^
8 warnings generated.
</pre>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/12/15/seen-during-a-recent-compile-of-mozilla-central-with-clang-offered-without-comment/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Party like it&#8217;s 1999: &lt;stdint.h&gt; comes to Mozilla!</title>
		<link>http://whereswalden.com/2011/12/08/party-like-its-1999-stdint-h-comes-to-mozilla/</link>
		<comments>http://whereswalden.com/2011/12/08/party-like-its-1999-stdint-h-comes-to-mozilla/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 20:08:11 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[c89]]></category>
		<category><![CDATA[c99]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[msvc]]></category>
		<category><![CDATA[our long national nightmare is over]]></category>
		<category><![CDATA[stdint.h]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3544</guid>
		<description><![CDATA[tl;dr Need an integer type with guaranteed size? If you&#8217;re not defining a cross-file interface, #include "mozilla/StdInt.h" and use uint32_t or any other type defined by &#60;stdint.h&#62;. (If you are defining an interface, use PRUint32 and similar &#8212; for now.) mozilla/StdInt.h is a cross-platform implementation of &#60;stdint.h&#62;&#8216;s functionality usable in any code. Embedders may find [...]]]></description>
			<content:encoded><![CDATA[<h2><abbr title="too long; didn't read">tl;dr</abbr></h2>
<p>Need an integer type with guaranteed size?  If you&#8217;re not defining a cross-file interface, <code>#include "mozilla/StdInt.h"</code> and use <code>uint32_t</code> or any other type defined by <code>&lt;stdint.h&gt;</code>.  (If you are defining an interface, use <code>PRUint32</code> and similar &mdash; for now.)  <code>mozilla/StdInt.h</code> is a cross-platform implementation of <code>&lt;stdint.h&gt;</code>&#8216;s functionality usable in any code.</p>
<p>Embedders may find that the <code>mozilla/StdInt.h</code> <code>typedef</code>s conflict with ones they have already been using.  To work around this conflict, write a <code>stdint.h</code> compatible with the embedding&#8217;s <code>typedef</code>s (more likely: adapt an existing implementation), then set the preprocessor variable <code>MOZ_CUSTOM_STDINT_H</code> to a quoted path to that reimplementation when <code>mozilla/StdInt.h</code> is included.  It may be simplest to add this to command line flags when invoking the compiler.</p>
<h2>Fixed-size integer types</h2>
<p><dfn>Fixed-size integer types</dfn> are signed or unsigned types with exactly <var>N</var> bits.  They contrast with the built-in C and C++ types (<code>char</code>, <code>short</code>, <code>int</code>, <abbr title="et cetera, and so on" lang="la">&amp;c.</abbr>) with compiler-dependent sizes.  Fixed-size integer types are quite useful:</p>
<ul>
<li>They work well when serializing an object to a sequence of bytes, where the size of a serialized item <em>must</em> be constant for correctness.</li>
<li>They minimize memory use in <code>class</code>es and <code>struct</code>s, also making padding-based waste more obvious.</li>
<li>They work well in cross-platform <abbr title="Application Programming Interfaces">APIs</abbr>, eliminating the challenge of implementing correct behavior when types have different sizes across platforms.</li>
</ul>
<p>Fixed-size integer types are useful in the same way <code>size_t</code>, <code>off_t</code>, and other non-built-in types are: they fit some problem domains better than built-in types.</p>
<p>C99 and C++11 finally standardized fixed-size integer types in <code>&lt;stdint.h&gt;</code> and <code>&lt;cstdint&gt;</code>.  They define <code>{u,}int{8,16,32,64}_t</code> types, plus useful constants for their limits (<code>INT8_MIN</code>, <code>INT8_MAX</code>, <code>UINT8_MAX</code>, <code>INT16_MIN</code>, <span lang="la">&amp;c.</span>).  One would expect projects to quickly use these types, but it didn&#8217;t happen.</p>
<p>Old projects predating <code>&lt;stdint.h&gt;</code> have been particularly slow to adopt it.  Many such projects already rolled their own non-<code>&lt;stdint.h&gt;</code>-named fixed-size integer types; switching would be a hassle.  And not all compilers shipped <code>&lt;stdint.h&gt;</code>: Visual Studio didn&#8217;t have it until 2010!  (ಠ_ಠ)  Projects implementing their own <code>&lt;stdint.h&gt;</code>-compatible types posed another problem, because different projects&#8217; implementations might be incompatible.</p>
<p>New projects fare better, but not always.  Sometimes their dependence on old projects anchors them to the old, pre-<code>&lt;stdint.h&gt;</code> world.</p>
<h2>Fixed-size integer types in Mozilla</h2>
<p>Mozilla sits squarely in the old-project category, facing every rationale noted above for using its own types.  These have long been <abbr title="Netscape Portable Runtime">NSPR</abbr>&#8216;s <code>PR{Ui,I}nt{8,16,32,64}</code> and SpiderMonkey&#8217;s <code>{u,}int{8,16,32,64}</code> types.  But recently the landscape has changed.</p>
<p>As Mozilla has imported more external code, fixed-size integer types have proliferated.  Most imported code uses <code>&lt;stdint.h&gt;</code>, with fallback <code>typedef</code>s for Visual Studio; some code (<abbr title="Inter-process communication">IPC</abbr> code from Chromium) defines and uses <code>{u,}int{8,16,32,64}</code>.  As type definitions have proliferated, surprising problems have arisen.</p>
<h2>The woes of multiplicity</h2>
<p><code>#include</code>-order issues are the simplest problem.  For example, the IPC <code>uint32</code>-style definitions are incompatible with SpiderMonkey&#8217;s definitions with some compilers.  <code>#include</code> IPC and SpiderMonkey headers in the wrong order, and the compiler will error on incompatible <code>typedef</code>s.  This problem is easy to diagnose but harder to resolve, and sometimes it causes considerable pain.  Mass refactorings that add <code>#include</code>s have fallen afoul of this, with the least bad solution usually being to fix the first error, recompile, and repeat until done (twenty-odd times <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=693469#c13">in one instance</a>).</p>
<p>Worse than <code>#include</code> mis-ordering and conflict are linking problems.  <code>int</code> and <code>long</code> <a href="http://msdn.microsoft.com/en-us/library/s3f49ktz%28v=VS.80%29.aspx">could</a> be 32-bit integers yet <a href="http://www.kegel.com/mangle.html#types">appear different when linked</a>.  Suppose a method taking an <code>int32</code> argument defined <code>int32 = int</code> during compilation, but a user of it saw <code>int32 = long</code> during compilation.  Each alone would compile.  But beneath <code>typedef</code>s they&#8217;d be incompatible and wouldn&#8217;t link.</p>
<p>As we&#8217;ve imported more code in Mozilla, more and more developers have been bitten by these problems.  We&#8217;ve reached a breaking point.  We could use <code>PRUint32</code>, <code>JSUint32</code>, and other types which never trample upon each other.  Yet no one likes them given the standardized types, and it&#8217;s not possible to change &#8220;upstream&#8221; code to such a scheme.  Thus a second solution: use <code>&lt;stdint.h&gt;</code> definitions for everything.</p>
<h2>Switching to <code>&lt;stdint.h&gt;</code></h2>
<p>Using the <code>&lt;stdint.h&gt;</code> types in Mozilla code is now as simple as <code>#include "mozilla/StdInt.h"</code>.  <code>mozilla/StdInt.h</code> implements the <code>&lt;stdint.h&gt;</code> interface even in the edge cases: for compilers not supporting it, and for embedders who can&#8217;t use the regular definitions.  It works as follows:</p>
<ol>
<li>If the preprocessor definition <code>MOZ_CUSTOM_STDINT_H</code> is defined, then <code>#include MOZ_CUSTOM_STDINT_H</code>.  Embedders who can&#8217;t use the default definitions should use this to adapt.  (<code>MOZ_CUSTOM_STDINT_H</code> may also be passed into the Mozilla build system using an environment variable.  Note that while the preprocessor definition must be a quoted path, the environment variable must be an unquoted path.)</li>
<li>Otherwise, if the compiler doesn&#8217;t provide <code>&lt;stdint.h&gt;</code>, use a custom implementation.  This is currently limited to Visual Studio prior to 2010, using an implementation imported from <a href="https://code.google.com/p/msinttypes/source/browse/trunk/stdint.h">msinttypes</a> on Google Code.</li>
<li>Otherwise use <code>&lt;stdint.h&gt;</code>.</li>
</ol>
<p>We&#8217;re only providing these types now, but shortly we&#8217;ll start switching code using non-<code>&lt;stdint.h&gt;</code> fixed-size integer types to use them.  Adding <code>mozilla/StdInt.h</code> is merely the first step toward removing the other fixed-size integer types (except when they&#8217;re necessary to interact with external libraries).</p>
<h2>Conclusion</h2>
<p>It&#8217;s been a dozen years since <code>&lt;stdint.h&gt;</code> was standardized.  Now it finally comes to Mozilla.  Let&#8217;s lower a barrier to hackability in Mozilla and start using it.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/12/08/party-like-its-1999-stdint-h-comes-to-mozilla/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Introducing MOZ_FINAL: prevent inheriting from a class, or prevent overriding a virtual function</title>
		<link>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/</link>
		<comments>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 17:17:39 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[final]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[moz_final]]></category>
		<category><![CDATA[sealed]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3533</guid>
		<description><![CDATA[The inexorable march of progress continues in the Mozilla Framework Based on Templates with the addition of MOZ_FINAL, through which you can limit various forms of inheritance in C++. Traditional C++ inheritance mostly can&#8217;t be controlled In C++98 any class can be inherited. (An extremely obscure pattern will prevent this, but it has down sides.) [...]]]></description>
			<content:encoded><![CDATA[<p>The inexorable march of progress continues in the Mozilla Framework Based on Templates with the addition of <code>MOZ_FINAL</code>, through which you can limit various forms of inheritance in C++.</p>
<h2>Traditional C++ inheritance mostly can&#8217;t be controlled</h2>
<p>In C++98 any class can be inherited.  (An extremely obscure pattern will prevent this, but it has down sides.)  Sometimes this makes sense: it&#8217;s natural to subclass an abstract <code>List</code> class as <code>LinkedList</code>, or <code>LinkedList</code> as <code>CircularLinkedList</code>.  But sometimes this doesn&#8217;t make sense.  <code>StringBuilder</code> certainly could inherit from <code>Vector&lt;char&gt;</code>, but doing so might expose many <code>Vector</code> methods that don&#8217;t belong in the <code>StringBuilder</code> concept.  It would be more sensible for <code>StringBuilder</code> to contain a private <code>Vector&lt;char&gt;</code> which <code>StringBuilder</code> member methods manipulated.  Preventing <code>Vector</code> from being used as a base class would be one way (not necessarily the best one) to avoid this conceptual error.  But C++98 doesn&#8217;t let you easily do that.</p>
<p>Even when inheritance is desired, sometimes you don&#8217;t want completely-virtual methods.  Sometimes you&#8217;d like a class to implement a virtual method (virtual perhaps because <em>its</em> base declared it so) which derived classes can&#8217;t override.  Perhaps you want to rely on that method being implemented only by your base class, or perhaps you want it &#8220;fixed&#8221; as an optimization.  Again in C++98, you can&#8217;t do this: public virtual functions are overridable.</p>
<h2>C++11&#8242;s contextual <code>final</code> keyword</h2>
<p>C++11 introduces a contextual <code>final</code> keyword for these purposes.  To prevent a class from being inheritable, add <code>final</code> to its definition just after the class name (the class can&#8217;t be unnamed).</p>
<pre class="code" data-language="c++">
struct Base1 final
{
  virtual void foo();
};

// ERROR: can't inherit from B.
struct Derived1 : public Base1 { };

struct Base2 { };

// Derived classes can be final too.
struct Derived2 final : public Base2 { };
</pre>
<p>Similarly, a virtual member function can be marked as not overridable by placing the contextual <code>final</code> keyword at the end of its declaration, before a terminating semicolon, body, or <code>= 0</code>.</p>
<pre class="code" data-language="c++">
struct Base
{
  virtual void foo() final;
};

struct Derived : public Base
{
  // ERROR: Base::foo was final.
  virtual void foo() { }
};
</pre>
<h2>Introducing <code>MOZ_FINAL</code></h2>
<p><abbr title="Mozilla Framework Based on Templates">mfbt</abbr> now includes support for marking classes and virtual member functions as final using the <code>MOZ_FINAL</code> macro in <code>mozilla/Attributes.h</code>.  Simply place it in the same position as <code>final</code> would occur in the C++11 syntax:</p>
<pre class="code" data-language="c++">
#include "mozilla/Attributes.h"

class Base
{
  public:
    virtual void foo();
};

class Derived final : public Base
{
  public:
    /*
     * MOZ_FINAL and MOZ_OVERRIDE are composable; as a matter of
     * style, they should appear in the order MOZ_FINAL MOZ_OVERRIDE,
     * not the other way around.
     */
    virtual void foo() MOZ_FINAL MOZ_OVERRIDE { }
    virtual void bar() MOZ_FINAL;
    virtual void baz() MOZ_FINAL = 0;
};
</pre>
<p><code>MOZ_FINAL</code> expands to the C++11 syntax or its compiler-specific equivalent whenever possible, turning violations of <code>final</code> semantics into compile-time errors.  The same compilers that usefully expand <a href="http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/"><code>MOZ_OVERRIDE</code></a> also usefully expand <code>MOZ_FINAL</code>, so misuse will be quickly noted.</p>
<p>One interesting use for <code>MOZ_FINAL</code> is to tell the compiler that one worrisome C++ trick sometimes isn&#8217;t.  This is the <em>virtual-methods-without-virtual-destructor</em> trick.  It&#8217;s used when a class must have virtual functions, but code doesn&#8217;t want to pay the price of destruction having virtual-call overhead.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    virtual void method() { }
    ~Base() { }
};

void destroy(Base* b)
{
  delete b; // may cause a warning
}
</pre>
<p>Some compilers warn when they instantiate a class with virtual methods but without a virtual destructor.  Other compilers only emit this warning when a pointer to a class instance is <code>delete</code>d.  The reason is that in C++, behavior is undefined if the static type of the instance being deleted isn&#8217;t the same as its runtime type <em>and</em> its destructor isn&#8217;t virtual.  In other words, if <code>~Base()</code> is non-virtual, <code>destroy(new Base)</code> is perfectly fine, but <code>destroy(new DerivedFromBase)</code> is not.  The warning makes sense if destruction might miss a base class &mdash; but if the class is marked <code>final</code>, it never will!  Clang silences its warning if the class is <code>final</code>, and I hope that <a href="https://connect.microsoft.com/VisualStudio/feedback/details/707497/msvc-should-not-emit-the-optional-warning-c4265-virtual-functions-non-virtual-destructor-for-a-class-marked-as-sealed">MSVC will shortly do the same</a>.</p>
<h2>What about <code>NS_FINAL_CLASS</code>?</h2>
<p>As with <code>MOZ_OVERRIDE</code> we had a gunky <abbr title="Cross-platform component-object model">XPCOM</abbr> static-analysis <code>NS_FINAL_CLASS</code> macro for final classes.  (We had no equivalent for final methods.)  <code>NS_FINAL_CLASS</code> too was misplaced as far as C++11 syntax was concerned, and it too has been deprecated.  Almost all uses of <code>NS_FINAL_CLASS</code> have now been removed (the one remaining use I&#8217;ve left for the moment due to an apparent Clang bug I haven&#8217;t tracked down yet), and it shouldn&#8217;t be used.</p>
<p>(Side note: In replacing <code>NS_FINAL_CLASS</code> with <code>MOZ_FINAL</code>, I discovered that some of the existing annotations have been buggy for months!  Clearly no one&#8217;s done static analysis builds in awhile.  The moral of the story: compiler static analyses that happen for every single build are vastly superior to user static analyses that happen only in special builds.)</p>
<h2>Summary</h2>
<p>If you don&#8217;t want a class to be inheritable, add <code>MOZ_FINAL</code> to its definition after the class name.  If you don&#8217;t want a virtual member function to be overridden in derived classes, add <code>MOZ_FINAL</code> at the end of its declaration.  Some compilers will then enforce your wishes, and you can rely on these requirements rather than hope for the best.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Introducing MOZ_OVERRIDE to annotate virtual functions which override base-class virtual functions</title>
		<link>http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/</link>
		<comments>http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 17:55:41 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[help wanted]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[moz_override]]></category>
		<category><![CDATA[override]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3515</guid>
		<description><![CDATA[Overriding inherited virtual functions One way C++ supports code reuse is through inheritance. One base class implements common functionality. Then other classes inherit from it, essentially copying functionality from it. These other classes can add their own new functionality, or, more powerfully, they can override the base class functionality. class Base { public: virtual const [...]]]></description>
			<content:encoded><![CDATA[<h2>Overriding inherited virtual functions</h2>
<p>One way C++ supports code reuse is through inheritance.  One base class implements common functionality.  Then other classes <dfn>inherit</dfn> from it, essentially copying functionality from it.  These other classes can add their own new functionality, or, more powerfully, they can override the base class functionality.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    virtual const char* type() { return "Base"; }
};
class Derived : public Base
{
  public:
    virtual const char* type() { return "Derived"; }
};
</pre>
<p>Overriding base class functionality is simple.  Keeping such overrides working correctly is sometimes harder.  The problem is that the override relationship is implicit: if the override doesn&#8217;t exactly match the signature of the desired function in the base class, it may not work correctly.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    // Perhaps as part of an incomplete refactoring,
    // the base class's function changed its name.
    virtual const char* kind() { return "Base"; }
};
class DerivedIncorrectly : public Base
{
  public:
    virtual const char* type() { return "Derived"; }
};

// BAD: code expecting kind() to work and sometimes
// indicate Derived-ness no longer will.
</pre>
<h2>Making the override relationship explicit</h2>
<p>Some languages (Scala, C#, probably others) provide the ability to mark a derived class&#8217;s function as an override of an inherited function.  C++98 included no such ability, but C++11 does, through the contextual <code>override</code> keyword.  When <code>override</code> is used, that virtual member function must override one found on a base class.  If it does not, it is a compile error.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    virtual const char* kind() { return "Base"; }
};
class DerivedIncorrectly : public Base
{
  public:
    // This will cause a compile error: there's no type()
    // method on Base that this overrides.
    virtual const char* type() override { return "Derived"; }

    // This will work as intended.
    virtual const char* kind() override { return "Derived"; }
};
</pre>
<h2>Introducing <code>MOZ_OVERRIDE</code></h2>
<p>The Mozilla Framework Based on Templates now includes support for the C++11 contextual <code>override</code> keyword, encapsulated in the <code>MOZ_OVERRIDE</code> macro in <del><code>mozilla/Types.h</code></del><ins><code>mozilla/Attributes.h</code></ins>.  Simply place it at the end of the declaration of the relevant method, before any <code>= 0</code> or method body, like so:</p>
<pre class="code" data-language="c++">
<del>#include "mozilla/Types.h"</del> // MOZ_OVERRIDE has since moved...
<ins>#include "mozilla/Attributes.h"</ins> // ...to here

class Base
{
  public:
    virtual void f() = 0;
};
class Derived1 : public Base
{
  public:
    virtual void f() MOZ_OVERRIDE;
};
class Derived2 : public Base
{
  public:
    virtual void f() MOZ_OVERRIDE = 0;
};
class Derived3 : public Base
{
  public:
    virtual void f() MOZ_OVERRIDE { }
};
</pre>
<p><code>MOZ_OVERRIDE</code> will expand to use the C++11 construct in compilers which support it.  Thus in such compilers misuse of <code>MOZ_OVERRIDE</code> is an error.  Even better, some of the compilers used by tinderbox support <code>override</code>, so in many cases tinderbox will detect misuse.  (Specifically, <abbr title="Microsoft Visual C++ 2005">MSVC++ 2005</abbr> and later support it, so errors in cross-platform and Windows code won&#8217;t pass tinderbox .  Much more recent versions of <abbr title="GNU Compiler Collection">GCC</abbr> and Clang support it as well, but these versions are too new for tinderbox to have picked them up yet &mdash; in the case of GCC too new to even have been released yet.  <img src='http://whereswalden.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  )</p>
<h2>What about <code>NS_OVERRIDE</code>?</h2>
<p>It turns out there&#8217;s already a macro annotation to indicate an override relationship: <code>NS_OVERRIDE</code>.  This gunky <abbr title="Cross-platform component object model">XPCOM</abbr> macro expands to a user attribute under gcc-like compilers.  It&#8217;s only used by static analysis right now, so its value is limited.  Unfortunately its position is different &mdash; necessarily so, because in the C++11 <code>override</code> position it would attach to the return value of the method:</p>
<pre class="code" data-language="c++">
class OldAndBustedDerived : public Base
{
  public:
    NS_OVERRIDE virtual void f(); // annotates the method
    __attribute__(...) virtual void g(); // its expansion
};
class Derived2 : public Base
{
  public:
    // But in the MOZ_OVERRIDE position, it would annotate
    // f()'s return value.
    virtual void f() __attribute__(...);
};
</pre>
<p><code>NS_OVERRIDE</code> is now deprecated and should be replaced with <code>MOZ_OVERRIDE</code>.  With a little work, static analysis with new-enough compilers can likely look for <code>MOZ_OVERRIDE</code> just as easily as for <code>NS_OVERRIDE</code>.  And since <code>MOZ_OVERRIDE</code> works in non-static analysis builds, it&#8217;s arguably better in the majority of cases anyway.  If you&#8217;re looking for an easy way to improve Mozilla code, changing <code>NS_OVERRIDE</code> uses to use <code>MOZ_OVERRIDE</code> would be a simple way to help.</p>
<h2>Summary</h2>
<p>If you&#8217;ve overridden an inherited virtual member function and you&#8217;re worried that that override might silently break at some point, annotate your override with <code>MOZ_OVERRIDE</code>.  This will cause some compilers to enforce an override relationship, making it much less likely that your intended relationship will break.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Introducing MOZ_DELETE, a macro improving upon the deliberately-unimplemented method idiom</title>
		<link>http://whereswalden.com/2011/11/09/introducing-moz_delete-a-macro-improving-upon-the-deliberately-unimplemented-method-idiom/</link>
		<comments>http://whereswalden.com/2011/11/09/introducing-moz_delete-a-macro-improving-upon-the-deliberately-unimplemented-method-idiom/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 22:12:33 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[copy constructor]]></category>
		<category><![CDATA[default assignment]]></category>
		<category><![CDATA[help wanted]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[moz_delete]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3487</guid>
		<description><![CDATA[C++ default operators and the sole-ownership idiom Often a C++ class will solely manage some value: for example, a GtkWindow* or a void* for malloc&#8216;d memory. The class will then release ownership in its destructor as appropriate. It would be extremely problematic to release ownership multiple times &#8212; think security-vulnerability-problematic. C++ copy construction and default [...]]]></description>
			<content:encoded><![CDATA[<h2>C++ default operators and the sole-ownership idiom</h2>
<p>Often a C++ class will solely manage some value: for example, a <code>GtkWindow*</code> or a <code>void*</code> for <code>malloc</code>&#8216;d memory.  The class will then release ownership in its destructor as appropriate.  It would be extremely problematic to release ownership multiple times &mdash; think security-vulnerability-problematic.  C++ copy construction and default assignment exacerbate this issue, because C++ automatically generates these methods for all classes, even when the default behavior breaks sole-ownership.  The C++98 idiom solving this is to privately declare a copy constructor and a default assignment operator, then never define them:</p>
<pre class="code" data-language="c++">
struct Struct
{
  private:
    Struct(const Struct&amp; other);
    void operator=(const Struct&amp; other);
};
</pre>
<p>Declaring the methods privately prevents any code but friends of <code>Struct</code> from calling them.  And by never defining them, even such friends will cause a link-time error if they try.</p>
<h2>Disabling the default operators in C++11</h2>
<p>Once you&#8217;re familiar with this idiom it&#8217;s not too bad.  But initially, it&#8217;s pretty unclear.  And nothing prevents someone from actually defining these methods.  (They could only be used by <code>Struct</code> or friends of <code>Struct</code>, to be sure, but for sufficiently complex code it&#8217;s possible someone might make a mistake.)  C++11 improves upon this trick by introducing deleted function syntax:</p>
<pre class="code" data-language="c++">
struct Struct
{
  private: // no longer necessary, but doesn't hurt
    Struct(const Struct&amp; other) = delete;
    void operator=(const Struct&amp; other) = delete;
};
</pre>
<p>Deleted functions are effectively removed from name lookup: using, defining, or referring to a deleted function produces a compile error &mdash; far better than a link error or, even worse, no error at all.</p>
<h2><code>= delete</code> support in <abbr title="Mozilla Framework Based on Templates">mfbt</abbr></h2>
<p>The Mozilla Framework Based on Templates now includes support for declaring a function only to prevent its use (or use of an inherited version).  The <code>MOZ_DELETE</code> macro encapsulates this support:</p>
<pre class="code" data-language="c++">
<del>#include "mozilla/Types.h"</del> // MOZ_DELETE has since moved...
<ins>#include "mozilla/Attributes.h"</ins> // ...to here

struct Struct
{
  private:
    Struct(const Struct&amp; other) MOZ_DELETE;
    void operator=(const Struct&amp; other) MOZ_DELETE;
};
</pre>
<p><code>MOZ_DELETE</code> isn&#8217;t as readable or understandable as <code>= delete</code>, but it&#8217;s searchable, and <a href="http://hg.mozilla.org/integration/mozilla-inbound/file/b5373c0d5a88/mfbt/Types.h#l93">the comment next to its definition</a> will clarify matters.  If the declarations are private, <code>MOZ_DELETE</code> is just as good as the traditional idiom, and in compilers supporting C++11 deleted functions it&#8217;s better.</p>
<p>Which compilers support C++11 deleted functions?  I&#8217;m aware of <abbr title="GNU Compiler Collection">GCC</abbr> <a href="http://gcc.gnu.org/projects/cxx0x.html">since 4.4</a>, Clang <a href="http://clang.llvm.org/cxx_status.html">since 2.9</a>, and <abbr title="Intel C/C++ Compiler">ICC</abbr> <a href="http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler/">since 12.0</a>.  Rightly, if unfortunately, you must specify <code>-std=c++0x</code> or similar to use deleted function syntax without causing a warning.  For various reasons Mozilla can&#8217;t do that yet, so <code>MOZ_DELETE</code> only produces the C++11 syntax when compiling with Clang (where we can pass <code>-Wno-c++0x-extensions</code> to disable the warning).  I&#8217;d love to see it use C++11 syntax in GCC and ICC as well, but I don&#8217;t have the time to solve the <code>-std=c++0x</code> problem now, or to figure out another workaround.  I&#8217;ve filed <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=701183">bug 701183</a> for this problem &mdash; help there is much appreciated.</p>
<h2>Summary</h2>
<p>Use <code>MOZ_DELETE</code> when declaring any method you will intentionally not implement.  It&#8217;ll work better, and produce better errors, in some compilers.  Those compilers don&#8217;t include GCC or ICC yet, but <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=701183">with your help</a> they could.  Any takers?</p>
<p><strong>Update</strong>, evening of November 10, 2011: I just landed further changes to make <code>MOZ_DELETE</code> use C++11 syntax with GCC when compiling with <code>-std=c++0x</code> (which we apparently do more often than I&#8217;d thought), so you should now get its goodness in GCC as well &mdash; most of the time.  In some &#8220;exotic&#8221; situations we don&#8217;t compile anything with <code>-std=c++0x</code>, so you won&#8217;t get any benefit there.  Also, the JavaScript engine is never compiled with it.  So if you want this to work fully, everywhere, you should use Clang.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/09/introducing-moz_delete-a-macro-improving-upon-the-deliberately-unimplemented-method-idiom/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How I organize my Mozilla trees</title>
		<link>http://whereswalden.com/2011/11/03/how-i-organize-my-mozilla-trees/</link>
		<comments>http://whereswalden.com/2011/11/03/how-i-organize-my-mozilla-trees/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 17:17:26 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[hg]]></category>
		<category><![CDATA[mercurial]]></category>
		<category><![CDATA[mozilla]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3436</guid>
		<description><![CDATA[Using Mozilla trees more smartly A month ago I got a new laptop, requiring me to migrate my Mozilla trees, patches, and related work from old laptop to new. My previous setup was the simplest, stupidest thing that could work: individual clones of different trees, no sharing among those trees, sometimes multiple clones of the [...]]]></description>
			<content:encoded><![CDATA[<h2>Using Mozilla trees more smartly</h2>
<p>A month ago I got a new laptop, requiring me to migrate my Mozilla trees, patches, and related work from old laptop to new.  My previous setup was the simplest, stupidest thing that could work: individual clones of different trees, no sharing among those trees, sometimes multiple clones of the same tree for substantial, independent patchwork I didn&#8217;t want to explicitly order.  Others have tried <a href="http://jlebar.com/2011/5/20/Faster_and_smaller_clones_of_branches.html">smarter tricks</a> in the past, and I decided to upgrade my setup.</p>
<h2>A new setup</h2>
<p>The new setup is essentially this:</p>
<ul>
<li>I have one local clone of <a href="http://hg.mozilla.org/integration/mozilla-inbound/">mozilla-inbound</a> in <code>~/moz/.clean-base</code> which I never develop against or build against, and never modify except by updating it.</li>
<li>Whenever I want a mozilla-inbound tree, I clone <code>~/moz/.clean-base</code>.  I change the <code>default-push</code> entry in the new clone to point to the original mozilla-inbound.  (I don&#8217;t change the <code>default</code> entry; pulling is entirely local.)</li>
<li>If I want to push a patch, I pull and update <code>~/moz/.clean-base</code>.  Then I pull and update the local clone that has the patch I want to push.  Then I finish my patch and push it.  Because <code>default-push</code> points to the remote mozilla-inbound, <code>hg push</code> as usual does exactly what I want.</li>
</ul>
<h2>Advantages</h2>
<p>This setup has many advantages:</p>
<ul>
<li>Getting a new mozilla-inbound tree is fast.  I never clone the remote mozilla-inbound tree, because I have it locally.  It&#8217;s not modified by a patch queue where I&#8217;d have to temporarily checkpoint work, pop to clone, then reapply after.</li>
<li>Updating a working mozilla-inbound tree is fast.  Pulling and updating are completely local with no network delay.</li>
<li>I only need to update from the remote mozilla-inbound once for new changes to be available for all local trees.  Instead of separately updating my SpiderMonkey shell tree, updating my browser tree, and updating any other trees I&#8217;m using, at substantial cost in time, one pull in <code>~/moz/.clean-base</code> benefits all trees.</li>
<li>My working trees substantially share storage with <code>~/moz/.clean-base</code>.</li>
</ul>
<h2>Pitfalls, and workarounds</h2>
<p>Of course any setup has down sides.  I&#8217;ve noticed these so far:</p>
<ul>
<li>Updating a working trees is a two-step process: first updating <code>~/moz/.clean-base</code>, then updating the actual tree.</li>
<li>I&#8217;ll almost always lose a push race to mozilla-inbound.  If my local working tree is perfectly up-to-date with my <code>~/moz/.clean-base</code>, that&#8217;s generally not up-to-date with the remote tree, particularly as rebasing my patches is now a two-step process.  That produces a larger window of time for others to push things after I&#8217;ve updated my clean tree but before I&#8217;ve rebased my working tree.</li>
<li>I have to remember to edit the <code>default-push</code> in new trees, lest I accidentally mutate <code>~/moz/.clean-base</code>.</li>
</ul>
<p>Some of these problems are indeed annoying, but I&#8217;ve found substantial workarounds for them such that I no longer consider them limitations.</p>
<h3>Automate updating <code>~/moz/.clean-base</code></h3>
<p>Updating is only a two-step process if I update <code>~/moz/.clean-base</code> manually, but it&#8217;s easy to automate this with a cronjob.  With frequent updates <code>~/moz/.clean-base</code> is all but identical to the canonical mozilla-inbound.  And by making updates automatic, I also lose push races much less frequently (particularly if I rebase and push right after a regular update).</p>
<p>I&#8217;ve added this line to my crontab using <code>crontab -e</code> to update <code>~/moz/.clean-base</code> every twenty minutes from 07:00-01:00 every day but Sunday (this being when I might want an up-to-date tree):</p>
<pre class="code" data-language="cron">
*/20 00-01,07-23 * * 1-6 /home/jwalden/moz/inflight/pull-updated-inbound &gt;/dev/null 2&gt;&amp;1
</pre>
<p>I perform the update in a script, piping all output to <code>/dev/null</code> so that cron won&#8217;t mail me the output after every update.  It seems better to have a simpler crontab entry, so I put the actual commands in <code>/home/jwalden/moz/inflight/pull-updated-inbound</code>:</p>
<pre class="code" data-language="bash">
#!/bin/bash

cd ~/moz/.clean-base/
hg pull -u
</pre>
<p>With these changes in place, updating a working tree costs only the time required to rebase it: network delay doesn&#8217;t exist.  And the intermediate tree doesn&#8217;t intrude on my normal workflow.</p>
<h3>Add a hook to <code>~/moz/.clean-base</code> to prevent inadvertent pushes</h3>
<p>My setup depends on <code>~/moz/.clean-base</code> being clean.  Local changes or commits will break automatic updates and might corrupt my working trees.  I want <code>~/moz/.clean-base</code> to only change through pulls.</p>
<p>I can enforce this using a Mercurial <a href="http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html"><code>prechangegroup</code></a> hook.  This hook, run when a repository is about to accept a group of changes, can gate changes before they&#8217;re added to a tree.  I use such a hook to prevent any changes except by a push by adding these lines to <code>~/moz/.clean-base/.hg/hgrc</code>:</p>
<pre class="code">
# Prevent pushing into local mozilla-inbound clone: only push after changing a clone's default-push.
[hooks]
prechangegroup.prevent_pushes = python:prevent_pushes.prevent_pushes.hook
</pre>
<p>This invokes the <code>hook</code> function in <code>prevent_pushes.py</code>:</p>
<pre class="code" data-language="python">
#!/usr/bin/python

def hook(ui, repo, **kwargs):
  source = kwargs['source']
  if source != 'pull':
    print "Changes pushed into non-writable repository!  Only pulls permitted."
    return 1
  print "Updating pristine mozilla-inbound copy..."
  return 0
</pre>
<p>On my Fedora-based system, I place this file in <code>/usr/lib/python2.7/site-packages/prevent_pushes/</code> beside an empty <code>__init__.py</code>.  Mercurial will find it and invoke the hook whenever <code>~/moz/.clean-base</code> receives changesets.</p>
<p>Only pushing from a new clone without a <code>default-push</code> would attempt to modify <code>~/moz/.clean-base</code>, so the need to prevent changes to <code>~/moz/.clean-base</code> might seem small.  Yet so far this hook has prevented such changes more than once when I&#8217;ve forgotten to set a <code>default-push</code>, and I expect it will again.</p>
<h2>Conclusion</h2>
<p>There are doubtless many good ways to organize Mozilla work.  I find this system works well for me, and I hope this description of it provides ideas for others to incorporate into their own setups.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/03/how-i-organize-my-mozilla-trees/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Properly resizing vector image backgrounds</title>
		<link>http://whereswalden.com/2011/10/21/properly-resizing-vector-image-backgrounds/</link>
		<comments>http://whereswalden.com/2011/10/21/properly-resizing-vector-image-backgrounds/#comments</comments>
		<pubDate>Sat, 22 Oct 2011 03:43:56 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[background-size]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[gecko]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[svg]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3292</guid>
		<description><![CDATA[Resizing backgrounds in CSS The CSS background-image property allows web developers to add backgrounds to parts of pages, but only at their original sizes. CSS 3 added background-size to resize background images, and I implemented it in Gecko. But I couldn&#8217;t implement it for SVG backgrounds, because Gecko didn&#8217;t support them. When support arrived, nobody [...]]]></description>
			<content:encoded><![CDATA[<style type="text/css" scoped="scoped">
    .vector-background-test
    {
      display: inline-block;
      margin: 1em;
      /*background-color: white; color: black;*/
    }
  .vector-background-test figcaption { font-family: monospace; }
  .vector-background-test img
  {
    display: block; margin: 0 auto;
  }
</style>
<h2>Resizing backgrounds in <abbr title="Cascading stylesheet">CSS</abbr></h2>
<p>The CSS <a href="https://developer.mozilla.org/en/CSS/background-image"><code>background-image</code></a> property allows web developers to add backgrounds to parts of pages, but only at their original sizes.  CSS 3 added <code>background-size</code> to resize background images, and I <a href="https://developer.mozilla.org/web-tech/2009/08/04/background-images-no-longer-restricted-to-original-size-explore-the-space-with-background-size/">implemented it in Gecko</a>.  But I couldn&#8217;t implement it for <a href="https://developer.mozilla.org/en/SVG"><abbr title="Scalable Vector Graphics">SVG</abbr></a> backgrounds, because Gecko didn&#8217;t support them.  When <a href="http://blog.dholbert.org/2010/10/svg-as-image.html">support</a> arrived, nobody updated the background sizing algorithm for vector images&#8217; increased flexibility.  I&#8217;d hoped to prevent this omission by adding &#8220;canary&#8221; tests for <code>background-size</code>-modified SVG backgrounds.  But I miswrote the tests, so <code>background-size</code> wasn&#8217;t updated for SVG-in-CSS.</p>
<p>Since I&#8217;d inadvertently allowed this mess to happen, I felt somewhat obligated to <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=609714">fix it</a>.  Starting with Firefox 8, Firefox will properly render backgrounds which are vector images, at the appropriate size required by the corresponding <code>background-size</code>.  To the best of my knowledge Gecko is the first browser engine to properly render vector images in CSS backgrounds.</p>
<h2>How do images scale in backgrounds now?</h2>
<p><a href="http://hg.mozilla.org/mozilla-central/file/default/layout/reftests/backgrounds/vector">It&#8217;s complicated</a>: so complicated that to have any real confidence in complete correctness of a fix, I generated tests for the <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian product</a> of several different variables, then manually assigned an expected rendering to those 200-odd tests.  <a href="http://www.youtube.com/watch?v=aCbfMkh940Q">It was the only way to be sure</a> I&#8217;d implemented every last corner correctly.  (In case you&#8217;re wondering, these tests have been submitted to the <a href="http://hg.csswg.org/test/file/tip/contributors/mozilla/submitted/css3-background/background-size/vector/">CSS test suite</a> where they <a href="http://lists.w3.org/Archives/Public/public-css-testsuite/2011Sep/0026.html">await review</a>.  That should be <a href="http://www.youtube.com/watch?v=rX7wtNOkuHo">lots of fun</a>, I&#8217;m sure!)</p>
<p>Still, the algorithm can mostly (but not entirely!) be summarized by following a short list of rules:</p>
<ol>
<li>If <code>background-size</code> specifies a fixed dimension (percentages and relative units are fixed by context), that wins.</li>
<li>If the image has an intrinsic ratio (its width-height ratio is constant &mdash; 16:9, 4:3, 2.39:1, 1:1, <abbr title="et cetera" lang="la">&amp;c.</abbr>), the rendered size preserves that ratio.</li>
<li>If the image specifies a size and isn&#8217;t modified by <code>contain</code> or <code>cover</code>, that size wins.</li>
<li>With no other information, the rendered size is the corresponding size of the background area.</li>
</ol>
<p>Note that sizing only cares about the image&#8217;s dimensions and proportions, or lack thereof.  A vector-based image with fixed dimensions will be treated identically to a pixel-based image of the same size.</p>
<p>Subsequent examples use the following highly-artistic images:</p>
<table class="border-1">
<tr>
<th>File name</th>
<th>Image (at 150&#215;150)</th>
<th>Description</th>
</tr>
<tr>
<td><a href="http://whereswalden.com/files/mozilla/background-size/vector/no-dimensions-or-ratio.svg"><code>no-dimensions-or-ratio.svg</code></a></td>
<td><img src="http://whereswalden.com/files/mozilla/background-size/vector/no-dimensions-or-ratio.png" alt="Image containing corner-to-corner gradient, no width, height, or intrinsic ratio" /></td>
<td>This image is dimensionless and proportionless: think of it like a gradient desktop background that you could use on a 1024&#215;768 screen as readily as on a 1920&#215;1080 screen.</td>
</tr>
<tr>
<td><a href="http://whereswalden.com/files/mozilla/background-size/vector/100px-wide-no-height-or-ratio.svg"><code>100px-wide-no-height-or-ratio.svg</code></a></td>
<td><img src="http://whereswalden.com/files/mozilla/background-size/vector/100px-wide-no-height-or-ratio.png" alt="Image containing a vertical gradient, 100 pixel width and of indeterminate height, with no intrinsic ratio" /></td>
<td>This image is 100 pixels wide but has no height or intrinsic ratio.  Imagine it as a thin strip of wallpaper that could be stretched the entire height of a webpage.</td>
</tr>
<tr>
<td><a href="http://whereswalden.com/files/mozilla/background-size/vector/100px-height-3x4-ratio.svg"><code>100px-height-3x4-ratio.svg</code></a></td>
<td><img src="http://whereswalden.com/files/mozilla/background-size/vector/100px-height-3x4-ratio.png" alt="Image containing a vertical gradient, 100 pixel height and of indeterminate width, with a width/height intrinsic ratio of 3:4" /></td>
<td>This image is 100 pixels high but lacks a width, and it has an intrinsic ratio of 3:4.  The ratio ensures that its width:height ratio is always 3:4, unless it&#8217;s deliberately scaled to a disproportionate size.  (One dimension and an intrinsic ratio is really no different from two dimensions, but it&#8217;s still useful as an example.)</td>
</tr>
<tr>
<td><a href="http://whereswalden.com/files/mozilla/background-size/vector/no-dimensions-1x1-ratio.svg"><code>no-dimensions-1x1-ratio.svg</code></a></td>
<td><img src="http://whereswalden.com/files/mozilla/background-size/vector/no-dimensions-1x1-ratio.png" alt="Square image with indeterminate width and height, containing a horizontal gradient" /></td>
<td>This image has no width or height, but it has an intrinsic ratio of 1:1.  Think of it as a program icon: always square, just as usable at 32&#215;32 or 128&#215;128 or 512&#215;512.</td>
</tr>
</table>
<p>In the examples below, all enclosing rectangles are 300 pixels wide and 200 pixels tall.  Also, all backgrounds have <code>background-repeat: no-repeat</code> for easier understanding.  Note that the demos below are all the <em>expected</em> rendering, not the actual rendering in your browser.  See how your browser actually does on <a href="http://whereswalden.com/files/mozilla/background-size/vector/demo.html">this demo page</a>, and <a href="http://www.mozilla.org/en-US/firefox/channel/">download an Aurora or Beta build</a> (or even <a href="http://nightly.mozilla.org/">a nightly</a>) to see the demo rendered correctly.</p>
<p>Now consider the rules while moving through these questions to address all possible <code>background-size</code> values.</p>
<h3>Does the <code>background-size</code> specify fixed lengths for both dimensions?</h3>
<p>Per rule 1, fixed lengths always win, so we always use them.</p>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/lengths/no-dimensions-or-ratio.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-or-ratio.svg);</code><br />
      <code>background-size: 125px 175px;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/lengths/100px-wide-no-height-or-ratio.png" /></p>
<figcaption>
      <code>background: url(100px-wide-no-height-or-ratio.svg);</code><br />
      <code>background-size: 250px 150px;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/lengths/100px-height-3x4-ratio.png" /></p>
<figcaption>
      <code>background: url(100px-height-3x4-ratio.svg);</code><br />
      <code>background-size: 275px 125px;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/lengths/no-dimensions-1x1-ratio.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-1x1-ratio.svg);</code><br />
      <code>background-size: 250px 100px;</code><br />
    </figcaption>
</figure>
<h3>Is the <code>background-size</code> <code>contain</code> or <code>cover</code>?</h3>
<p><code>cover</code> makes the picture <em>as small as possible</em> to cover the background area.  <code>contain</code> makes the picture <em>as large as possible</em> while still fitting in the background area.  For an image with an intrinsic ratio, exactly one size matches the cover/fit criteria alone.  But for a vector image lacking an intrinsic ratio, cover/fit is insufficient, so the large/small constraints choose the resulting rendered size.</p>
<p>Rule 1 is irrelevant, so try rule 2: preserve any intrinsic ratio (while respecting <code>contain</code>/<code>cover</code>).  Preserving a 3:4 intrinsic ratio for a 300&#215;200 box with <code>contain</code>, for example, means drawing a 150&#215;200 background.</p>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/cc/100px-height-3x4-ratio-contain.png" /></p>
<figcaption>
      <code>background: url(100px-height-3x4-ratio.svg);</code><br />
      <code>background-size: contain;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/cc/100px-height-3x4-ratio-cover.png" /></p>
<figcaption>
      <code>background: url(100px-height-3x4-ratio.svg);</code><br />
      <code>background-size: cover;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/cc/no-dimensions-1x1-ratio-contain.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-1x1-ratio.svg);</code><br />
      <code>background-size: contain;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/cc/no-dimensions-1x1-ratio-cover.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-1x1-ratio.svg);</code><br />
      <code>background-size: cover;</code><br />
    </figcaption>
</figure>
<p>Rule 3 is irrelevant, so if there&#8217;s no intrinsic ratio, then per rule 4, the background image covers the entire background area, satisfying the largest-or-smallest constraint.</p>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/cc/no-dimensions-or-ratio-contain.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-or-ratio.svg);</code><br />
      <code>background-size: contain;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/cc/100px-wide-no-height-or-ratio-contain.png" /></p>
<figcaption>
      <code>background: url(100px-wide-no-height-or-ratio.svg);</code><br />
      <code>background-size: contain;</code><br />
    </figcaption>
</figure>
<h3>Is the <code>background-size</code> <code>auto</code> or <code>auto auto</code>?</h3>
<p>Per rule 2, rendering must preserve any intrinsic ratio.</p>
<p>If we have an intrinsic ratio, any dimension (or both) fixes the other, and we&#8217;re done.  If we have an intrinsic ratio but no dimensions, then per rule 4, we use the background area &mdash; but see rule 2!  To preserve the intrinsic ratio, the image is rendered as if for <code>contain</code>.</p>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/auto-auto/100px-height-3x4-ratio.png" /></p>
<figcaption>
      <code>background: url(100px-height-3x4-ratio.svg);</code><br />
      <code>background-size: auto auto;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/auto-auto/no-dimensions-1x1-ratio.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-1x1-ratio.svg);</code><br />
      <code>background-size: auto auto;</code><br />
    </figcaption>
</figure>
<p>If we have no intrinsic ratio, then per rule 3, we use the image&#8217;s dimension if available, and per rule 4, the corresponding background area dimension if not.</p>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/auto-auto/no-dimensions-or-ratio.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-or-ratio.svg);</code><br />
      <code>background-size: auto auto;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/auto-auto/100px-wide-no-height-or-ratio.png" /></p>
<figcaption>
      <code>background: url(100px-wide-no-height-or-ratio.svg);</code><br />
      <code>background-size: auto auto;</code><br />
    </figcaption>
</figure>
<h3>The <code>background-size</code> is one <code>auto</code> and one length.</h3>
<p>Per rule 1 we use the specified dimension, so we have one dimension to determine.</p>
<p>If we have an intrinsic ratio, rule 2 plus the specified dimension determines rendering size.</p>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/length-auto/100px-height-3x4-ratio.png" /></p>
<figcaption>
      <code>background: url(100px-height-3x4-ratio.svg);</code><br />
      <code>background-size: 150px auto;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/length-auto/no-dimensions-1x1-ratio.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-1x1-ratio.svg);</code><br />
      <code>background-size: 150px auto;</code><br />
    </figcaption>
</figure>
<p>Otherwise, per rule 3 we consult the image, using the image&#8217;s dimension if it has it.  If it doesn&#8217;t, per rule 4, we use the background area&#8217;s dimension.  Either way, we have our rendered size.</p>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/length-auto/no-dimensions-or-ratio.png" /></p>
<figcaption>
      <code>background: url(no-dimensions-or-ratio.svg);</code><br />
      <code>background-size: auto 150px;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/length-auto/100px-wide-no-height-or-ratio-length-auto.png" /></p>
<figcaption>
      <code>background: url(100px-wide-no-height-or-ratio.svg);</code><br />
      <code>background-size: 200px auto;</code><br />
    </figcaption>
</figure>
<figure class="vector-background-test">
<p><img width="304" height="204" src="http://whereswalden.com/files/mozilla/background-size/vector/length-auto/100px-wide-no-height-or-ratio-auto-length.png" /></p>
<figcaption>
      <code>background: url(100px-wide-no-height-or-ratio.svg);</code><br />
      <code>background-size: auto 125px;</code><br />
    </figcaption>
</figure>
<h2>Whee, that&#8217;s a mouthful!</h2>
<p>Yes.  Yes it is.  (Two hundred tests, remember?)  But it&#8217;s shiny!</p>
<h2>Anything else to know?</h2>
<p>In rewriting the sizing algorithm, I was confronted with the problem of how to resize CSS gradients (distinct from gradients embedded in SVG images), which CSS treats as an image subtype.</p>
<p>Our previous sizing algorithm happened to treat gradients as if they were a special image type which magically inherited the intrinsic ratio of their context.  Thus if the background were resized with a single length, the gradient would paint over a proportional part of the background area.  Other resizing would simply expand them to cover the background area.</p>
<p><a href="http://dev.w3.org/csswg/css3-images/">CSS 3 Image Values</a> specifies the nature of the images represented by gradients: they have no dimensions and no intrinsic ratio.  Firefox 8 implements these semantics, which are a change from gradient rendering semantics in previous releases.  This will affect rendering only in the case where <code>background-size</code> is <code>auto &lt;length&gt;</code> or <code>&lt;length&gt; auto</code> (and equivalently, simply <code>&lt;length&gt;</code>).  Thus if you wish to resize a gradient background, you should not use a length in concert with <code>auto</code> to do so, because in that case rendering will vary across browsers.</p>
<h2>Conclusion</h2>
<p>SVG background images have now become more powerful than you can possibly imagine.  If the SVG has fixed dimensions, it&#8217;ll work like any raster image.  But SVG goes beyond this: if an SVG image only has partial fixed dimensions, the final rendering will respect that partial dimension information.  Proportioned images will remain proportioned (unless you force them out of proportion); they won&#8217;t be disproportionally stretched just because the background area has particular dimensions.  Images with a dimension but no intrinsic ratio will have the dimension used when the background is <code>auto</code>-sized, rather than simply have it be ignored.  These aren&#8217;t just bugfixes: they&#8217;re new functionality for the web developer&#8217;s toolbox.</p>
<p>Now go out and make better shiny with this than I have.  <img src='http://whereswalden.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/10/21/properly-resizing-vector-image-backgrounds/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Implementing mozilla::ArrayLength and mozilla::ArrayEnd, and some followup work</title>
		<link>http://whereswalden.com/2011/10/20/implementing-mozillaarraylength-and-mozillaarrayend-and-some-followup-work/</link>
		<comments>http://whereswalden.com/2011/10/20/implementing-mozillaarraylength-and-mozillaarrayend-and-some-followup-work/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 23:03:28 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[arrayend]]></category>
		<category><![CDATA[arraylength]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[help wanted]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3319</guid>
		<description><![CDATA[In my last post I announced the addition of mozilla::ArrayLength and mozilla::ArrayEnd to the Mozilla Framework Based on Templates, and I noted I was leaving a description of how these methods were implemented to a followup post. This is that post. The C++ template trick used to implement mozilla::ArrayLength The implementations of these methods are [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://whereswalden.com/2011/10/20/computing-the-length-or-end-of-a-compile-time-constant-length-array-jsns_array_endlength-are-out-mozillaarraylengthend-are-in/">my last post</a> I announced the addition of <code>mozilla::ArrayLength</code> and <code>mozilla::ArrayEnd</code> to the Mozilla Framework Based on Templates, and I noted I was leaving a description of how these methods were implemented to a followup post.  This is that post.</p>
<h2>The C++ template trick used to implement <code>mozilla::ArrayLength</code></h2>
<p>The implementations of these methods are surprisingly simple:</p>
<pre class="code" data-language="c++">
template&lt;typename T, size_t N&gt;
size_t
ArrayLength(T (&#038;arr)[N])
{
  return N;
}

template&lt;typename T, size_t N&gt;
T*
ArrayEnd(T (&#038;arr)[N])
{
  return arr + ArrayLength(arr);
}
</pre>
<p>The trick is this: you can templatize an array based on its compile-time length.  Here we templatize both methods on: the type of the elements of the array, so that each is polymorphic; and the number of elements in the array.  Then inside the method we can refer to that length, a constant known at compile time, and simply return it to implement the desired semantics.</p>
<p>Templatizing on the length of an array may not seem too unusual.  The part that may be a little unfamiliar is how the array is described as a parameter of the template method: <code>T (&#038;arr)[N]</code>.  This declares the argument to be a <dfn>reference</dfn> to an array of <var>N</var> elements of type <var>T</var>.  Its being a reference is important: we don&#8217;t actually care about the array contents at all, and we don&#8217;t want to copy them to call the method.  All we care about is its type, which we can capture without further cost using a reference.</p>
<p>This technique is uncommon, but it&#8217;s not new to Mozilla.  Perhaps you&#8217;ve wondered at some point why Mozilla&#8217;s string classes have both <a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/xpcom/string/public/nsTSubstring.h#l282"><code>EqualsLiteral</code></a> and <a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/xpcom/string/public/nsTSubstring.h#l269"><code>EqualsASCII</code></a>: the former for use only when comparing to &#8220;an actual literal string&#8221;, the latter for use when comparing to any <code>const char*</code>.  You can probably guess why this interface occurs now: <code>EqualsLiteral</code> is a method templatized on the length of the actual literal string passed to it.  It can be more efficient than <code>EqualsASCII</code> because it knows the length of the compared string.</p>
<h2>Using this trick in other code</h2>
<p>I did most of the work to convert <code>NS_ARRAY_LENGTH</code> to <code>ArrayLength</code> with a script.  But I still had to look over the results of the script to make sure things were sane before proceeding with it.  In doing so, I noticed a decent number of places where an array was created, then it and its length were being passed as arguments to another method.  For example:</p>
<pre class="code" data-language="c++">
void nsHtml5Atoms::AddRefAtoms()
{
  NS_RegisterStaticAtoms(Html5Atoms_info, ArrayLength(Html5Atoms_info));
}
</pre>
<p>Using <code>ArrayLength</code> here is safer than hard-coding a length.  But safer still would be to not require callers to pass an array and a length separately &mdash; rather to pass them together.  We can do this by pushing the template trick down another level, into <a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/xpcom/ds/nsAtomTable.cpp#l422"><code>NS_RegisterStaticAtoms</code></a> (or at least into an internal method used everywhere, if the external <abbr title="application programming interface">API</abbr> must be preserved for some reason):</p>
<pre class="code" data-language="c++">
static nsresult
RegisterStaticAtoms(const nsStaticAtom* aAtoms, PRUint32 aAtomCount)
{
  // ...old implementation...
}

template&lt;size_t N&gt;
nsresult
NS_RegisterStaticAtoms(const nsStaticAtom (&#038;aAtoms)[N])
{
  return RegisterStaticAtoms(aAtoms, N);
}
</pre>
<p>The pointer-and-length method generally still needs to stick around somewhere, and it does in this rewrite here.  It&#8217;s just that it wouldn&#8217;t be the interface user code would see, or it wouldn&#8217;t be the primary interface (for example, it might be <code>protected</code> or similar).</p>
<p><code>NS_RegisterStaticAtoms</code> was just one such method which could use improvement.  In a quick skim I also see:</p>
<ul>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/storage/test/test_asyncStatementExecution_transaction.cpp#l30"><code>check_transaction</code></a> in storage tests,
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/js/src/jsinterp.cpp#l655"><code>js::Invoke</code></a> and <a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/js/src/jscntxt.h#l1547"><code>js::AutoArrayRooter</code></a> in SpiderMonkey code,</li>
<li><a href="http://mxr.mozilla.org/mozilla-central/source/content/base/public/nsContentUtils.h#816"><code>nsContentUtils::FormatLocalizedString</code></a>,</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/gfx/thebes/gfxTeeSurface.cpp#l47"><code>gfxTeeSurface</code></a>,</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/xpcom/glue/nsTArray.h#l827"><code>nsTArray::AppendElements</code></a>,</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/xpcom/tests/TestTArray.cpp#l66"><code>test_basic_array</code></a> in <code>nsTArray</code> test code,</li>
<li><em>potentially</em> <a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/layout/generic/TextOverflow.cpp#l71"><code>nsDependentString::nsDependentString</code></a> if a couple places I noted (and just linked) are any guide,</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/layout/style/nsCSSScanner.h#l165"><code>nsCSSScanner::ReportUnexpectedParams</code></a>,</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/layout/base/nsCSSFrameConstructor.cpp#l3398"><code>nsCSSFrameConstructor::FindDataByInt</code></a>,</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/content/base/public/nsContentUtils.h#l736"><code>nsContentUtils::ReportToConsole</code></a>,</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/content/base/src/nsGenericElement.cpp#l3423"><code>nsGenericElement::FindAttributeDependence</code></a> (this one&#8217;s responsible for something like a fifth of <em>all</em> uses of <code>ArrayLength</code>!),</li>
<li>a bunch of <code>struct</code>s in <code>nsSVGElement</code>, and</li>
<li><a href="http://hg.mozilla.org/mozilla-central/annotate/6cd262091470/xpcom/string/public/nsTString.h#l421"><code>nsFixedString::nsFixedString</code></a></li>
</ul>
<p>&#8230;as potential spots that could be improved &mdash; at least for some callers &mdash; with some additional templatization on array length.</p>
<p>I didn&#8217;t look super-closely at these, so I might have missed some.  Or I might have been over-generous in what could be rewritten to templatize on length, seeing only the one or two places that pass fixed lengths and missing the majority of cases that don&#8217;t.  But there&#8217;s definitely a lot of cleaning that could be done here.</p>
<h2>A call for help</h2>
<p>Passing arrays and lengths separately is dangerous if you don&#8217;t know what you&#8217;re doing.  The trick used here eliminates it, in certain cases.  The more we can use this pattern, the more we can fundamentally reduce the danger of separating data from its length.</p>
<p>I don&#8217;t have time to do the above work myself.  (I barely had time to do the <code>ArrayLength</code> work, really.  I only did it because I&#8217;d sort of started the ball rolling in a separate bug, so I felt some obligation to make sure it got done.)  And it&#8217;s not particularly hard work, requiring especial knowledge of the relevant code.  It&#8217;s a better use of my time for me to work on JavaScript engine code, or on other code I know particularly well, than to do this work.  But for someone interested in getting started working on Gecko C++ code, it would be a good first project.  I&#8217;ve filed <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=696242">bug 696242</a> for this task; if anyone&#8217;s interested in a good first bug for getting into Mozilla C++ coding, feel free to start with that one.  If you have questions about what to do, in any way, feel free to ask them there.</p>
<p>On the other hand, if you have any questions about the technique in question, or the way it&#8217;s used in Mozilla, feel free to ask them here.  But if you want to contribute to fixing the issues I&#8217;ve noted, let&#8217;s keep them to the bug, if possible.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/10/20/implementing-mozillaarraylength-and-mozillaarrayend-and-some-followup-work/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

