<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
 <title>Danrich Parrol's Blog</title>
 <description>Thoughts, mostly about technology</description>
 <link>https://dparrol.github.io/</link>
 <lastBuildDate>Sun, 04 Jan 2015 16:15:14 </lastBuildDate>
 <pubDate>Sun, 04 Jan 2015 16:15:14 </pubDate>
 <language>en-US</language>
 
 <item>
  <title>Trivial caching with a simplified hash table</title>
  <description><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Hash_table">Hash tables</a> are pretty simple: <a href="https://en.wikipedia.org/wiki/Hash_function">hash</a> your key to get an array index to look in for the value, and handle collisions... somehow. Most of the complexity comes from how you handle hash collisions. Now suppose that you handle them <em>by not handling them:</em> when you're trying to write to the hash table, just overwrite anything that's already there. This will give you a <a href="https://en.wikipedia.org/wiki/Cache_%28computing%29">cache</a>: you put things in, but they might disappear. Newer things will tend to replace older ones.</p>
<p>I love how simple this is. The usual way of making a cache in memory is to keep a doubly linked list of the items in the cache in order of how recently they were used, have a hash table pointing to them, and do a bunch of twiddling to make sure that when the cache fills up, the least recently used item is evicted first. That's fine, but it's got a fair bit of overhead, and it's not <em>trivial</em> the way the hash table thing is.</p>
<p>Let's write some code. I'll use C, the lingua franca of people whose concern for optimization is excessive but not quite obsessive. First let's define some data types:</p>
<div class="codehilite"><pre><span class="c1">// Keys and values in the cache are both strings. You could use</span>
<span class="c1">// whatever you want, but let&#39;s keep it simple for now.</span>
<span class="k">typedef</span> <span class="kt">char</span><span class="o">*</span> <span class="kt">key_t</span><span class="p">;</span>
<span class="k">typedef</span> <span class="kt">char</span><span class="o">*</span> <span class="kt">value_t</span><span class="p">;</span>
<span class="c1">// A cache is just an array of slots where we can put values.</span>
<span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="kt">key_t</span> <span class="n">key</span><span class="p">;</span> 
    <span class="kt">value_t</span> <span class="n">value</span><span class="p">;</span>
<span class="p">}</span> <span class="kt">cache_entry_t</span><span class="p">;</span>
<span class="k">typedef</span> <span class="kt">cache_entry_t</span><span class="o">*</span> <span class="kt">cache_t</span><span class="p">;</span>
</pre></div>


<p>Making a cache just requires allocating some memory to hold it, and making sure it's initially blank:</p>
<div class="codehilite"><pre><span class="cp">#define CACHE_SIZE 128</span>
<span class="kt">cache_t</span> <span class="nf">cacheCreate</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="n">calloc</span><span class="p">(</span><span class="n">CACHE_SIZE</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">cache_entry_t</span><span class="p">));</span>
<span class="p">}</span>
</pre></div>


<p>To insert a key-value pair into the cache, hash your key and put it in there.</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="nf">cacheInsert</span><span class="p">(</span><span class="kt">cache_t</span> <span class="n">cache</span><span class="p">,</span> <span class="kt">key_t</span> <span class="n">key</span><span class="p">,</span> <span class="kt">value_t</span> <span class="n">value</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">hash</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="o">%</span> <span class="n">CACHE_SIZE</span><span class="p">;</span> <span class="c1">// Get position in cache</span>
    <span class="n">free</span><span class="p">(</span><span class="n">cache</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">key</span><span class="p">);</span>             <span class="c1">// Evict anything already there</span>
    <span class="n">free</span><span class="p">(</span><span class="n">cache</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">value</span><span class="p">);</span>
    <span class="n">cache</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">key</span> <span class="o">=</span> <span class="n">key</span><span class="p">;</span>             <span class="c1">// Put new value in place</span>
    <span class="n">cache</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>


<p>To look up something, it's just like a hash table lookup except without any collision handling:</p>
<div class="codehilite"><pre><span class="kt">value_t</span> <span class="nf">cacheGet</span><span class="p">(</span><span class="kt">cache_t</span> <span class="n">cache</span><span class="p">,</span> <span class="kt">key_t</span> <span class="n">key</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">hash</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="o">%</span> <span class="n">CACHE_SIZE</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">cache</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">key</span> <span class="o">&amp;&amp;</span> <span class="n">keys_equal</span><span class="p">(</span><span class="n">cache</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">key</span><span class="p">,</span> <span class="n">key</span><span class="p">))</span> <span class="p">{</span>
        <span class="k">return</span> <span class="n">cache</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">value</span><span class="p">;</span>  <span class="c1">// We found the key! :-D</span>
    <span class="p">}</span> 
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>                <span class="c1">// We didn&#39;t find the key. :-(</span>
<span class="p">}</span>
</pre></div>


<p>There you have it: an in-memory cache, with negligible overhead, in just a few lines of simple code. Fun, right?</p>
<p>(Want complete, runnable code? <a href="https://github.com/dparrol/hashcache">Here's a repo.</a>)</p>]]></description>
  <link>https://dparrol.github.io/trivial-cache.html</link>
  <guid isPermaLink="true">https://dparrol.github.io/trivial-cache.html</guid>
  <pubDate>Thu, 01 Jan 2015 00:00:00 </pubDate>
 </item>
 
 <item>
  <title>Unicode strings: you probably don't want random indexing by code point</title>
  <description><![CDATA[<p>Whenever the topic of Unicode string encoding comes up, someone always disparages variable-width encodings like UTF-8 and UTF-16, saying that it's important to be able to get the nth code point in constant time. <em>This is almost never what you really want,</em> and people should stop saying this unless they have very exotic needs. A lot of what I'm going to say here will be pretty obvious to the folks who are experienced with Unicode string handling, so if you're one of them then please forgive me for belaboring a point – there are a lot of misconceptions going around.</p>
<h2>A quick review of how Unicode works</h2>
<p>Unicode represents text in various human languages, like "dog" or "陽明山國家公園", or even "(╯°□°）╯︵ ┻━┻". The symbols that you see, like "d" or "한" or "ȃ͜͡", are called <a href="http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries">grapheme clusters</a>, because they're made up of one or more graphemes – the components that you see, like the letter a and the circle over it in "å".</p>
<p>Grapheme clusters are represented as sequences of one or more <a href="http://en.wikipedia.org/wiki/Code_point">code points</a>. These correspond to things like the letters "a" and "ξ", or to more obscure things like <a href="http://en.wikipedia.org/wiki/Combining_character">combining characters</a> – for instance, if you stick a <a href="http://www.fileformat.info/info/unicode/char/0301/index.htm">combining acute accent (code point U+0301)</a> after a <a href="http://www.fileformat.info/info/unicode/char/0065/index.htm">lowercase e (code point U+0065)</a>, then it looks like "é". Incidentally, Unicode also happens to have a <a href="http://www.fileformat.info/info/unicode/char/e9/index.htm">code point U+00E9</a> that looks exactly the same: é. These are the same grapheme cluster as far as human eyes are concerned, and users will perceive them both exactly the same, and if the user types in one of those and presses backspace then the grapheme cluster should be deleted whether it's one code point or two. And if the user asks how many characters there are in "kamelåså", then the answer should be 8, even if those å graphemes happen to have more than one code point in them.</p>
<p>Finally, the Unicode code points in the text are represented as bytes using some encoding. The simplest, <a href="http://en.wikipedia.org/wiki/UTF-32">UTF-32</a>, just represents each code point as a 32-bit integer. My favorite, <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a>, uses a variable-width encoding to represent each code point using a sequence of 1-4 bytes. The strangely popular <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> is also variable-width, using either 2 or 4 bytes.</p>
<h2>Let's look at some common tasks</h2>
<p>Suppose that you find yourself with a string containing a bunch of people's names, separated by newlines. Like this:</p>
<div class="codehilite"><pre>Catherine the Great
藤原定家
Thorin II Oakenshield, son of Thráin, son of Thrór, King under the Mountain
Billy Danger
</pre></div>


<p>The first obvious thing you'd want to do with this is to split it – find the substrings, like "Catherine the Great", that contain the individual names. You can do this by going through the code points and splitting on line feeds, <a href="https://en.wikipedia.org/wiki/Newline">U+000A</a> – our good old friend <code>'\n'</code>. So far, easy.</p>
<p>Another thing you could do is a substring search; maybe the user wants to locate the string "Thrór". At this point things get trickier – you'll probably want to treat the one-code-point and two-code-point representations of the letter ó as equivalent. There are Unicode text-handling libraries that handle this sort of thing, though, so assume you've got one. The substring search will tell you that "Thrór" starts at code point 70 (or 71, depending on how the á in Thráin is represented), or at UTF-8 byte position 79, or at UTF-16 offset 71. Notice that if you have the byte position in an encoded representation of the string, you can index by <em>that</em> in constant time, no matter how variable-width the encoding might be.</p>
<p>The same thing applies to stuff like regular expression searches. Suppose you want to find all those "son of X" things with the regular expression <code>/son of (\S+)/</code>. Your regular expression matcher can iterate over the string by code point – easy, no matter what encoding you're using – and keep track of the byte offsets for its matches. It'll find its first match, "Thráin,", at code points 55-63, or UTF-8 byte positions 63-72. Grabbing this substring from the match location is easy and fast – just remember where the match was in the encoded representation, rather than where it was in the sequence of code points.</p>
<p>For our final act, let's count characters – or more precisely, grapheme clusters. "Catherine" is 9 characters, and 9 code points, and 9 bytes in UTF-8. "藤原定家" is 4 characters, and 4 code points, and 12 bytes in UTF-8. "Thráin" is 6 characters, and 6 or 7 code points (depending on how you represent the á), and 6 or 7 bytes in UTF-8. If you assume that the number of code points is the same as the number of characters, then you'll sometimes be wrong.</p>
<h2>What do <em>you</em> need to do with Unicode strings?</h2>
<p>I can't really think of any task for which constant-time string indexing by Unicode code point would be helpful. People use this as an argument against variable-width text encodings <em>all the time,</em> but it just doesn't seem that important.</p>
<p>(P.S.: If you really, <em>really</em> need fast indexing by <a href="http://www.unicode.org/reports/tr29/">any form of text segmentation</a> on potentially very large strings, you can make this (and almost every other conceivable string operation) decently fast using some sort of augmented B+ tree with gap buffers at the leaves. Probably unnecessary, but it could be fun to write.)</p>]]></description>
  <link>https://dparrol.github.io/unicode-random-indexing.html</link>
  <guid isPermaLink="true">https://dparrol.github.io/unicode-random-indexing.html</guid>
  <pubDate>Sun, 21 Dec 2014 00:00:00 </pubDate>
 </item>
 
 <item>
  <title>First post</title>
  <description><![CDATA[<p>This post was created to test the software I wrote to generate this blog. It is a placeholder, and should be ignored by all right-thinking people.</p>
<div class="codehilite"><pre><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="mi">2</span> <span class="o">+</span> <span class="s">&#39;foo&#39;</span>
</pre></div>]]></description>
  <link>https://dparrol.github.io/first-post.html</link>
  <guid isPermaLink="true">https://dparrol.github.io/first-post.html</guid>
  <pubDate>Sat, 20 Dec 2014 00:00:00 </pubDate>
 </item>
 
</channel>
</rss>