<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joseph Livni on Medium]]></title>
        <description><![CDATA[Stories by Joseph Livni on Medium]]></description>
        <link>https://medium.com/@j.d.livni?source=rss-d24b5a950413------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i1ibXaOq969MyS3rPO6gtw@2x.jpeg</url>
            <title>Stories by Joseph Livni on Medium</title>
            <link>https://medium.com/@j.d.livni?source=rss-d24b5a950413------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:33:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@j.d.livni/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Video Infra: How Millions of Video Streams get Delivered]]></title>
            <link>https://levelup.gitconnected.com/video-infra-how-millions-of-video-streams-get-delivered-e78c094deda3?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/e78c094deda3</guid>
            <category><![CDATA[fmp4]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[streaming-video]]></category>
            <category><![CDATA[video-delivery]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 01:04:15 GMT</pubDate>
            <atom:updated>2023-03-29T01:04:15.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fkj-MOBUBjwHkvHmB96SA.jpeg" /></figure><p>All of the largest video streaming services (eg: Youtube, Netflix, Twitch) have the same core problems when it comes to delivering video: supporting multiple video formats, providing the best experience over unreliable networks, and minimizing latency.</p><p>In this post, we’ll go over how a client (ie: smart phone, laptop, tv) finds the video it wants to stream, how unreliable networks are handled, and the various delivery protocols that are popular today.</p><h3>How do clients find the video?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1FnPDkhFZDgoU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1FnPDkhFZDgoU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F1FnPDkhFZDgoU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="235" frameborder="0" scrolling="no"><a href="https://medium.com/media/aad3f6b58d3e5cd41652117e9d98c34c/href">https://medium.com/media/aad3f6b58d3e5cd41652117e9d98c34c/href</a></iframe><p>Let&#39;s say you’re scrolling through Netflix and select the latest season of “Drive to Survive” (Note: I haven’t finished yet, so please no spoilers). The first thing that will happen before downloading can start is a request for the video manifest.</p><p>The Media Description Presentation (MPD) (aka the manifest) is an XML file that bridges the video ingest, processing, and delivery pipeline by listing the location of the video, audio, and related data for download via HTTP.</p><h4>MPD file Organization</h4><ul><li><strong>Period</strong>: an interval along the temporal axis that contains 1 or more Adaptation Sets.</li><li><strong>Adaptation Set</strong>: A media stream (eg: video, audio, or audio in another language) and contains 1 or more media Representations.</li><li><strong>Representation</strong>: A specific encoding of a media stream (eg: video could be encoded at 1Mbps, 2Mbps, and 5Mbps) and contains 1 or more segments.</li><li><strong>Segment</strong>: A media stream containing 1 or more chunks in a temporal sequence that provides a URI for HTTP download.</li><li><strong>Chunk</strong>: Contains 1 or more frames.</li><li><strong>Frame</strong>: In the case of video it’s a single image and in the case of audio it’s a sequence of audio samples over a period of time.</li></ul><h3>How is video data delivered?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZI8w9Llg5E64MRtzBg%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Fstudiosoriginals-teddy-too-big-ZI8w9Llg5E64MRtzBg&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2FZI8w9Llg5E64MRtzBg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="360" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e541a90d5694e1fc91e13ca70b91fc8/href">https://medium.com/media/4e541a90d5694e1fc91e13ca70b91fc8/href</a></iframe><p>Once a player successfully downloads the MPD it starts to download, decode, sync, and play the corresponding media payloads. In order to reduce latency and improve overall performance video and audio are downloaded in segments, usually 2–10 seconds in length.</p><p>However, not all players support the same flavor of delivery protocol and format. Today, there are two popular delivery protocols: HTTP Live Streaming (HLS) which is Apple’s propriety protocol that is used in Apple products, and Dynamic Adaptive Stream over HTTP (DASH), which is the open-source equivalent of HLS. Common Media Application Format (CMAF), which was created to handle the compatibility issue between HLS and DASH, is starting to increase in popularity.</p><p>A key aspect of each of these delivery protocols is support for adjustable bitrate streaming (aka ABR). This makes it possible to stream the highest quality video given changing network and client resource conditions. As input, ABR takes in system performance data like frame buffering, network bandwidth, and the available video quality lanes (advertised in the manifest) and returns the highest quality lane that can be streamed without dropping frames.</p><h3>How is the video data Contained?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1xo9AKS4eeBJENaRAn%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1xo9AKS4eeBJENaRAn%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F1xo9AKS4eeBJENaRAn%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d46b29290fbada3f7e19834cc404908/href">https://medium.com/media/2d46b29290fbada3f7e19834cc404908/href</a></iframe><p>Each delivery protocol (eg: HLS, DASH, CMAF) has a corresponding file format (eg: MPEG-TS, fMP4) that packages the video/audio media and metadata.</p><h4>Fragmented MP4</h4><p>I’m sure we’ve all heard of MP4, the most well-known video format. It contains two important types of data. The first is the raw data (eg: video, audio, captions). The second is the metadata that communicates to the client how to playback the stream. The MP4 standard is structured using ‘boxes’ which are treated like classes that can be inherited and extended to support different properties relevant to the data it stores.</p><p>The specific flavor of it that is used by DASH is fragmented MP4 (aka fMP4). The main distinction is that fMP4 allows for a stream to be downloaded in fragments of non-multiplexed audio/video as opposed to a single multiplexed MP4 file. To make this possible each fMP4 file contains a small amount of additional metadata overhead that communicates to the player that this file is a fragment of a larger stream. CMAF uses a file type that is closely related.</p><h4>MPEG Transport Stream (MPEG-TS)</h4><p>MPEG Transport Stream (TS), used by HLS, is a multiplexed bit stream, made up of packetized elementary stream chunks. It’s a legacy protocol that was originally created to support DVB, ATSC, and IPTV broadcast systems.</p><p>Today, the main downsides compared to fMP4 are that it’s less supported by browsers, it has larger metadata overhead, and it has worse caching and storage performance due to the video/audio being multiplexed and all of the potential combinations that might exist.</p><p>Furthermore, HLS now supports fMP4 which makes it more attractive as the go-to-delivery container format.</p><h3>Summary</h3><p>In this post, we went over how client devices find the video to stream, the protocols used to efficiently stream video in segments, and the different formats that streams are delivered in.</p><p>If you have any questions or critiques leave a comment.</p><p>If you found this helpful, let me know 👏👏👏.</p><h3>Resources</h3><ul><li><a href="https://en.wikipedia.org/wiki/MP4_file_format">https://en.wikipedia.org/wiki/MP4_file_format</a></li><li><a href="https://en.wikipedia.org/wiki/MPEG_transport_stream">https://en.wikipedia.org/wiki/MPEG_transport_stream</a></li><li><a href="https://bitmovin.com/container-formats-fun-1/">https://bitmovin.com/container-formats-fun-1/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e78c094deda3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/video-infra-how-millions-of-video-streams-get-delivered-e78c094deda3">Video Infra: How Millions of Video Streams get Delivered</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Video Infra: How Video Processing Codecs Work for Millions of Live Streams]]></title>
            <link>https://levelup.gitconnected.com/video-infra-how-video-processing-codecs-work-for-millions-of-live-streams-731838a45cf2?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/731838a45cf2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[video-codec]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 16:09:57 GMT</pubDate>
            <atom:updated>2024-01-25T16:15:17.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBYzKB8jFGi7qh5u7ZxgwA.jpeg" /></figure><p>I’ve been working in the video live stream space for over a year and these are the things I wish I knew about codecs when starting out.</p><p>This post goes over what codecs are as they relate to video processing and the most popular codecs that we see in the wild today.</p><p>To read about audio processing check out this <a href="https://medium.com/gitconnected/distributed-video-infra-how-audio-data-is-transformed-for-millions-of-live-streams-c17b168eedbf">post</a>.</p><h3>What is the purpose of a codec?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPu5F5t64WNKYE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FPu5F5t64WNKYE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FPu5F5t64WNKYE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c61794e3b929aa573ff2b79ceb02122/href">https://medium.com/media/6c61794e3b929aa573ff2b79ceb02122/href</a></iframe><p>Codecs are important to conserve resources, improve performance, and more effectively support different types of player devices.</p><p>Video media takes up a lot of space. A single 1920x1080 video with 3 bytes of color allocated for each pixel running at 30 frames per second (fps) for 5 minutes would consume 1.5Gbps of network bandwidth and 450Gbs of long-term storage. <a href="https://www.wyzowl.com/youtube-stats">Wyzowl</a> estimates that 183 hours of video content are uploaded to YouTube every minute. This would result in ~988Tbs of storage being consumed (assuming this video quality), not even taking into account the expensive network costs. This is obviously unsustainable.</p><p>Codecs allow us to compress the size of the video/audio media while making tradeoffs between resolution, bitrate, compression ratio, and latency. The most widely used codecs today provide compression results in the x150 range which means the previously 1.5Gbps video can now be streamed over a network at 5Mbps, which is definitely more reasonable.</p><h4>Definitions</h4><ul><li><strong>Bitrate</strong>: (frame size) x (frame rate)</li><li><strong>Video file size</strong>: (bitrate) x (duration) x (compression ratio)</li></ul><h3>How does a codec work?</h3><p>Codecs provide the instructions/recipe to encode and decode video media. On the encoding side, it takes a video and compresses it into a smaller file size using a combination of lossless and lossy strategies.</p><p>Lossless compression means that no data is lost and that the original video can be completely reconstructed by the decoder. This would include techniques such as removing redundant data within and between frames.</p><p>Lossy compression means that data is lost, but that doesn’t mean there is an impact on “perceived” quality. This is an important area where we see the interaction between technology and our physical senses.</p><p>For example, if you were to place your hand stationary, in front of your face, you could see all of the lines and details. But if you were to start quickly waving it side to side all that detail would get blurry and disappear. In the same way, lossy compression is able to take advantage of the limits of human perception and reduce the data needed to represent certain aspects of a video.</p><p>Inversely, on the decoding side, the video is decompressed using the inverse of the recipe used by the encoder. This is why the player needs to support the codec that a video is encoded in.</p><h3>What are the most popular codecs?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7aTHbH39h8xYePza%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7aTHbH39h8xYePza%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o7aTHbH39h8xYePza%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/d04e13def98351e2ccdd42c50202cf78/href">https://medium.com/media/d04e13def98351e2ccdd42c50202cf78/href</a></iframe><h4>AVC/H264</h4><p>AVC (Advanced Video Codec) is the current bread and butter of the video processing industry for both VOD and Live. It’s been around since 2003 and, as stated by the most recent BitMovin Industry report, is still significantly further ahead of others in terms of adoption.</p><h4>HEVC/H265</h4><p>HEVC (Highly Efficient Video Codec) is able to compress video more efficiently than h264, but with some caveats. While it has the ability to compress info more efficiently and has better motion compensation and spatial prediction than H264 it requires more advanced hardware which is one of the headwinds to its adoption. In addition, despite various performance improvements, expensive licensing requirements have been a large detractor to using H265.</p><p>One place where H.265 remains a better option than VP9 or H.264 is 4K and HDR video delivery to living room devices, as it’s almost universally supported on Smart TVs. Google has also recently added it to Chrome.</p><h4>Versatile Video Codec (VCC)</h4><p>VCC is the successor to HEVC and shows compression efficiency improvements while maintaining the same quality. But it’s CPU intensive, lacks hardware support, and like HEVC has licensing issues that have slowed adoption.</p><h4>AV1</h4><p><a href="https://en.wikipedia.org/wiki/AV1">AV1</a> is the successor to VP9 and is the royalty-free competitor to HEVC. It’s more efficient than HEVC, but it takes longer to encode because of a lack of hardware support, which can make it less ideal for live streaming uses cases. It’s becoming more popular for higher-quality encoding, but because of the computational cost is still reserved for highly viewed content.</p><h4>Enhanced Video Codec (EVC)</h4><p>EVC is one of the newest codecs, released by MPEG in 2020. To prevent royalty issues, it comes with two profiles, Baseline and Main. The Baseline is supposed to provide ~30% savings over H264 and is royalty-free. The Main profile will provide better performance but will require royalties. This is still relatively new, so it’s not clear yet what its future adoption will look like.</p><h4>Low Complexity Enhanced Video Codec (LCEVC)</h4><p>LCEVC is marketed as the “codec to improve other codecs”. It was created to be easily compatible with current systems to reduce upfront cost, allow for a tradeoff between quality and resource consumption, and be usable on commodity hardware.</p><p>It does this by processing a video at a lower resolution with an existing codec (ie: H264) and doing additional specialized processing that corrects impairments, upscales, and adds detail. The result of this is two outputs: a base bitstream and an extra enhancement layer to improve video quality.</p><h3>How Are Codecs Used in the Wild?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxkSzarUPEt326y6klD%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxkSzarUPEt326y6klD%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxkSzarUPEt326y6klD%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/d20250a8071a240cf8865f5f7aa5119f/href">https://medium.com/media/d20250a8071a240cf8865f5f7aa5119f/href</a></iframe><p>Despite being old by technology standards, H264 is the most supported codec and is likely found in most video processing pipelines. However, there are certain conditions that could make other codecs more performative assuming that the viewer’s player supports them. For example, it might be more expensive (ie: cost more compute resources) to encode a video with AV1 vs. H264. But if the system predicts that the video will be streamed over a certain threshold of devices that support the codec the initial compute cost can be outweighed by the network savings or improved quality.</p><p>It’s also common for video processing systems to use a bitrate ladder to provide multiple video qualities and resolutions to viewers. Based on the desired bitrate, compression efficiency, and quality different codecs maybe be selected to encode the video for different quality lanes.</p><h3>Summary</h3><p>In this post, we went over what’s the purpose of video codecs, how they work at a high level, and what the most popular codecs are used today.</p><p>If you have any questions or critiques leave a comment.</p><p>If you found this helpful, let me know 👏👏👏.</p><h3>Resources</h3><ul><li>H264 Ffmpeg documentation: <a href="https://trac.ffmpeg.org/wiki/Encode/H.264">https://trac.ffmpeg.org/wiki/Encode/H.264</a></li><li>Breakdown of terminology for the H265 codec: <a href="https://codesequoia.wordpress.com/2012/10/28/hevc-ctu-cu-ctb-cb-pb-and-tb/">https://codesequoia.wordpress.com/2012/10/28/hevc-ctu-cu-ctb-cb-pb-and-tb/</a></li><li>VCC: <a href="https://bitmovin.com/vvc-video-codec/">https://bitmovin.com/vvc-video-codec/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=731838a45cf2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/video-infra-how-video-processing-codecs-work-for-millions-of-live-streams-731838a45cf2">Video Infra: How Video Processing Codecs Work for Millions of Live Streams</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Video Infra: How Audio Data is Transformed for Millions of Live Streams]]></title>
            <link>https://levelup.gitconnected.com/distributed-video-infra-how-audio-data-is-transformed-for-millions-of-live-streams-c17b168eedbf?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/c17b168eedbf</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[audio-codec]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[live-streaming]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 02:50:05 GMT</pubDate>
            <atom:updated>2023-03-13T02:50:05.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpGmrT49j-AJbYnOK6DJYQ.jpeg" /><figcaption>Image by C D-X via <a href="https://unsplash.com/photos/PDX_a_82obo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditShareLink">https://unsplash.com/photos/PDX_a_82obo</a> Copyright-free</figcaption></figure><p>I’ve been working in the video live-stream space for the last year. This is the context around audio that I would have found helpful when starting out.</p><p>This post will go over the fundamentals of how audio starts off as an analog sound, then how it’s transformed into a digital representation, and finally how it’s compressed into the final form that is delivered to viewers/listeners.</p><h3>Properties of Human Hearing 👂</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPQiyXFdIXqSgE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FPQiyXFdIXqSgE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FPQiyXFdIXqSgE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9fa3e6ec155c58424bd82e44079f4f0/href">https://medium.com/media/a9fa3e6ec155c58424bd82e44079f4f0/href</a></iframe><p>Before jumping into how audio is processed it’s important to understand how it’s perceived by people. One of the elements important to working in the video/audio space is being aware of the physical world and the senses that viewers/listeners will be using to experience the final output.</p><ul><li>The outer ear and ear canal collect arriving air pressure waves.</li><li>Air pressure waves are transmitted as mechanical vibration via the eardrum and inner ear to the liquid-filled cochlea.</li><li>Depending on the frequency of the sound, different areas of the cochlea resonate which causes the hair cells to vibrate.</li><li>Stimulated nerve endings send impulses to the brain, allowing it to perceive and distinguish sounds of different frequencies, levels, and timbre.</li></ul><p>Because of these physical properties, <a href="https://www.mdpi.com/498470">audio perception is not linear across different frequencies</a>. This concept will become important when discussing audio compression optimizations and sampling rates.</p><h3>Going from Analog to Digital Audio 🎸</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXDn8V9LECMavx7QKdK%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Fnew-girl-schmidt-nick-miller-XDn8V9LECMavx7QKdK&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FXDn8V9LECMavx7QKdK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb885c2c17ab6eb5ac446c8d95569fda/href">https://medium.com/media/cb885c2c17ab6eb5ac446c8d95569fda/href</a></iframe><h4>What is Analog Audio?</h4><p><a href="https://en.wikipedia.org/wiki/Analog_signal">Analog</a> audio is represented as varying voltage fluctuations. This is generated by the device hardware, such as a microphone, which converts sound waves into this voltage.</p><h4>What is Digital Audio?</h4><p><a href="https://en.wikipedia.org/wiki/Digital_signal_(signal_processing)">Digital</a> audio is stored as a sequence of discrete values. The most common way to represent digital audio is with <a href="https://en.wikipedia.org/wiki/Pulse-code_modulation">Pulse Code Modulation</a> (PCM) which is a sequence of audio samples stored as bytes. The two most important parameters when dealing with PCM are the sample rate and sample bit-depth. Both of these are a tradeoff between performance and audio quality.</p><p>A high enough sample size is needed so that the player outputting the audio can recreate the original continuous analog audio without any perceptual quality differences. The most common rate is 44100 samples per second (you might have also seen this represented as 44,100 Hz). But, for certain uses in which the dynamic range is known beforehand, optimizations can be made to reduce the number of samples.</p><p>This is because the audio sample size should generally be at or above the <a href="https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem">Nyquist</a> rate which is twice the highest frequency in the audio (remember from early that we perceive audio at different frequencies with different levels of granularity).</p><p>If the sample rate is too low we risk aliasing which is when the player fails to correctly identify the original audio signal and the output could either be silent or distorted.</p><p>Bit-depth is important to enable a range of audio values. The most common size is 16 bits although higher-quality audio can use up to 24 bits.</p><h4>How is Analog Converted to Digital?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*HA3IyOXdaQ92BzcjBbz1wg.png" /></figure><p>The process starts with an analog-to-digital (ATD) converter sampling the analog voltage at regular intervals. Each sample is then quantized which means assigning the sample to the discrete value of the bucket it falls into. Finer quantization leads to less error but increases the number of bits representing a signal.</p><p>An important mathematical concept for this process and for the process of converting back to analog is a <a href="https://towardsdatascience.com/understanding-audio-data-fourier-transform-fft-spectrogram-and-speech-recognition-a4072d228520">Fourier Transform</a> which converts a continuous signal from the time domain to the frequency domain. The most common type of Fourier Transform for audio processing is the <a href="https://en.wikipedia.org/wiki/Modified_discrete_cosine_transform"><strong>Modified Discrete Cosine Transform</strong></a> (<strong>MDCT</strong>) which processes subsequent overlapping audio blocks to avoid artifacts being generated on the boundaries.</p><h4>Time vs. Frequency Domain</h4><p>I want to highlight the distinction between the two because this caused me some initial confusion.</p><p>The time domain represents the changes in a signal over a span of time, while the frequency domain represents how much of the signal exists within a given frequency band over a range of frequencies. When it comes to audio, the frequency domain<a href="https://resources.pcb.cadence.com/blog/2020-time-domain-analysis-vs-frequency-domain-analysis-a-guide-and-comparison"> gives a better understanding than the time domain because it’s based on the breaking down of intricate sounds into their separate component frequencies</a>. The best video I’ve found that explains this can be found <a href="https://www.youtube.com/watch?v=fYtVHhk3xJ0">here</a>. This will make more sense when discussing compression optimizations later on.</p><h3>Audio Compression 🤖</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FA06UFEx8jxEwU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FA06UFEx8jxEwU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FA06UFEx8jxEwU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="320" frameborder="0" scrolling="no"><a href="https://medium.com/media/649b348358107ce45ff2a26ef30f6eff/href">https://medium.com/media/649b348358107ce45ff2a26ef30f6eff/href</a></iframe><p>At this point, we have raw, uncompressed audio data represented as PCM. However, this can take up a non-trivial amount of storage and network bandwidth.</p><blockquote>For example: <strong>(16 bit) x (44100 samples) x (2 channels) = ~166kbps</strong></blockquote><p>Audio codecs can shrink this by taking advantage of various audio-related properties.</p><h4>Psychoacoustic Models</h4><p>A common audio compression technique is the use of psychoacoustic models of human auditory perception. By taking advantage of limitations in human hearing data can be removed while still maintaining the same perceptual quality.</p><p>The first step in this process is to pass the frequency domain signal through a <a href="https://en.wikipedia.org/wiki/Filter_bank">filter bank</a>, which is an array of <a href="https://en.wikipedia.org/wiki/Bandpass_filter">bandpass filters</a> that separates the input signal into multiple frequency components.</p><p>A bandpass is a device that accepts <a href="https://en.wikipedia.org/wiki/Frequency">frequencies</a> within a certain range and rejects frequencies outside that range. You can dive deeper into how this works, but it gets a lot more math-heavy and I didn’t feel like going down that rabbit hole.</p><p>Now that the frequencies are separated from one another, frequencies outside human perception can be removed and principles related to masking can be used to filter out even more data. Masking is the effect that louder sounds (“masker”) tend to suppress the perception of other, weaker sounds (“probe”) in the masker’s spectral or temporal vicinity. Types of masking used are:</p><ul><li><strong>Inter-band masking</strong>:<strong> </strong>masking effects spreading to frequencies beyond the critical bandwidth.</li><li><strong>Temporal masking effects</strong>: when masker and probe signals are not present at the same time.</li><li><strong>Post-masking</strong>: right after a loud stimulus a softer stimulus won’t be perceived because of the reduced sensitivity of the ear.</li><li><strong>Pre-masking</strong>: because a softer sound needs longer build-up time for cognitive processing a loud stimulus immediately following a softer one can override it.</li></ul><h3>How Audio Data is Packaged for Viewers 📦</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FWRQBXSCnEFJIuxktnw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FWRQBXSCnEFJIuxktnw%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeDJ6eG5yaG1iNHZtMGZ4cWN2ZTd1aTJibmxzOTkyaDJtdTF1d3ppMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FWRQBXSCnEFJIuxktnw%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="278" frameborder="0" scrolling="no"><a href="https://medium.com/media/81589a9157db1c2cec662896c0fcfaec/href">https://medium.com/media/81589a9157db1c2cec662896c0fcfaec/href</a></iframe><p>Next, we’ll briefly discuss the different types of audio formats that can be chosen to compress audio and deliver it in a supported file type to player devices.</p><h4>What is a Container?</h4><p>Audio containers store the raw audio bytes and corresponding metadata to assist the player in decoding and processing the data. When determining the best option for your use case, at a high level, you should be thinking about bitrate, latency, codec support, and player compatibility.</p><h4>What is an Audio Format?</h4><p>An audio format is a two-part structure that consists of a container and a codec. This can get confusing because compared to video, audio containers, and codecs are much more closely tied together.</p><p>For example, when discussing video codecs we might be referring to H264, HEVC, AV1, or VP9, etc... while for video containers it could be MP4 or FLV. It’s very clear if we’re talking about codecs or containers.</p><p>However, when discussing audio the same term (ie: MP3) could be used to refer to the container (aka file type) or the codec.</p><h4>MP3 (<strong>MPEG-2 Audio Layer 3)</strong></h4><p>The first version of <a href="https://en.wikipedia.org/wiki/MP3">MP3</a> had its public release in 1993 and revolutionized digital audio in the 1990s.</p><h4>AAC (Advanced Audio Coding)</h4><p>AAC is an improved version of MP3. It has all of the same features in addition to better quality at the same bitrate, support for a broader range of sampling rates, and support for more performance tradeoffs. This is the <a href="https://bitmovin.com/wp-content/uploads/2022/12/bitmovin-6th-video-developer-report-2022-2023.pdf">most widely used audio format</a> used today.</p><h4>Opus</h4><p>Opus has been steadily gaining in popularity since it was standardized by IETF in 2012. It was designed for interactive audio applications and has one of the lowest latencies among audio codecs.</p><h4>FLAC (Free Lossless Audio Codec)</h4><p><a href="https://en.wikipedia.org/wiki/FLAC">FLAC</a> is the most widely supported lossless audio format. Compared to the others listed, FLAC is best for archiving audio in which you don’t want to lose any of the original signal. The tradeoff is that the compression rate isn’t as good as the other lossy options.</p><h4>Summary</h4><p>In this post, we went over how analog audio is converted to an uncompressed digital format, some of the techniques that audio compression algorithms use to decrease bitrate and save on network/storage costs, and the different types of audio formats that can be used to store and compress audio.</p><p>If you have any questions or critiques leave a comment.</p><p>If you found this helpful, let me know 👏👏👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c17b168eedbf" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/distributed-video-infra-how-audio-data-is-transformed-for-millions-of-live-streams-c17b168eedbf">Distributed Video Infra: How Audio Data is Transformed for Millions of Live Streams</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State of the Video Development Industry in 2022: sparknotes]]></title>
            <link>https://medium.com/@j.d.livni/state-of-the-video-development-industry-in-2022-sparknotes-a940c7ddb650?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/a940c7ddb650</guid>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[low-latency-streaming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[livestream]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 16:56:31 GMT</pubDate>
            <atom:updated>2022-12-27T16:56:31.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="live streaming" src="https://cdn-images-1.medium.com/max/1024/1*Hox-4pDU6u2tT-M60LnFMw.jpeg" /></figure><h3>Background</h3><p>This is a summary of the main ideas that came out of the <a href="https://bitmovin.com/wp-content/uploads/2022/12/bitmovin-6th-video-developer-report-2022-2023.pdf">BitMovin 6th Video Developer Report</a>. This annual report surveys the video development community to gather insight into current and upcoming trends. As someone new to video streaming technology and the industry I found this insightful and hope others can too.</p><h3>Biggest Industry Challenges</h3><p>The biggest reported industry challenges in order are: controlling costs (eg: bandwidth and storage), support for low latency live streams, ad insertion, and monitoring/analytics.</p><h4>Resources efficiency</h4><p>Over the last three years, starting in 2020, live streaming has seen a massive surge in viewership and investment. At the same time video remains expensive in terms of storage, memory, and bandwidth. Due to these factors and the current economic climate, it makes sense that companies are focusing more on trimming the bottom line by improving the efficiency of their infrastructure. I’m curious to see how this will impact the user experience because there are two different types of improvements that can be made. On one hand, there are those that improve the utilization of current storage, memory, and compute resources such as improving caching and video processing algorithms. On the other hand, are resource efficiencies that potentially tradeoff latency, reliability, and video quality such as shrinking the encoding bitrate ladder or enabling just in time encoding.</p><h4>Low Latency streaming</h4><p>Support for low latency has dropped down to second place from first. Some of the big areas in which low latency streams can improve the user experience are categories such as gaming, e-commerce, and overall streamer/viewer interactivity. This is an area of development that I’m excited about because in my opinion there are very few consumer products that rely as heavily on the performance of backend infra in order to be unlocked. One of the technologies that is helping to enable more widescale low latency adoption is the Common Media Application Format (CMAF), which is a delivery container standard originally proposed in 2016 that supports chunked encoding and transfer which reduces delivery latency.</p><p>When I first heard about the concept of low-latency technology it was unclear to me what it actually meant. It seems like there is no fixed latency standard, but rather a working definition like the definition of durability in an ACID database. The survey reported that 3 seconds of glass-to-glass latency is the most popular latency expectation, but most services are delivering in the 5–30 second range.</p><h4>Ad Insertion</h4><p>It makes sense that companies want to integrate ads into live streams because datacenters and software engineers aren’t cheap. I don’t know much about the protocols that support this integration, but it’s an area I’m interested in diving deeper into.</p><h4>Monitoring/Analytics</h4><p>One of the things I especially like about working in the video space is the direct user experience. However, this also relates to one of the main challenges which is translating the user experience into metrics that we can use to detect regressions and make improvements.</p><p>According to the report, the most important performance metrics are buffering/rebuffering rates, the bitrate delivered, video start time, and buffering duration. While it is challenging to instrument all of these metrics I think much more effort is required to setup the monitoring and the analysis systems/tools to make sense out of this data across the entire video pipeline.</p><h3>ML/AI in video</h3><p>I think that keeping up on the trends in the ML/AI space is important as it relates to VOD and Live because often times when we see large leaps in innovation it’s because of two evolving technologies coming together to create new and novel capabilities and user experiences.</p><p>The main use cases related to video were reported to be: automatic caption generation, recommendation systems, improving video encoding optimizations, measuring the quality of viewer experience (QoE), and copyright detection.</p><h3>Encoding Standards</h3><p>Despite being created in 2003, H264/AVC is still the most popular video codec. However, there is a large increase in the use of H265/HEVC, H266/VCC, and AV1 with this trend likely continuing into 2023.</p><p>Thank you for taking the time to read this post.</p><p>If you found this helpful, let me know 👏👏👏.</p><p>If you want to read more click the “follow” button below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a940c7ddb650" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Command Line Git Parser]]></title>
            <link>https://medium.com/analytics-vidhya/golang-command-line-git-parser-2f4e85ac8fc6?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f4e85ac8fc6</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 22:38:52 GMT</pubDate>
            <atom:updated>2019-10-25T08:50:50.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="golang command line parser" src="https://cdn-images-1.medium.com/max/1000/1*TKhH0-D0BdQXv1qFJClEnA.png" /><figcaption>source: <a href="https://github.com/egonelbre/gophers">https://github.com/egonelbre/gophers</a></figcaption></figure><p>Every morning at 10 am my team has a virtual daily standup where each member writes out what they accomplished yesterday and want they’ll be working on today.</p><p>One of the challenges is that on any given day I could be working on multiple projects and trying to remember everything I did in a workday 24 hours later can be hard.</p><p>That’s why I built a command-line tool in Go that will traverse every project directory and show me all the commits I made in the last 24 hours. Let us jump into it!</p><p>To get the final code:</p><pre>cd $GOPATH/github.com<br>git clone <a href="https://github.com/Lebonesco/daily-standup-cli">https://github.com/Lebonesco/daily-standup-cli</a></pre><h3>Some CLI boilerplate</h3><p>We’ll be using two third party packages. cli will be the client library that we’re building the project off of and go-homedir provides some useful file system methods.</p><pre>mkdir daily-standup-cli<br>cd daily-standup-cli<br>touch main.go<br>go get <a href="https://github.com/urfave/cli">https://github.com/urfave/cli</a><br>go get github.com/mitchellh/go-homedir</pre><p>If you’re interested in learning more about the cli package this project uses the docs in its <a href="https://github.com/urfave/cli">repo</a> are extensive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aea4d0bd121d89bdc8d6c91d1a3705e9/href">https://medium.com/media/aea4d0bd121d89bdc8d6c91d1a3705e9/href</a></iframe><p>In the code above we’ve set up the functionality to start the client and pass in various flags. Right now we’re keeping it simple with only three flags, but you can easily extend the functionality of this project to be able to do things like specifying your output to an email, slack channel, or file.</p><p>The block of code below specifies a flag with the name user or u and no default value.</p><pre>...<br>cli.StringFlag{   <br>    Name:  &quot;user, u&quot;,<br>    Value: &quot;&quot;,<br>    Usage: &quot;git user name&quot;,  <br>},<br>...</pre><p>app.Action is where the core of our code will be executed when we run the program. c.String(&quot;flag&quot;) returns a flag value. The dir flag has a default of your systems home directory and after is set to 24 hours from the current time. The only flag without a default is user which is your git username.</p><p>To see our client details run:</p><pre>go run main.go --help</pre><pre>NAME:<br>   Daily Standup Helper CLI - Reports git history</pre><pre>USAGE:<br>   main [global options] command [command options] [arguments...]</pre><pre>VERSION:<br>   1.0.0</pre><pre>AUTHOR:<br>   github.com/Lebonesco</pre><pre>COMMANDS:<br>   help, h  Shows a list of commands or help for one command</pre><pre>GLOBAL OPTIONS:<br>   --user value, -u value   git user name<br>   --dir value, -d value    parent directory to start recursively searching for *.git files (default: &quot;/Users/josephlivni&quot;)<br>   --after value, -a value  when to start looking at commit history (default: &quot;2019-10-18T14:21:17&quot;)<br>   --help, -h               show help<br>   --version, -v            print the version</pre><h3>The Core of the Application</h3><p>It’s time to get to the fun part!</p><p>The next section will include code that will crawl through your folders, capture git logs, store them temporarily in memory, and then save them as a formatted JSON file.</p><h4>Capturing Git Logs</h4><p>The code below takes in the path that we want to execute our git log command, the user whose commits we care about, and the date in which we want to start filtering by.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a372c2917bb559cb1f1b0c0dc1985a93/href">https://medium.com/media/a372c2917bb559cb1f1b0c0dc1985a93/href</a></iframe><p>If you were to just run git log you would get a lot of unstructured data thrown at your terminal. Luckily git provides us with a --pretty=format option that allows us to output our results into formatted XML. %an will give us the author’s name, %cd the date the commit was made, and %B the commit message. If you want to learn more about git log formatting checkout the <a href="https://git-scm.com/docs/git-log">official docs</a>.</p><h4>Crawling Through Directories</h4><p>The idea here is that we will crawl through the file system and when we find a .git file we’ll execute the code we just wrote above and capture the logs.</p><p>Fortunately, Go has a method filepath.Walk() that, given a starting directory, will recursively traverse down.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/790b8d1ff6283ccc281011feb056fce8/href">https://medium.com/media/790b8d1ff6283ccc281011feb056fce8/href</a></iframe><p>The code is fairly basic. When we hit a file with info.Name() == .git we get the commit logs from that project. We then take the XML bytes and convert them into acommit struct and append our results to commits.</p><p>Note: <em>The reason we couldn’t use </em><em>xml.Umarshal(b, &amp;commit) to convert the bytes to structs is because the result we receive from git is an array of XML objects without a wrapping tag. Therefore, </em><em>xml.Umarshal would only give us the first result. </em><em>d.Decode is smart enough to walk through the array until it hits the end.</em></p><h4>Bringing Everything Together</h4><p>We’ll finally write runClient which will tie all our code together and save our results to a local file.</p><p>The below code will run getGitHistory() and save the results as a nicely formatted JSON file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30f59e9aab04091c5e7bf5d48d0d94f/href">https://medium.com/media/e30f59e9aab04091c5e7bf5d48d0d94f/href</a></iframe><p>Finally, if you’re interested in being able to run this from anywhere run:</p><pre>cp main /usr/local/bin/&lt;whatever-you-want-to-call-it&gt;</pre><p>All Done!</p><p>Thanks for reading this. I hope it was interesting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f4e85ac8fc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/golang-command-line-git-parser-2f4e85ac8fc6">Golang Command Line Git Parser</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Go Cache in 10 Minutes]]></title>
            <link>https://medium.com/hackernoon/build-a-go-cache-in-10-minutes-c908a8255568?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/c908a8255568</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[build-a-go-cache]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 16:16:01 GMT</pubDate>
            <atom:updated>2019-04-25T09:39:09.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvlMpkpIKmPm6IF_QnmjmQ.jpeg" /></figure><p>The <a href="https://hackernoon.com/tagged/cache">cache</a> is one of the greatest innovations of computer science 🔥🔥🔥. It significantly reduces work on the <a href="https://hackernoon.com/tagged/cpu">CPU</a> and provides massive performance gains in terms of speed. 😃</p><p>It works by saving the result of computations that may be needed later. For example: say you had a service that, given a string, generated a hash. A cache could save time and resources by checking if the hash of the received string had already been generated. If it had, and was still in the cache, it would be returned without running through the hashing algorithm again.</p><p>Today, we’ll be building a <strong>LRU </strong>(<em>Last Recently Used</em>) cache that stores a fixed amount of strings and ejects the last used item once the cache is full.</p><p>This won’t be anything you would want to run in production. But it will clearly demonstrate the data structures and algorithms that make this type of cache work.</p><p><strong>To get and run the final results:</strong></p><pre>git clone <a href="https://github.com/Lebonesco/go_lru_cache.git">https://github.com/Lebonesco/go_lru_cache.git</a><br>go run main.go</pre><p>Let’s jump into some code!</p><p>We’ll start by defining our data structures. These will include Node, Queue, Hash, and Cache. Our Queue will be a doubly linked list of Node pointers that are mapped to from the Hash. This will allow for <strong>O(1)</strong> <strong>insertion</strong> and<strong> deletion</strong> of values. 👍</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1abfbf2729e58808117a08ac63a836a8/href">https://medium.com/media/1abfbf2729e58808117a08ac63a836a8/href</a></iframe><p><strong>Note: </strong>We are<strong> </strong>just caching strings right now, but any data type could replace it.</p><p>Next, we’ll setup our constructor functions for the Cache and Queue. Although, Hash starts out empty it needs to be initialized or it will result in a <strong>“nil pointer error”</strong> later on. In addition, we create two empty Nodes for the<strong> Head</strong> and <strong>Tail</strong>. This will make more sense when we move onto our Add() and Remove() methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39837c4dde129180bedf7f800f67aaa8/href">https://medium.com/media/39837c4dde129180bedf7f800f67aaa8/href</a></iframe><p>Onto the primary code of the cache.</p><p>The cache has <strong>three methods</strong> that are required to make it work: <strong>Check()</strong>(receives the string from the user and returns the result), <strong>Add()</strong>(adds a string to the cache), <strong>Remove()</strong>(ejects a string from the cache).</p><p>Inside of Check(), if the string already exists in the cache we first remove it before adding it back again so that the string gets shifted to the front of the Queue.</p><p>Both Add() and Remove() involve similar operations that reassign Left and Right Node pointers in the Queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9823ec71eeb5384f416717aa23735b5c/href">https://medium.com/media/9823ec71eeb5384f416717aa23735b5c/href</a></iframe><p>Awesome, we now have a working cache! 🎉🎉🎉</p><p>The last step is to add a main() and some display methods to demonstrate our results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8175a4649a126aba7cf412adf2efcdbc/href">https://medium.com/media/8175a4649a126aba7cf412adf2efcdbc/href</a></iframe><p>To see your code in action, run:</p><pre>go run main.go<br>START CACHE<br>add: cat<br>1 - [{cat}]<br>add: blue<br>2 - [{blue} &lt;--&gt; {cat}]<br>add: dog<br>3 - [{dog} &lt;--&gt; {blue} &lt;--&gt; {cat}]<br>add: tree<br>4 - [{tree} &lt;--&gt; {dog} &lt;--&gt; {blue} &lt;--&gt; {cat}]<br>add: dragon<br>5 - [{dragon} &lt;--&gt; {tree} &lt;--&gt; {dog} &lt;--&gt; {blue} &lt;--&gt; {cat}]<br>add: potato<br>remove: cat<br>5 - [{potato} &lt;--&gt; {dragon} &lt;--&gt; {tree} &lt;--&gt; {dog} &lt;--&gt; {blue}]<br>add: house<br>remove: blue<br>5 - [{house} &lt;--&gt; {potato} &lt;--&gt; {dragon} &lt;--&gt; {tree} &lt;--&gt; {dog}]<br>remove: tree<br>add: tree<br>5 - [{tree} &lt;--&gt; {house} &lt;--&gt; {potato} &lt;--&gt; {dragon} &lt;--&gt; {dog}]<br>add: cat<br>remove: dog<br>5 - [{cat} &lt;--&gt; {tree} &lt;--&gt; {house} &lt;--&gt; {potato} &lt;--&gt; {dragon}]</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdsKnRuALlWsZG%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FdsKnRuALlWsZG%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FdsKnRuALlWsZG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/b262e606843d1af9503450acc0765723/href">https://medium.com/media/b262e606843d1af9503450acc0765723/href</a></iframe><p>Thank you for taking the time to read this article.</p><p>If you found it helpful or interesting please let me know 👏👏👏.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c908a8255568" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/build-a-go-cache-in-10-minutes-c908a8255568">Build a Go Cache in 10 Minutes</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write a compiler in Go: a quick guide]]></title>
            <link>https://medium.com/free-code-camp/write-a-compiler-in-go-quick-guide-30d2f33ac6e0?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d2f33ac6e0</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 14:54:04 GMT</pubDate>
            <atom:updated>2019-01-07T14:54:51.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwPzWlZJoBbgrtEvwslRdg.jpeg" /><figcaption><strong>Photo by </strong><a href="https://www.flickr.com/photos/diliff/"><strong>DAVID ILIFF</strong></a><strong>. License:</strong><a href="https://creativecommons.org/licenses/by-sa/3.0/"><strong> CC-BY-SA 3.0</strong></a></figcaption></figure><p>Compilers are awesome! 🔥 🔥 🔥 They combine theory and application and touch on a lot of software related topics such as parsing and language construction. At their core, compilers are a program that make a program readable by the computer.</p><p>The inspiration for this came out of a compilers course I took this past Fall and my love for Go.</p><p>This is the guide I wish I had when starting my journey into compilers. There are a lot of books, videos, and tutorials on how to create compilers. The goal of this post is to strike a balance between providing a nontrivial example of some of the things a compiler can do while avoid getting stuck in the weeds. 😒</p><p>The result will be a compiler that can execute a small made up language.To checkout and run the final project see the instructions below. 👇</p><p><strong>Note:</strong> Remember that Go is strict about absolute paths when running this</p><pre>cd $GOPATH/src/github.com/Lebonesco<br>git clone <a href="https://github.com/Lebonesco/go-compiler.git">https://github.com/Lebonesco/go-compiler.git</a><br>cd go-compiler<br>go test -v<br>go run main.go ./examples/math.bx</pre><h4>Outline of the Compiler</h4><ul><li><strong>Lexer/Parser</strong></li><li><strong>AST Generator</strong></li><li><strong>Type Checker</strong></li><li><strong>Code Generation</strong></li></ul><h4>The Language</h4><p>The goal of this post is to get you familiar with compilers as quickly as a possible so we’ll keep the language simple. For <strong>Types </strong>we’ll work with strings, integers, and bools. It will have <strong>Statements</strong> that include func, if, else, let, and return. This should be enough to have fun working with some of the complexities of a compiler.</p><p>The first compiler that I built, I completed over the course of two months and took up <strong>1000’s of lines</strong> of code. I took some shortcuts in this post in order to show you the key fundamentals.</p><p>Two common components that our language is missing are classes and arrays. These add additional complications we don’t have time for right now. If it turns out that people really want to know how to handle these elements I’ll write a followup.</p><p>Some example code:</p><pre>func add(a Int, b int) Int {<br>    return a + b;<br>}</pre><pre>func hello(name String) String {<br>    return &quot;hello:&quot; + &quot; &quot; + name;<br>}</pre><pre>let num = add(1, 2);<br>let phrase = string hello(&quot;Jeff&quot;);<br>let i = int 0;<br>let result = &quot;&quot;;</pre><pre>if (i == 2) {<br>    result = hello(&quot;cat&quot;);<br>} else {<br>    result = hello(&quot;dog&quot;);<br>}</pre><pre>PRINT(result);</pre><h4>Quick Setup</h4><p>The only outside package we need is <strong>gocc,</strong> which will help build the lexer and parser.</p><p>To get it run:</p><pre>go get github.com/goccmack/gocc</pre><p>Make sure the bin folder where gocc is located is in your <strong>PATH :</strong></p><pre>export PATH=$GOPATH/bin:$PATH</pre><p><strong>Note:</strong> If you’re having problems at this stage try running go env to make sure that your $GOROOT and $GOPATH are correctly assigned.</p><p>Cool, let’s dive into some code.</p><h4>Building the Lexer</h4><p>The lexer’s job is to read the program and output a stream of tokens that are consumed by the parser. Each Token contains the type that the token represents in the language and the string Literal of that token.</p><p>To identify the pieces of the program we will be using regular expressions. gocc will then convert these regular expressions into a <strong>DFA</strong> (<em>Deterministic Finite Automata</em>) which can theoretically run in linear time.</p><p>The notation that we’ll be using is <strong>BNF</strong> (<em>Backus–Naur form</em>). Don’t confuse this with <strong>EBNF</strong> (<em>extended Backus–Naur form</em>) or <strong>ABNF</strong> (<em>augmented Backus–Naur form</em>) which have some added features. Keep this in mind when looking at other examples online that could be using other forms which provide more syntactic sugar.</p><p>Let’s start with the basics and define what strings and integers will look like.</p><p>Note that:</p><ul><li>All token names must be lower case</li><li>Any key preceded by ‘!’ will be ignored</li><li>Any key preceded by ‘_’ will not by turned into a token</li><li>Any expression enclosed by ‘{‘ expression ‘}’ can be repeated 0 or more times</li></ul><p>In the below example we are ignoring all white space and have defined an int and string_literal token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb94657051f933daf30d3161bea1e80a/href">https://medium.com/media/bb94657051f933daf30d3161bea1e80a/href</a></iframe><p>Every language has built in keywords that are reserved words that deliver special functionality. But, how will the lexer know whether a string is a keyword or a user created identifier? It handles this be giving preference to the order in which tokens are defined. Therefore, let’s define keywords next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7469440f3d21132d167054e02966e62f/href">https://medium.com/media/7469440f3d21132d167054e02966e62f/href</a></iframe><p>We’ll finish this up by adding the punctuation necessary for expressions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6605b3c909e3957a82005ff09c2baa9/href">https://medium.com/media/b6605b3c909e3957a82005ff09c2baa9/href</a></iframe><p>Cool! Let’s see if this is actually doing what we want with some <strong>unit tests</strong>. Feel free to just paste this part into your IDE. 👍</p><p><strong>Note:</strong> It’s generally good practice in Go to place test files in the relevant subdirectory, but for simplicity I’m placing all tests in the root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2da8a25913642ec0e181121f95c622f/href">https://medium.com/media/e2da8a25913642ec0e181121f95c622f/href</a></iframe><p>To test our<strong> scanner</strong> run:</p><pre>$ gocc grammer.bnf<br>$ go test -v<br>=== RUN   TestToken<br>--- PASS: TestToken (0.00s)<br>PASS<br>ok      github.com/Lebonesco/compiler       0.364s</pre><p>Great, we now have a working <strong>Lexer</strong> 👍</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdIxkmtCuuBQuM9Ux1E%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FdIxkmtCuuBQuM9Ux1E%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FdIxkmtCuuBQuM9Ux1E%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="217" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a165bff41cdef188240249947434054/href">https://medium.com/media/8a165bff41cdef188240249947434054/href</a></iframe><h4>Building the Parser</h4><p>Building the <strong>Parser</strong> is similar to how we built the <strong>Lexer</strong>. We will construct a set of element sequences that when correctly match a stream of tokens produce a grammar. This will also run in linear time by internally converting our <strong>NFA</strong> (<em>Non-Deterministic Automaton</em>) grammar to<strong> DFA</strong> (<em>Deterministic Finite Automaton</em>).</p><p>Let’s keep things simple. What actually is our program? Well, it’s a bunch of Statements in which each Statement can contain a set of Statements and/or Expressions. This seems like a good place to start our grammar.</p><p>Below is the beginning recursive hierarchy of the program. Statements is a sequence of zero or more Statements and Functions is a list of functions. Our languages requires functions to be defined before other Statement types. This will reduce some headache during the type checking phase. empty is a keyword in <strong>BNF </strong>that represents an empty space.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/359dfd30594dbfef89fac9b996d02edc/href">https://medium.com/media/359dfd30594dbfef89fac9b996d02edc/href</a></iframe><p>But wait! What is a Statement? It’s a unit of code that doesn’t return a value. This includes: if, let, and return statements. This is opposed to Expressions which do return values. We will get to those next.</p><p>Below is our grammar for Statement and Function. A StatementBlock is a larger abstraction that encapsulates a list of Statements with braces { }.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4528bde7b9a9e7f6769139f7f129183/href">https://medium.com/media/c4528bde7b9a9e7f6769139f7f129183/href</a></iframe><p>Next lets build out our Expression which handles all infix operations such as +, -, *, &lt;, &gt;, ==, and, and or.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf0a665e6da86b46092467d34a66234/href">https://medium.com/media/edf0a665e6da86b46092467d34a66234/href</a></iframe><p>Almost done with a fully working grammar! Let’s wrap things up by defining our parameter insertion. Each function can accept any amount of values. When <strong>defining a function</strong> we need to label the argument types in the signature while a <strong>called function </strong>can accept any amount of Expressions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1795119c742f4a7ec19b07b057f46071/href">https://medium.com/media/1795119c742f4a7ec19b07b057f46071/href</a></iframe><p>Now that our parser is completed let’s add some code to our driver, main.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4afff1021ac0eab122c448fed1ae566/href">https://medium.com/media/f4afff1021ac0eab122c448fed1ae566/href</a></iframe><p>As we progress through the compiler we will add more functionality to this driver.</p><p>One of the things challenging about building a parser is that there’re many different ways to define the grammar. 😿</p><p>We won’t really know how well we did until we get into the next section which uses the output we just generated. The difficulty of building the static type checker will be strongly influenced by our grammar design. Keep your fingers crossed 🤞.</p><h4>Test Parser</h4><p>We’ll keep this simple because at this point our parser can still produce false positives. Once we start working on the AST we can check its accuracy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d6988128a1ef7e2d6006d78beecd4ed/href">https://medium.com/media/1d6988128a1ef7e2d6006d78beecd4ed/href</a></iframe><pre>go test -v<br>=== RUN   TestParser<br>--- PASS: TestParser (0.00s)<br>=== RUN   TestToken<br>--- PASS: TestToken (0.00s)<br>PASS<br>ok      github.com/Lebonesco/go-compiler        7.295s</pre><p>Congrats 🎉 🎉 🎉! You now have a fully working Lexer and Parser. Time to move onto the <strong>AST</strong> (<em>Abstract Syntax Tree</em>).</p><h3>Abstract Syntax Tree</h3><p>The best way to understand an abstract syntax tree is in relation to a parse tree which is what we generated in the last post. A parse tree represents each part of the program that is matched in our grammar.</p><blockquote>By contrast, an AST only contains the information related to type checking and code generation, and skips any other extra content that is used while parsing the text.</blockquote><p>Don’t worry if that definition doesn’t makes sense right now. I always learn best by actually coding, so let’s jump into it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FliBsVeLILcyaY%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FliBsVeLILcyaY%2Fsource.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FliBsVeLILcyaY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/139efe784b271b43a2bbdaeeae9c43d6/href">https://medium.com/media/139efe784b271b43a2bbdaeeae9c43d6/href</a></iframe><p>Create a new directory and two new files. ast.go will contain our AST generating functions and types.go will have the <em>tree node types</em>.</p><pre>mkdir ast<br>cd ast<br>touch ast.go<br>touch types.go</pre><p>Like with the parse tree, we will define our structure from top to bottom. Every node will either be a Statement or Expression. Go isn’t object oriented so we’ll use a composition pattern utilizing interface and struct to represent our node categories. Our AST will return a Program node that contains the rest of the program. From now on, any struct we created with a TokenLiteral() method is a node. If that node has a statementNode() method it will fit the Statement interface and if it has a expressionNode() method it’s an Expression.</p><p>In addition, we’ll be adding json tags to each struct field to make it easier when we convert our AST into json for testing purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae2f6e53dbcb2f0b5d526576d77fce03/href">https://medium.com/media/ae2f6e53dbcb2f0b5d526576d77fce03/href</a></iframe><p>Now let’s start building our Statement structs based off of the Statement and Node interfaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/813f8c063d997a6555499d69f9eca879/href">https://medium.com/media/813f8c063d997a6555499d69f9eca879/href</a></iframe><p><strong><em>Note:</em></strong> json:&quot;-&quot; means that the field will be omitted from our json.</p><p>Next we need some hooks to connect our nodes and parser. The code below allows our Statement nodes to fit the Node and Statement interfaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4385a076a2cd372a4376eca5e529b04/href">https://medium.com/media/d4385a076a2cd372a4376eca5e529b04/href</a></iframe><p>We then need the hooks that will be called by the parser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f847de2e7fc5d7b463bd677328064d8/href">https://medium.com/media/4f847de2e7fc5d7b463bd677328064d8/href</a></iframe><p>As you can see, <strong>most of our code</strong> is checking and casting our input type.</p><p>These hooks will then be called by the parser in grammar.bnf. To access these functions we’ll need to import &quot;github.com/Lebonesco/go-compiler/ast.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02bcc22f2299ebee663041e3e075a743/href">https://medium.com/media/02bcc22f2299ebee663041e3e075a743/href</a></iframe><p>Now when a piece of grammar is identified, it calls an AST hook and passes in the necessary data to construct a node.</p><p>As you could imagine, there is a lot of flexibility in how you want to generate your AST. There are <strong>design strategies </strong>that reduce the amount of unique nodes in the AST . However, having more node types will make your life easier when we get to the typechecker and code generation. 😌</p><p>This part has a lot of code. However, it’s not very difficult and mostly all the same. The error handling in Go can feel a bit tedious, but in the long run it’ll be worth it when we make a silly mistake. Safety First 👍</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7TKqFBcRXaKUQquQ%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbachelorinparadise-ashley-bip-i-was-trying-to-protect-you-3o7TKqFBcRXaKUQquQ&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7TKqFBcRXaKUQquQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="221" frameborder="0" scrolling="no"><a href="https://medium.com/media/163333a741b28c107b247aad1a4f1458/href">https://medium.com/media/163333a741b28c107b247aad1a4f1458/href</a></iframe><p>We’re not going to do anything too crazy with our error handling because I want to save on lines of code. However, if you feel so inclined you can add more descriptive and useful errors.</p><p>Let’s move on to Expressions!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ad787624ac04326f6d70804199a99e/href">https://medium.com/media/97ad787624ac04326f6d70804199a99e/href</a></iframe><p>Fit them into the Node and Expression interfaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729d0d289a1c273e1186b4a33adb153a/href">https://medium.com/media/729d0d289a1c273e1186b4a33adb153a/href</a></iframe><p>And create the Expression hooks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c58a659c0942649373e7e64be27bbd2/href">https://medium.com/media/9c58a659c0942649373e7e64be27bbd2/href</a></iframe><p>Finally, insert the hooks into the parser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96835532668b5aee5946381fd9983dd2/href">https://medium.com/media/96835532668b5aee5946381fd9983dd2/href</a></iframe><h4>Test AST Generator</h4><p>The test cases for the AST generator are the most tedious to write. But trust me, this is not a part you want to mess up on. If you have problems here, those bugs will rollover into your type checker and code generator. 😟</p><p>In my opinion, if code doesn’t have tests it’s broken</p><p>In our AST test we will construct what our final result should look like. To avoid comparing elements such as tokens, that could create false negatives, we convert our result and expected output into json before comparing with a <strong>deep comparison</strong> function, reflect.DeepEqual().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36fefcf6dd692e86764af301a614a2a0/href">https://medium.com/media/36fefcf6dd692e86764af301a614a2a0/href</a></iframe><p>Run Test:</p><pre>go test -v<br>=== RUN   TestAST<br>--- PASS: TestAST (0.00s)<br>=== RUN   TestParser<br>--- PASS: TestParser (0.00s)<br>=== RUN   TestToken<br>--- PASS: TestToken (0.00s)<br>PASS<br>ok      github.com/Lebonesco/go-compiler        9.020s</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fa0h7sAqON67nO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fa0h7sAqON67nO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fa0h7sAqON67nO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab38f4d6331ea3d9fbc2f1d6919794f0/href">https://medium.com/media/ab38f4d6331ea3d9fbc2f1d6919794f0/href</a></iframe><p>Half way to a working compiler! 👍 While you give this post some 👏 👏 👏 don’t forget to give yourself a hand for making it this far.</p><p>Let’s add some more code to the driver.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3f44c50b56090fdf6e7cfa67cc8d0ab/href">https://medium.com/media/f3f44c50b56090fdf6e7cfa67cc8d0ab/href</a></iframe><p>Now onto my favorite part, the <strong>Type Checker</strong>.</p><h3>Type Checker</h3><p>Our type checker will make sure that users don’t write code that conflicts with our <strong>statically typed</strong> language.</p><p>The core backbone of our <strong>type checker</strong> will be a combination of data structures that track identifier types, initialization, and valid type operations. This can get vastly more complicated once we start dealing with different levels of scope and classes. However, we’re keeping it as simple as possible. 😌</p><p>To start:</p><pre>touch checker_test.go<br>mkdir checker<br>cd checker<br>touch checker.go<br>touch environment.go</pre><p>environment.go will contain all of our helper functions that will be used by our <strong>checker</strong> and <strong>code generator</strong> to access and manipulate our set of variables and corresponding types. Our environment is simple so this will be straight forward.</p><p>We’ll begin by setting all of our constant values including <strong>operation types</strong>, <strong>variable types</strong>, and <strong>mapping of each type to its valid methods</strong>.</p><p><strong>Note:</strong> If we had classes in our language our checker would handle this third part rather than us doing it by hand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d67a04463d6df72ce3447bbadee75395/href">https://medium.com/media/d67a04463d6df72ce3447bbadee75395/href</a></iframe><p>The rest of environment.go are basic <strong>getters </strong>and <strong>setters </strong>that handle identifiers and functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26a6ea95fca56e69ae464f60dbd3a694/href">https://medium.com/media/26a6ea95fca56e69ae464f60dbd3a694/href</a></iframe><p>The foundation of our type checker will be a single <strong>dispatch</strong> function, checker(), that takes in a Node and fires the corresponding checker function</p><p>I felt like saving lines of code so we’ll be using a global environment to store our variable types.</p><p><strong>Note: </strong>This wouldn’t be possible if we allowed Block Statements and Functions to have their own scope or if we were abiding by best practices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4d3380ac9c928a1b26c4ad2813d00d/href">https://medium.com/media/aa4d3380ac9c928a1b26c4ad2813d00d/href</a></iframe><p>Now eval Statements. Block Statements are the only statement in which we return a type in order to handle the case when it is inside a function. If there is a Return Statement inside the Block Statement its type is returned. Otherwise, the Nothing_Type is returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b008c320f68f407d03440dc55cdfa02d/href">https://medium.com/media/b008c320f68f407d03440dc55cdfa02d/href</a></iframe><p>Onto evaluating Expressions. The most complicated part will be evalFunctionCall() because it could either be a built in function such as PRINT() or user defined.</p><p><strong>Note: </strong>Currently, there is only one <strong>builtin</strong> function. However, more could be easily added given the framework that we’ve built.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/935f5c252cb0eea2af44cdb1b8da5e45/href">https://medium.com/media/935f5c252cb0eea2af44cdb1b8da5e45/href</a></iframe><p>Awesome! Let’s add a small snippet to our driver.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef7d3545a0b952d2446576ea3c3a949a/href">https://medium.com/media/ef7d3545a0b952d2446576ea3c3a949a/href</a></iframe><h4>Test Type Checker</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2db982549db14a966e51fc31ecf56720/href">https://medium.com/media/2db982549db14a966e51fc31ecf56720/href</a></iframe><pre>go test -v<br>=== RUN   TestAST<br>--- PASS: TestAST (0.00s)<br>=== RUN   TestOperations<br>--- PASS: TestOperations (0.00s)<br>=== RUN   TestIdents<br>--- PASS: TestIdents (0.00s)<br>=== RUN   TestFunctions<br>--- PASS: TestFunctions (0.00s)<br>=== RUN   TestParser<br>--- PASS: TestParser (0.00s)<br>=== RUN   TestToken<br>--- PASS: TestToken (0.00s)<br>PASS<br>ok      github.com/Lebonesco/go-compiler        9.020s</pre><p>I made some deliberate choices to leave things out of this language such as classes, for loops, and function scope. Most of the complexities that arise from these occur in the checker and code generator. If I added those elements this post would be a lot lot longer. 😦</p><h3>Code Generation</h3><p>We have finally made it to the last stage! 🎉 🎉 🎉</p><p>In order to handle the most cases with the least amount of hassle every expression will be assigned to a temporary variable. It might make our generated code look bloated, but it will solve for any nested expressions.</p><p>Bloated code won’t have any impact on final program speed because the optimizer will remove any redundancy when we compile our final generated C++ code.</p><p>Our generator will look similar to the type checker. The main difference is that we’ll be passing down a buffer to store the generated code.</p><p>While I chose to compile into C++, you can substitute in any language . The main purpose of this <strong>Go Compiler Guide</strong> was to enable you to be able to understand the pieces well enough to go out and create your own.</p><p>To start:</p><pre>touch gen_test.go<br>mkdir gen<br>cd gen<br>touch gen.go</pre><p>We’ll begin by importing all of the necessary packages and defining three <strong>utility functions, </strong>write() to write generated code to a buffer, check()to do error handling, and freshTemp()to generate <strong>unique</strong> variable names for temporary variables we create on the fly.</p><p><strong>Note:</strong> It’s generally bad practice to use panic()for normal error handling in Go, but I’m tired of writing if statements.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYU0j0j92jLdU4%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYU0j0j92jLdU4%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FYU0j0j92jLdU4%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b8715f2475c30c63a73663a7945c52/href">https://medium.com/media/e6b8715f2475c30c63a73663a7945c52/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c45e6d94c8d4acf5a6c9d1ed3004b7/href">https://medium.com/media/a7c45e6d94c8d4acf5a6c9d1ed3004b7/href</a></iframe><p>Similar to the <strong>checker</strong>, our <strong>generator</strong> has a core dispatch function that accepts a Node and calls the corresponding <strong>gen</strong> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4f3e9ed81d71956b9583917ddc954f3/href">https://medium.com/media/c4f3e9ed81d71956b9583917ddc954f3/href</a></iframe><p>Let’s generate some Statements. genProgram() generates necessary headers and main() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aa7d9d7c2ca552fe038b663096197ff/href">https://medium.com/media/9aa7d9d7c2ca552fe038b663096197ff/href</a></iframe><p>Generating Expressions will look very similar to the code above. The main difference is that a temp variable is returned representing that expression. This helps us handle more complex Expression nesting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dd2d6f09a10ef4d983903f50472605e/href">https://medium.com/media/9dd2d6f09a10ef4d983903f50472605e/href</a></iframe><p>The final piece of code will be our C++ <strong>Builtin types. </strong>Without this nothing will work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d05d3e7eb7f87e677f9fee58ecbb5ffa/href">https://medium.com/media/d05d3e7eb7f87e677f9fee58ecbb5ffa/href</a></iframe><h4>Test Code Generator</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29a7b5cb9d602c44ef19d44e728f0dc4/href">https://medium.com/media/29a7b5cb9d602c44ef19d44e728f0dc4/href</a></iframe><h3>Bringing It All Together</h3><p>We’re now going to combine our <strong>lexer</strong>, <strong>parser</strong>, <strong>AST generator</strong>, <strong>type checker</strong>, and <strong>code generator</strong> into a final runnable program, main.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def3ab7d608940c312eba7dc1c909f78/href">https://medium.com/media/def3ab7d608940c312eba7dc1c909f78/href</a></iframe><p><strong>Note:</strong> I’m running this on a Windows so my C++ compiles into main.exe. If this doesn’t work for you remove the .exe extension.</p><p>To find some test programs to run go to github.com/Lebonesco/go-compiler/examples.</p><pre>go run main.go ./example/function.bx<br>hello Jeff<br>3</pre><p>And there you have it! We have completed a fully working compiler in Go!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCkqpoOOS0BCQU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FCkqpoOOS0BCQU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FCkqpoOOS0BCQU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/7994a1fd6b72f848baca99c90e698390/href">https://medium.com/media/7994a1fd6b72f848baca99c90e698390/href</a></iframe><p>Thank you for taking the time to read this article.</p><p>If you found it helpful or interesting please let me know 👏👏👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d2f33ac6e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/write-a-compiler-in-go-quick-guide-30d2f33ac6e0">How to write a compiler in Go: a quick guide</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Go Json Parser: Batteries Included]]></title>
            <link>https://medium.com/hackernoon/create-a-go-json-parser-batteries-included-9d02d09fe508?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d02d09fe508</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go-json-parser]]></category>
            <category><![CDATA[parser]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Fri, 28 Dec 2018 12:16:00 GMT</pubDate>
            <atom:updated>2019-04-25T09:39:10.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeP3A7A60m6Osl8miEkksQ.jpeg" /></figure><p>The inspiration for this post came from a project at work. I was building a service that required the comparison of two<strong> Json</strong> objects. The catch was that I needed to be able to <strong>replace keys</strong>,<strong> filter out paths</strong>, and <strong>apply comparison functions</strong> to specific nodes.</p><p>Obviously, a standard library comparison function such as reflect.DeepEqual() would not work. 😧</p><p>The solution was to build a<strong> AST</strong>(<em>Abstract Syntax Tree</em>) modeled off of the <strong>Json</strong> objects. Every Node in the tree represents either a string, integer, array, or object.</p><p>By doing this I would allow for the flexibility to more easily apply <a href="https://hackernoon.com/tagged/algorithms">algorithms</a> onto the data.</p><p>To build this we’ll start with the <strong>Lexer</strong> to generate <strong>Tokens</strong>. Then move onto the <strong>Parser </strong>which will take the tokens and match them to <strong>Json</strong> grammar. Finally, we’ll add <strong>AST</strong> hooks to generate the tree.</p><p>The final directory structure:</p><pre>.<br>main.go<br>/lexer<br>    lexer.go<br>    lexer_test.go<br>/token<br>    token.go<br>/parser<br>    parser.go<br>/ast<br>    ast.go</pre><p>If you want to see and run the final results:</p><pre>cd $GOPATH/src/github.com/Lebonesco<br>git clone <a href="https://github.com/Lebonesco/json_parser.git">https://github.com/Lebonesco/json_parser.git</a><br>go run main.go ./examples/test.json</pre><h3>Lexer</h3><p>The lexer’s job is to take in the <a href="https://hackernoon.com/tagged/json">json</a> data and convert it into a stream of tokens. These tokens include: INVALID, EOF, COMMA, COLON, LBRACE, RBRACE, LBRACKET, RBRACKET, STRING, and INTEGER.</p><p><strong>Note:</strong> A lexer is also referred to as a scanner.</p><p>Let’s start down below 👇</p><pre>cd $GOPATH/src/github.com/Lebonesco/json_parser<br>mkdir token<br>cd token<br>touch token.go</pre><p>You have some freedom in how you want to define your tokens. The more data you add to a token the easier it is to debug.</p><p>Note: We’ll be using a rune array, []rune, to store our token literals to allow for <strong>Unicode</strong> characters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8503c490d55396c196f5ac9d60fc71ae/href">https://medium.com/media/8503c490d55396c196f5ac9d60fc71ae/href</a></iframe><p>Next, let’s jump into our lexer 👍</p><pre>mkdir lexer<br>cd lexer<br>touch lexer.go<br>touch lexer_test.go</pre><p>The lexer will track where we are in the input and necessary character look aheads.</p><p>In terms of functionality, it will need to be able to create a new token and peak ahead to the next one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eecb33e832d48f038857eb131e95431b/href">https://medium.com/media/eecb33e832d48f038857eb131e95431b/href</a></iframe><p><strong>Note:</strong> This scanner doesn’t support <strong>Boolean</strong> values, but they could easily be added.</p><h4>Lexer Test</h4><p>Here we will take in a j<strong>son</strong> string and make sure that it outputs the correct stream of tokens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0468fa61c97930952bf3946de1e31142/href">https://medium.com/media/0468fa61c97930952bf3946de1e31142/href</a></iframe><p>To run the test:</p><pre>go test -v<br>=== RUN   TestLexer<br>--- PASS: TestLexer (0.00s)<br>PASS<br>ok      github.com/Lebonesco/json_parser/lexer  0.433s</pre><p>You now have a working<strong> lexer</strong> 🎉 🎉 🎉</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FslOhiKAVFgwr6%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FslOhiKAVFgwr6%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FslOhiKAVFgwr6%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/73ffeb194923f16088b20b8ea6f99155/href">https://medium.com/media/73ffeb194923f16088b20b8ea6f99155/href</a></iframe><h3>Parser</h3><p>This is the part where we take our stream and match it with <strong>json grammar</strong> to produce <strong>AST</strong> nodes.</p><p>If we were to define <strong>json</strong> in terms of regular expressions it would be represented by the grammar defined below 👇</p><pre>JSON : value<br>Value :  Object | Array | String | Integer | Bool | Null<br>Array : &#39;[&#39; [Value] {&#39;,&#39; Value}&#39;]&#39;<br>Object : &#39;{&#39; [Property] {&#39;,&#39; Property} &#39;}&#39;<br>Property : String &#39;:&#39; Value</pre><p>In the above syntax, [expression] means the expression occurs one or more times and {expression} means that it occurs zero or more times.</p><p>There are tools like gocc that will generate a lexer and/or parser if you provide the regular expressions. That’s the recommended way to go if you’re dealing with something more complicated.</p><p>But since <strong>Json</strong> is fairly simple, we’ll do it by hand! 👐</p><p>Let’s construct the AST nodes that will represent our final results.</p><pre>mkdir ast<br>cd ast<br>touch ast.go</pre><p>The nodes are fairly simple. If we cared more about error handling and tracking node hashes, like in my use case, we could store more data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3db73bf7efaa4009901bf4d8f963bb2b/href">https://medium.com/media/3db73bf7efaa4009901bf4d8f963bb2b/href</a></iframe><p><strong>Note:</strong> Because Go uses composition instead of inheritance we need to apply the TokenLiteral() method to each node type in order for each to be interpreted as a Json node.</p><p>Now onto the Parser!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774f6953486fb9f19dd11896b4a3ed5b/href">https://medium.com/media/774f6953486fb9f19dd11896b4a3ed5b/href</a></iframe><p>Let’s bring it all together and write our driver, main.go.</p><p><strong>Note: </strong>json.MarshalIndent() is a nice substitute to json.Marshal() to get prettier <strong>json</strong> outputs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06e61150237c993889c2ce0d4e2705d9/href">https://medium.com/media/06e61150237c993889c2ce0d4e2705d9/href</a></iframe><p>To run:</p><pre>go run main.go ./exampes/test.json</pre><p>All Done 😄</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F8UF0EXzsc0Ckg%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F8UF0EXzsc0Ckg%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F8UF0EXzsc0Ckg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="261" frameborder="0" scrolling="no"><a href="https://medium.com/media/1527442f794ef0aef56e977eb523b7a1/href">https://medium.com/media/1527442f794ef0aef56e977eb523b7a1/href</a></iframe><p>Now that we can generate an <strong>AST, </strong>it’s easy to add a rolling hash to each node and do all of the other custom operations such as:</p><ul><li><strong>substitute node values</strong></li><li><strong>filter out nodes</strong></li><li><strong>apply special comparison functions to nodes</strong></li></ul><p>I’ll leave those extensions to the reader. Feel free to drop links to your work in the comments. I’d love to see what you come up with. 👍</p><p>Thank you for taking the time to read this article.</p><p>If you found it helpful or interesting please let me know 👏👏👏.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d02d09fe508" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/create-a-go-json-parser-batteries-included-9d02d09fe508">Create a Go Json Parser: Batteries Included</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Go Pipelines in 5 minutes]]></title>
            <link>https://medium.com/@j.d.livni/understanding-go-pipelines-in-5-minutes-2906a5c41496?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/2906a5c41496</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Thu, 18 Oct 2018 19:35:19 GMT</pubDate>
            <atom:updated>2018-10-18T19:35:19.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yIam3Ctoj7ErEWlwdspYpg.jpeg" /></figure><p>Pipelines are awesome and offer huge performance benefits! Whether you’re new to Go, pipelines, or both, you should have this design pattern in your engineering toolkit.</p><h4>Why Pipelines?</h4><p>Before getting into how to build a running example, lets talk about why you should even care.</p><p>To put it simply, they allow for the <strong>lazy evaluation </strong>of large amounts of data. But for those of us who haven’t taking <em>Programming Languages 420</em> what does that even mean?</p><blockquote>Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed</blockquote><p>For example, through lazy evaluation you could represent an infinite array of data because when it is being processed you are only doing work on the index that you’re currently at.</p><p>This is opposed to loading the entire memory block into memory. An array of infinite length would probably make your computer unhappy 😦</p><p>To demonstrate the benefits we’ll build a set of<strong> lazy</strong> and <strong>eager</strong> functions to process an array of data and compare their performances.</p><h4>Eager Code</h4><p>Below we have our basic eager functions. Each function does work on the <strong>entire</strong> array before passing onto the next one.</p><pre>package main<br>import time</pre><pre>var vals []int = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}</pre><pre>func doubleEager(array []int) []int {<br>    for idx, val := range array {<br>        array[idx] += val<br>        time.Sleep(100 * time.Millisecond)<br>    }<br>    return array<br>}</pre><pre>func squareEager(array []int) []int {<br>    for idx, val := range array {<br>        array[idx] = val * val<br>        time.Sleep(100 * time.Millisecond)<br>    }<br>    return array<br>}</pre><pre>func main() {<br>    res := squareEager(doubleEager(vals))<br>}</pre><h4>Lazy Code</h4><p>Now, lets shift over to our lazy code. This is just an initial preprocessing step to convert the array into a stream of integers. The pattern shown here is going to be similar to all of our “lazy functions”, in that all of the computation will occur inside of a <strong>goroutine</strong> and the result will be pushed to a <strong>stream</strong> that is returned by the function.</p><pre>....<br>func generate(nums []int) &lt;-chan int {<br>    out := make(chan int)<br>    go func() {<br>        defer close(out)<br>        for _, n := range nums {<br>            out &lt;- n<br>            time.Sleep(100 * time.Millisecond)<br>        }<br>     }()<br>     return out<br>}</pre><pre>func main() {<br>    c := generate(vals) <br>    ...<br>}</pre><p><em>Note: We added the </em><strong><em>sleep</em></strong><em> so that it will be easier to see the difference in performance later on.</em></p><p>The next step is to write the rest of our lazy functions.</p><pre>...<br>func doubleLazy(in &lt;-chan int) &lt;-chan int {<br> out := make(chan int)<br> go func() {<br>  defer close(out)<br>  for n := range in {<br>   out &lt;- n * 2<br>   time.Sleep(100 * time.Millisecond)<br>  }<br> }()<br> return out<br>}</pre><pre>func squareLazy(in &lt;-chan int) &lt;-chan int {<br> out := make(chan int)<br> go func() {<br>  defer close(out)<br>  for n := range in {<br>   out &lt;- n * n<br>   time.Sleep(100 * time.Millisecond)<br>  }<br> }()<br> return out<br>}<br>...</pre><pre>func main() {<br>    c := generate(vals)<br>    d := doubleLazy(c)<br>    s := squareLazy(d)<br>    ....<br>}</pre><p>We are almost done! All we need now is to add the code that will compare the run time of our two solutions.</p><p>We add a count to track how many values have begun to be processed in the lazy evaluation.</p><pre>...<br>func main() {<br>    start := time.Now()<br>    ... // lazy code<br>    count := len(vals) - 1<br>    for _ = range s {<br>        count--<br>        if count == 0 {<br>            log.Printf(&quot;Lazy Execution took %s&quot;, time.Since(start))<br>            continue<br>        }<br>    }<br>    <br>    start2 = time.Now()<br>    ... // eager code<br>    log.Println(&quot;Eager Execution took %s&quot;, time.Since(start2))<br>}</pre><p><strong>Results:</strong></p><pre>2018/08/30 20:15:37 Lazy Execution took 1.0125718s</pre><pre>2018/08/30 20:15:40 Eager Execution took 2.429461869s</pre><p>Well, there you have it. Thanks for reading until the end! I guess, sometimes it does pay off to be lazy.</p><p>Thank you for taking the time to read my article.</p><p>If you found this article helpful, let me know 👏👏👏.</p><p>If you want to read more click the “follow” button below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2906a5c41496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write a Go Worker Pool in 15 minutes]]></title>
            <link>https://medium.com/@j.d.livni/write-a-go-worker-pool-in-15-minutes-c9b42f640923?source=rss-d24b5a950413------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9b42f640923</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[worker-pool]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Joseph Livni]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 00:02:05 GMT</pubDate>
            <atom:updated>2018-10-09T20:50:50.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ugshDOhXfC287WWhG4IfSA.jpeg" /></figure><p>At my job I was building a service in Go that needed to process a lot of user requests quickly. By encapsulating it with a goroutine pool, performance increased by 20x. This post will go over how to create a worker pool for your own projects.</p><p>If you want to download the final results check it out <a href="https://github.com/Lebonesco/go_worker_pool">here</a>.</p><p>In this post we will:</p><ul><li>Create some mock work to do</li><li>Create the Worker Pool</li><li>Run Benchmark tests</li></ul><p>This is the file structure:</p><pre>/go_worker_pool<br>    /work<br>        work.go<br>    /pool<br>        worker.go<br>        dispatcher.go<br>    bench_test.go<br>    main.go</pre><p>The directory path that I will be building this:</p><pre>go/src/github.com/Lebonesco/go_worker_pool</pre><p>The final results will look something like this:</p><pre>$ go run main.go<br>2018/10/06 15:53:43 starting application...<br>2018/10/06 15:53:43 starting worker:  1<br>2018/10/06 15:53:43 starting worker:  2<br>2018/10/06 15:53:43 starting worker:  3<br>2018/10/06 15:53:43 starting worker:  4<br>2018/10/06 15:53:43 starting worker:  5<br>2018/10/06 15:53:43 creating jobs...<br>worker [2] - created hash [2376065843] from word [iCMRAjWw]<br>worker [4] - created hash [121297580] from word [xhxKQFDa]<br>worker [1] - created hash [3193224551] from word [XVlBzgba]<br>worker [3] - created hash [1481401259] from word [hTHctcuA]<br>worker [5] - created hash [166906897] from word [FpLSjFbc]<br>worker [5] - created hash [1752784812] from word [QYhYzRyW]<br>...</pre><h4>Create Some Mock Work</h4><p>To simulate a process that will take some time to complete, we’ll create a bunch of jobs represented as random strings that will have some work done on them, which in this case will be the generation of a string hash.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38a11e8c5ff3133e9db32f83b15c672e/href">https://medium.com/media/38a11e8c5ff3133e9db32f83b15c672e/href</a></iframe><p><em>DoWork()</em> takes in a <em>string</em> and <em>worker id</em> then computes a string hash and sleeps for a second before printing the work results. In order to print out when each job finishes set:</p><pre>$ export DEBUG=&quot;true&quot;</pre><p>We make this configurable because when we later run benchmark tests this output will be unnecessary and clutter up the results.</p><h4>Create the Worker Pool</h4><p>Next, lets dive into building the actual worker pool. It will be made up of three parts: the <em>dispatcher</em> (instantiates and connects all of the workers with the worker pool), the <em>workers</em> (grabs a waiting job and then does work), and the <em>collector</em> (collects jobs and distributes them to workers).</p><p>The import things to note from the below code are the <em>WorkerChannel</em> in the Worker struct and the <em>Start()</em> function.</p><p>A popular phrase when it comes to Go is “<em>Do not communicate by sharing memory; instead, share memory by communicating.</em>” This is the purpose of the <em>WorkerChannel</em> and how the Worker Pool communicates with the workers. The <em>WorkerChannel </em>stores all of the channels of available workers. When a job arrives the collector pulls a worker channel from <em>WorkerChannel</em> and passes the job to it which is then received by the worker. Inversely, when the worker is finished, it pushes its channel back onto <em>WorkerChannel to wait for the next job</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5596cdf42afc8788b43089b423bb2e9/href">https://medium.com/media/d5596cdf42afc8788b43089b423bb2e9/href</a></iframe><p>Awesome! We are close to being done. To finish up the Worker Pool lets complete the dispatcher and collector. Before going into the design I want you to be aware that there’s a lot of ways to design a worker pool in terms of how the pieces fit together.</p><p>Some ways work better than others depending on coding readability and how you want the code to be used. As long as you have the main pieces: <em>worker, dispatcher</em>, and <em>collector</em> you should be able to design your own. For example some people make their collector separate from their dispatcher. However, in my case I want to return a <em>Collector</em> struct from my dispatcher because I felt that it helped in terms of readability on the users end. The user in this case being anyone who wanted to use this worker pool with their own code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55c25d1136eb0faf0e5d287ef78e35cb/href">https://medium.com/media/55c25d1136eb0faf0e5d287ef78e35cb/href</a></iframe><p>Finally, lets create the driver that will run the application. It will consistent of a <em>main()</em> function that will instantiate the worker pool and create jobs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8febec600f2b48abc2de41f59b15c3a1/href">https://medium.com/media/8febec600f2b48abc2de41f59b15c3a1/href</a></iframe><h4>Benchmark tests!</h4><p>To make sure that this actually works lets run a simple benchmark test. Go makes this very easy by having a built in test framework.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a8e289a92582f771aab4358f1d706c/href">https://medium.com/media/32a8e289a92582f771aab4358f1d706c/href</a></iframe><p>Then we can run:</p><pre>$ go test -bench=.<br>starting worker:  1<br>starting worker:  2<br>starting worker:  3<br>starting worker:  4<br>starting worker:  5<br>goos: windows<br>goarch: amd64<br>pkg: tutorials/concurrent-limiter<br>BenchmarkConcurrent-4           1        3001744600 ns/op<br>BenchmarkNonConcurrent-4           1        20006911100 ns/op<br>PASS<br>ok      tutorials/concurrent-limiter    23.291s</pre><p>Well, there we have it. The evidence is in. The worker pool does provide a significant performance improvement. In addition, the longer each single job takes to complete and more workers you have running the more significant performance increase you’ll see.</p><p>Thank you for taking the time to read my article.</p><p>If you found this article helpful, let me know 👏👏👏.</p><p>If you want to read more click the “follow” button below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9b42f640923" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>