17.01.2015 Views

Erlang and OTP in Action.pdf - Synrc

Erlang and OTP in Action.pdf - Synrc

Erlang and OTP in Action.pdf - Synrc

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

324<br />

lookup(Key) -><br />

sc_event:lookup(Key),<br />

case sc_store:lookup(Key) of<br />

{ok, Pid} -><br />

decompress(sc_element:fetch(Pid)); #1<br />

{error, Reason} -><br />

{error, Reason}<br />

end.<br />

decompress(Data = {compressed, _, _, _}) -> #2<br />

lzjb:decompress(Data); #3<br />

decompress(Data) -><br />

Data. #4<br />

Fortunately, we know what compressed data looks like, so we can actually dispatch on that<br />

pattern. You can see that we do this <strong>in</strong> the head of the decompress function, (annotation #2)<br />

if it looks like compressed data we call lzjb:decompress on it (annotation #3), if it doesn’t we<br />

pass the data back unchanged (annotation #4). To actually use the decompress function,<br />

we call it on every piece of data returned from the cache (annotation #1).<br />

With that our long journey through the world of Drivers, both Port <strong>and</strong> L<strong>in</strong>ked <strong>in</strong>, is complete.<br />

We have a fully function<strong>in</strong>g compression <strong>and</strong> decompression system <strong>in</strong>tegrated <strong>in</strong>to the cache<br />

<strong>in</strong> a way that is very performant. We can have both uncompressed <strong>and</strong> compressed data<br />

mixed <strong>in</strong>to the cache without any problem <strong>and</strong> we have a compression <strong>OTP</strong> app that we can<br />

use whenever <strong>and</strong> wherever we need it.<br />

12.4 Summary<br />

In this chapter we looked at the two methods of communication with foreign code that is<br />

available to erlang. We also discussed the caveats of us<strong>in</strong>g each of these methods. The use<br />

of the Port Driver is, by far, the preferred solution from a safety st<strong>and</strong>po<strong>in</strong>t. However, <strong>in</strong><br />

some cases speed may be of the essence. In those cases it may be necessary to use a l<strong>in</strong>ked<br />

<strong>in</strong> driver. In either case, you now have the tools you need to create either style of <strong>in</strong>terface.<br />

©Mann<strong>in</strong>g Publications Co. Please post comments or corrections to the Author Onl<strong>in</strong>e forum:<br />

http://www.mann<strong>in</strong>g-s<strong>and</strong>box.com/forum.jspaforumID=454

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!