<?xml version="1.0" encoding="utf-8" ?><rss version="2.0" xmlns:tt="http://teletype.in/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>Anton Vasiljev</title><generator>teletype.in</generator><description><![CDATA[Trivial things about software development]]></description><image><url>https://img2.teletype.in/files/92/84/92844821-d886-485b-bc58-cf419e240721.png</url><title>Anton Vasiljev</title><link>https://blog.antono.info/</link></image><link>https://blog.antono.info/?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><atom:link rel="self" type="application/rss+xml" href="https://teletype.in/rss/antono?offset=0"></atom:link><atom:link rel="next" type="application/rss+xml" href="https://teletype.in/rss/antono?offset=10"></atom:link><atom:link rel="search" type="application/opensearchdescription+xml" title="Teletype" href="https://teletype.in/opensearch.xml"></atom:link><pubDate>Thu, 21 May 2026 21:53:33 GMT</pubDate><lastBuildDate>Thu, 21 May 2026 21:53:33 GMT</lastBuildDate><item><guid isPermaLink="true">https://blog.antono.info/rJyKtUCbV</guid><link>https://blog.antono.info/rJyKtUCbV?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/rJyKtUCbV?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>Something about Cargo</title><pubDate>Sat, 05 Jan 2019 18:50:22 GMT</pubDate><category>rust</category><category>aoc</category><description><![CDATA[<img src="https://teletype.in/files/04/0455f396-f4bf-4275-a7e6-85b109d138a1.jpeg"></img>Photo by Philipp Medicus (CC BY-NC 2.0)]]></description><content:encoded><![CDATA[
  <figure class="m_column">
    <img src="https://teletype.in/files/04/0455f396-f4bf-4275-a7e6-85b109d138a1.jpeg" width="2000" />
  </figure>
  <p><em>Photo by <a href="https://www.flickr.com/photos/p_medicus/" target="_blank">Philipp Medicus</a> (CC BY-NC 2.0)</em></p>
  <hr />
  <blockquote>Cargo is a tool that allows Rust packages to declare their various dependencies and ensure that you’ll always get a repeatable build.</blockquote>
  <p>This week i found something interesting about cargo.</p>
  <p>First there is a well organized <a href="https://doc.rust-lang.org/cargo/index.html" target="_blank">cargo book</a>. Short and clear text. Cargo is easy to understand if you have ruby bundler or npm background.</p>
  <p>Second: there is a <a href="https://github.com/rust-lang/cargo/wiki/Third-party-cargo-subcommands" target="_blank">list of third party cargo sub commands</a>. Extensions I liked very much:</p>
  <ul>
    <li><a href="https://github.com/rust-lang/rustfmt" target="_blank">cargo fmt</a> - to format all the code with rustfmt (a tool for formatting Rust code according to style guidelines).</li>
    <li><a href="https://github.com/kbknapp/cargo-count" target="_blank">cargo count</a> - to produce statistics for the project (see example below)</li>
    <li><a href="https://github.com/mmstick/cargo-deb" target="_blank">cargo-deb</a>, <a href="https://github.com/rustrpm/cargo-rpm" target="_blank">cargo-rpm</a>, <a href="https://github.com/kstep/cargo-pkgbuild" target="_blank">cargo-pkgbuild</a> - for native linux packaging</li>
    <li><a href="https://github.com/sfackler/cargo-tree" target="_blank">cargo-tree</a> - list dependency tree just like &#x60;npm ls&#x60;</li>
    <li><a href="https://github.com/RustSec/cargo-audit" target="_blank">cargo-audit</a> - Audit Cargo.lock for crates with security vulnerabilities</li>
  </ul>
  <pre>$ cargo install cargo-count
... skip ...
$ cargo count --all --language rs
Gathering information...
         Language  Files  Lines  Blanks  Comments  Code
         --------  -----  -----  ------  --------  ----
         Rust      7      1324   197     423       704
         --------  -----  -----  ------  --------  ----
Totals:            7      1324   197     423       704
</pre>
  <pre>$ cargo install cargo-tree
... skip ...
$ cargo tree

aoc2018 v0.1.0 (/Users/antono/Code/rust/aoc2018)                                                                                                       
├── chrono v0.4.6
│   ├── num-integer v0.1.39
│   │   └── num-traits v0.2.6
│   ├── num-traits v0.2.6 (*)
│   └── time v0.1.41
│       └── libc v0.2.45
│       [dev-dependencies]
│       └── winapi v0.3.6
├── indoc v0.3.1
│   ├── indoc-impl v0.3.1
│   │   ├── proc-macro-hack v0.5.4
│   │   │   ├── proc-macro2 v0.4.24
│   │   │   │   └── unicode-xid v0.1.0
│   │   │   ├── quote v0.6.10
│   │   │   │   └── proc-macro2 v0.4.24 (*)
│   │   │   └── syn v0.15.23
│   │   │       ├── proc-macro2 v0.4.24 (*)
│   │   │       ├── quote v0.6.10 (*)
│   │   │       └── unicode-xid v0.1.0 (*)
│   │   ├── proc-macro2 v0.4.24 (*)
│   │   ├── quote v0.6.10 (*)
│   │   ├── syn v0.15.23 (*)
│   │   └── unindent v0.1.3
│   └── proc-macro-hack v0.5.4 (*)
├── lazy_static v1.2.0
└── regex v1.1.0
    ├── aho-corasick v0.6.9
    │   └── memchr v2.1.2
    │       ├── cfg-if v0.1.6
    │       └── libc v0.2.45 (*)
    │       [build-dependencies]
    │       └── version_check v0.1.5
    ├── memchr v2.1.2 (*)
    ├── regex-syntax v0.6.4
    │   └── ucd-util v0.1.3
    ├── thread_local v0.3.6
    │   └── lazy_static v1.2.0 (*)
    └── utf8-ranges v1.0.2

</pre>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/r1TJSAGbV</guid><link>https://blog.antono.info/r1TJSAGbV?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/r1TJSAGbV?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>AOC: Puzzle 4: struct and impl</title><pubDate>Thu, 27 Dec 2018 22:40:36 GMT</pubDate><category>rust</category><description><![CDATA[DISCLAIMER]]></description><content:encoded><![CDATA[
  <p id="Jo1D"><a href="https://blog.antono.info/Syuxv7s1E" target="_blank">DISCLAIMER</a></p>
  <p id="seBB">Each time i dig into some interesting topic <a href="https://github.com/antono/aoc2018" target="_blank">while solving Advent Of Code puzzles</a>. This time it was rust structs and method implementation for structs.</p>
  <p id="P5tT">For tracking guard shift (<a href="https://github.com/antono/aoc2018/blob/master/src/bin/4.rs#L1" target="_blank">see puzzle details</a>) i introduced ShiftTimeline structure:</p>
  <pre id="t0D5" data-lang="rust">struct ShiftTimeline {
    data: Vec&lt;u32&gt;,
}</pre>
  <p id="DY81">The idea was to keep minutes between the guard was sleeping in vector.</p>
  <blockquote id="qCth">A <em>struct</em>, or <em>structure</em>, is a custom data type that lets you name and package together multiple related values that make up a meaningful group. If you’re familiar with an object-oriented language, a <em>struct</em>is like an object’s data attributes. In this chapter, we’ll compare and contrast tuples with structs, demonstrate how to use structs, and discuss how to define methods and associated functions to specify behavior associated with a struct’s data. Structs and enums (discussed in Chapter 6) are the building blocks for creating new types in your program’s domain to take full advantage of Rust’s compile time type checking.</blockquote>
  <p id="jfn4">First i was going to add more properties but after all I left only one. Its does not makes much sense to keep structure for single field... But i decided to keep it in order to group methods around it. Reading the <a href="https://doc.rust-lang.org/1.30.0/book/second-edition/ch05-03-method-syntax.html" target="_blank">rust book about methods</a>:</p>
  <blockquote id="vZVW"><em>Methods</em> are similar to functions: they’re declared with the <code>fn</code> keyword and their name, they can have parameters and a return value, and they contain some code that is run when they’re called from somewhere else. However, methods are different from functions in that they’re defined within the context of a struct, and their first parameter is always <code>self</code>, which represents the instance of the struct the method is being called on.</blockquote>
  <p id="o62k">When used ShiftTimeline structure i found duplicated data initialization code:</p>
  <pre id="dBkb" data-lang="rust">let timeline = ShiftTimeline { data: Vec::new() };</pre>
  <p id="C50f">So implemented simple initializer:</p>
  <pre id="aJjo" data-lang="rust">struct ShiftTimeline {
    data: Vec&lt;u32&gt;,
}

impl ShiftTimeline {
    fn new() -&gt; ShiftTimeline {
        ShiftTimeline { data: Vec::new() }
    }
}</pre>
  <p id="NsKj">Now it is possible to use ShiftTimeline::new() to get property initialized. One more method accepting reference to self for write access to structure fields:</p>
  <pre id="yF43" data-lang="rust">impl ShiftTimeline {

    ...

    fn record_sleep_time(&amp;mut self, asleep_at: NaiveDateTime, awake_at: NaiveDateTime) {
       let start_min = asleep_at_time.minute();
       let end_min = awake_at.minute();
       for idx in start_min..end_min {
           self.data.push(idx);
       }
    }
}

...

shift_timeline.record_sleep_time(...)</pre>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/aoc-2018-puzzle-2.2-rust</guid><link>https://blog.antono.info/aoc-2018-puzzle-2.2-rust?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/aoc-2018-puzzle-2.2-rust?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>AOC: Puzzle 2.2 in rust</title><pubDate>Fri, 14 Dec 2018 23:45:07 GMT</pubDate><category>rust</category><description><![CDATA[Input is the same as for 2.1. This time I must find ids that differs by one letter in the same position:]]></description><content:encoded><![CDATA[
  <p id="Hjlc">Input is <a href="https://github.com/antono/aoc2018/blob/master/inputs/2.txt" target="_blank">the same as for 2.1</a>. This time I must find ids that differs by one letter in the same position:</p>
  <blockquote id="HyKh">The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct boxes.</blockquote>
  <blockquote id="yw8Y">What letters are common between the two correct box IDs?</blockquote>
  <p id="yKrc">In order to compare ids I going to iteratively replace 1 char in all of them with 0 (which ins not part of original alphabet) and use results of replacement as hash keys while storing original ids to values for the key.</p>
  <p id="x1OL">Pseudocode for solution:</p>
  <pre id="tcpC" data-lang="rust">ids = get_input_ids
hash = {}

for original_id in ids
  for id_with_1_char_replaced in combinations_with_1_char_replaced(original_id)
    hash[id_with_1_chars_replaced].push(original_id)

solution = hash.values.find { |arr| arr.any? }

def combinations_with_1_char_replaced(original)
    result = []
    
    original.len.times |idx|
         id_as_array = original.clone()
         id_as_array[idx0] = 0
         result.push(id_as_array.join)
   
    return result</pre>
  <p id="q7Vg">Solution in rust:</p>
  <pre id="AOsJ" data-lang="rust">use std::char;

fn part_two() {
    let input = utils::read_puzzle_input(2);
    let mut results: HashMap&lt;String, Vec&lt;_&gt;&gt; = HashMap::new();
    let mut lines_count = 0;
    let mut ids_count = 0;

    for id in input.lines() {
        let ids = all_valiants_with_1_letter_replaced(id);

        lines_count += 1;

        for id_changed in ids {
            ids_count += 1;
            results.entry(id_changed)
                .and_modify(|vec| vec.push(id.clone()))
                .or_insert(vec!(id));
        }
    }

    let mut res = vec!();

    for (matcher, ids) in &amp;results {
        if ids.len() &gt; 1 {
            res.push((matcher.clone(), ids.clone()));
        }
    }

    println!(&quot;{}&quot;, &quot;-&quot;.repeat(100));

    for tup in &amp;res {
        println!(&quot;{:?}&quot;, tup);
    }

    println!(&quot;{}&quot;, &quot;-&quot;.repeat(100));

    println!(&quot;Res.len: {:?}&quot;, res.len());
    println!(&quot;Keys: {}&quot;, results.keys().len());
    println!(&quot;Values: {}&quot;, results.values().fold(0, |acc, arr| acc + arr.len()));
    println!(&quot;Lines: {}, ids: {}&quot;, lines_count, ids_count);
}


fn all_valiants_with_1_letter_replaced(id: &amp;str) -&gt; Vec&lt;String&gt; {
    let mut result: Vec&lt;String&gt; = vec!();
    let id_map = id.chars().collect::&lt;Vec&lt;char&gt;&gt;();
    let size = id.len();

    for idx in 0..size {
        let mut cur_map = id_map.clone();
        cur_map[idx] = &#x27;0&#x27;;
        result.push(cur_map.into_iter().collect());
    }

    return result;
}</pre>
  <p id="FNPg">Running the code:</p>
  <pre id="sBV5">➜  aoc2018 git:(master) ✗ cargo run --bin 2
warning: unused manifest key: package.edition
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running &#x60;target/debug/2&#x60;
----------------------------------------------------------------------------------------------------
(&quot;cvgywxqubnuaefmsl0jdrpfzyi&quot;, [&quot;cvgywxqubnuaefmsldjdrpfzyi&quot;, &quot;cvgywxqubnuaefmslkjdrpfzyi&quot;])
----------------------------------------------------------------------------------------------------
Res.len: 1
Keys: 6499
Values: 6500
Lines: 250, ids: 6500
</pre>
  <hr />
  <blockquote id="3hPC">What letters are common between the two correct box IDs?</blockquote>
  <p id="KBg8">Removing 0 from hash key: &quot;cvgywxqubnuaefmsljdrpfzyi&quot;. Submitting.</p>
  <blockquote id="cMpA">Your puzzle answer was <code>cvgywxqubnuaefmsljdrpfzyi</code>. Both parts of this puzzle are complete! They provide two gold stars: **</blockquote>
  <p id="ZPfI"><a href="https://github.com/antono/aoc2018" target="_blank">The Code</a></p>
  <hr />
  <p id="mBF5"><a href="https://blog.antono.info/Syuxv7s1E" target="_blank">Disclaimer</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/rJlqpIRJ4</guid><link>https://blog.antono.info/rJlqpIRJ4?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/rJlqpIRJ4?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>Borrowing in Rust</title><pubDate>Wed, 12 Dec 2018 13:32:45 GMT</pubDate><category>aoc</category><category>rust</category><description><![CDATA[<img src="https://teletype.in/files/82/82fbe53d-9aae-4cdf-b1fc-5ce5800367a2.jpeg"></img>Doing puzzle #2 of advent of code challenge in Rust. The puzzle is pretty simple. Input looks like this:]]></description><content:encoded><![CDATA[
  <figure class="m_column">
    <img src="https://teletype.in/files/82/82fbe53d-9aae-4cdf-b1fc-5ce5800367a2.jpeg" width="1018" />
  </figure>
  <p>Doing <a href="https://adventofcode.com/2018/day/2" target="_blank">puzzle #2 of advent of code</a> challenge in Rust. The puzzle is pretty simple. Input looks like this:</p>
  <pre>mvgowxqubnhaefjslkjlrptzyi
pvgowlqubnhaefmslkjdrpteyi
ovgowoqubnhaefmslkjnrptzyi
cvgowxqubnrxefmslkjdrptzyo
cvgowxqubnhaefmsokjdrprzyf
cvgowxqubnhjeflslkjgrptzyi
...
</pre>
  <p>The task is:</p>
  <blockquote>...count the number that have an ID <strong>containing exactly two of any letter</strong> and then separately count those with <strong>exactly three of any letter</strong>. You can <strong>multiply those two counts together</strong> to get [an answer]...</blockquote>
  <p>Pseudocode solution would look like:</p>
  <pre>for line in input
   counters = count_letters(line)

seen_two_letters = 0
seen_three_letters = 0

for counter in counters
   if counter.values.includes(2)
      seen_two_letters += 1
   if counter.values.include(3)
      seen_three_letters += 1

print seen_two_letters * seen_three_letters
</pre>
  <p>Let&#x27;s do it in rust. Without much optimization i going to use vector fo <a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html" target="_blank">HashMap</a>s to store char counts for each line. Then iterate over them and count hashes having 2 or 3 among values.</p>
  <pre>extern crate utils;
use std::collections::HashMap;

fn part_one() {
    let input = utils::read_puzzle_input(2);

    for line in input.lines() {
        let mut counters: HashMap&lt;char, u8&gt; = HashMap::new();

        for chr in line.chars() {
            match counters.get(&amp;chr).cloned() {
                Some(count) =&gt; counters.insert(chr, count + 1),
                None =&gt; counters.insert(chr, 1),
            };
        }
    }
}
</pre>
  <p>Running the code:</p>
  <pre>➜  aoc2018 git:(master) ✗ cargo run --bin 2
   Compiling aoc2018 v0.1.0 (file:///Users/antono/Code/rust/aoc2018)
error[E0502]: cannot borrow &#x60;counters&#x60; as mutable because it is 
also borrowed as immutable
  --&gt; src/bin/2.rs:57:32
   |
56 |             match counters.get(&amp;chr) {
   |                   -------- immutable borrow occurs here
57 |                 Some(count) =&gt; counters.insert(chr, count + 1),
   |                                ^^^^^^^^ mutable borrow occurs here
58 |                 None =&gt; counters.insert(chr, 1),
59 |             };
   |             - immutable borrow ends here

error[E0502]: cannot borrow &#x60;counters&#x60; as mutable because it is 
also borrowed as immutable
  --&gt; src/bin/2.rs:58:25
   |
56 |             match counters.get(&amp;chr) {
   |                   -------- immutable borrow occurs here
57 |                 Some(count) =&gt; counters.insert(chr, count + 1),
58 |                 None =&gt; counters.insert(chr, 1),
   |                         ^^^^^^^^ mutable borrow occurs here
59 |             };
   |             - immutable borrow ends here

error: aborting due to 2 previous errors

For more information about this error, try &#x60;rustc --explain E0502&#x60;.
error: Could not compile &#x60;aoc2018&#x60;.

To learn more, run the command again with --verbose.

</pre>
  <p>Re-reading topic on <a href="https://doc.rust-lang.org/1.11.0/book/ownership.html" target="_blank">ownership</a> and <a href="https://doc.rust-lang.org/1.11.0/book/references-and-borrowing.html" target="_blank">borrowing</a> from Rust Book. The concept of ownership looks clear to me. Borrowing and mutable borrowing was not. For proper borrowing one should obey some rules:</p>
  <blockquote>First, any borrow must last for a scope no greater than that of the owner. <em>Second, you may have one or the other of these two kinds of borrows, but not both at the same time: </em>one or more references (<code>&amp;T</code>) to a resource, <strong>exactly one mutable reference</strong> (<code>&amp;mut T</code>).</blockquote>
  <p>So the problem is that i borrowed counters hash map for both reading and writing. Since HashMap#get returns an Option with reference to the value (stored in heap). At the same time counter.insert() borrowing hash data as mutable in order to modify hash data (in heap). Rust denies this in order to guarantee memory safety and avoid race conditions:</p>
  <blockquote>Ownership is how Rust achieves its largest goal, memory safety.</blockquote>
  <p>So one of approaches is to avoid borrowing hash value for reading is just copy the value. Documentation for Option gives helpful <a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.cloned" target="_blank">.cloned()</a> method.</p>
  <blockquote>Maps an <code>Option&lt;&amp;T&gt;</code> to an <code>Option&lt;T&gt;</code> by cloning the contents of the option.</blockquote>
  <p>I&#x27;ll use the method when getting hash value:</p>
  <pre>fn part_one() {
    let input = utils::read_puzzle_input(2);

    for line in input.lines() {
        let mut counters: HashMap&lt;char, u8&gt; = HashMap::new();

        for chr in line.chars() {
            match counters.get(&amp;chr).cloned() {
                Some(count) =&gt; counters.insert(chr, count + 1),
                None =&gt; counters.insert(chr, 1),
            };
        }

        println!(&quot;{:?}&quot;, counters.values());
    }
}
</pre>
  <p>Running the code:</p>
  <pre>cargo run --bin 2
   Compiling aoc2018 v0.1.0 (file:///Users/antono/Code/rust/aoc2018)
    Finished dev [unoptimized + debuginfo] target(s) in 0.62 secs
     Running &#x60;target/debug/2&#x60;
[1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1]
[1, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1]
[1, 1, 2, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2]
[1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]
[1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1]
...
</pre>
  <p>It worked. The only thing is i doing copy of value each time i need to avoid read only borrowing. One smart person suggested me to use <a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry" target="_blank">HashMap#entry()</a> in order to get hash Entry for in place modification. Entry itself has a lot of useful methods. <a href="https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.and_modify" target="_blank">Entry#and_modify()</a> looks exactly what i need. Examples from docs:</p>
  <pre>use std::collections::HashMap;

let mut map: HashMap&lt;&amp;str, u32&gt; = HashMap::new();

map.entry(&quot;poneyland&quot;)
   .and_modify(|e| { *e += 1 })
   .or_insert(42);

assert_eq!(map[&quot;poneyland&quot;], 42);
</pre>
  <p>Wow. I&#x27;ll change my code a from this:</p>
  <pre>   for line in input.lines() {
        let mut counters: HashMap&lt;char, u8&gt; = HashMap::new();

        for chr in line.chars() {
            match counters.get(&amp;chr).cloned() {
                Some(count) =&gt; counters.insert(chr, count + 1),
                None =&gt; counters.insert(chr, 1),
            };
        }
   }
</pre>
  <p>to this:</p>
  <pre>    for line in input.lines() {
        let mut counters: HashMap&lt;char, u8&gt; = HashMap::new();

        for chr in line.chars() {
            counters
                .entry(chr)
                .and_modify(|count| { *count += 1})
                .or_insert(1);
        }
    }

</pre>
  <p>Ok. Time to finish the AOC puzzle. I counted all letters in all ids. Now i need count:</p>
  <blockquote><em>...count the number that have an ID <strong>containing exactly two of any letter</strong> and then separately count those with <strong>exactly three of any letter</strong>. You can <strong>multiply those two counts together</strong> to get [an answer]...</em></blockquote>
  <pre># pseudocode

seen_two_letters = 0
seen_three_letters = 0

for counter in counters
   if counter.values.includes(2)
      seen_two_letters += 1
   if counter.values.include(3)
      seen_three_letters += 1

print seen_two_letters * seen_three_letters
</pre>
  <p>Converting to rust:</p>
  <pre>extern crate utils;
use std::collections::HashMap;

fn part_one() {
    let input = utils::read_puzzle_input(2);
    let mut seen_two_letters_count = 0;
    let mut seen_three_letters_count = 0;

    for line in input.lines() {
        let mut counter: HashMap&lt;char, u8&gt; = HashMap::new();

        for chr in line.chars() {
            counter
                .entry(chr)
                .and_modify(|count| { *count += 1})
                .or_insert(1);
        }

        if counter.values().find(|v| { **v == 2 }).is_some() {
            seen_two_letters_count += 1;
        }

        if counter.values().find(|v| { **v == 3 }).is_some() {
            seen_three_letters_count += 1;
        }
    }

    println!(&quot;{}&quot;, seen_three_letters_count * seen_two_letters_count);
}
</pre>
  <p>Running:</p>
  <pre>➜  aoc2018 git:(master) ✗ cargo run --bin 2
   Compiling aoc2018 v0.1.0 (file:///Users/antono/Code/rust/aoc2018)
    Finished dev [unoptimized + debuginfo] target(s) in 0.62 secs
     Running &#x60;target/debug/2&#x60;
5368
</pre>
  <p>The number accepted!</p>
  <blockquote>Your puzzle answer was <code>5368</code>. The first half of this puzzle is complete! It provides one gold star: *</blockquote>
  <hr />
  <p><a href="https://blog.antono.info/Syuxv7s1E" target="_blank">Disclaimer</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/rkoLYw01V</guid><link>https://blog.antono.info/rkoLYw01V?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/rkoLYw01V?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>AOC: Sharing code in Rust</title><pubDate>Wed, 12 Dec 2018 10:56:19 GMT</pubDate><category>rust</category><category>aoc</category><description><![CDATA[After first puzzle in advent of code i found a function that can be reused:]]></description><content:encoded><![CDATA[
  <p>After first puzzle in advent of code i found a function that can be reused:</p>
  <pre>use std::fs::File;
use std::io::prelude::*;

// TODO: Share between puzzles...
fn read_puzzle_input(number: u8) -&gt; String {
    let mut input =
        File::open(format!(&quot;./inputs/{}.txt&quot;, number))
              .expect(&quot;Puzzle input not found...&quot;);

    let mut text = String::new();

    input
        .read_to_string(&amp;mut text)
        .expect(&quot;cannot read input file&quot;);

    return text;
}
</pre>
  <p>I going to move this function to separate file and then somehow reuse in <a href="https://github.com/antono/aoc2018" target="_blank">all my solutions</a>. Quick googling leads to &quot;<a href="https://doc.rust-lang.org/1.30.0/book/second-edition/ch07-00-modules.html" target="_blank">Using Modules to Reuse and Organize Code</a>&quot; of The Rust Book.</p>
  <blockquote>what happens if you have too many functions? Rust has a module system that enables the reuse of code in an organized fashion.</blockquote>
  <p>Nice! Two important things from first page:</p>
  <ul>
    <li>By default, functions, types, constants, and modules are private. The <code>pub</code> keyword makes an item public and therefore visible outside its namespace.</li>
    <li>The <code>use</code> keyword brings modules, or the definitions inside modules, into scope so it’s easier to refer to them.</li>
  </ul>
  <p>Rust has pretty flexible module layout and there are some rules for module organization. For my simple case i just made following steps:</p>
  <ol>
    <li>Moved function to external file &#x60;src/utils.rs&#x60;</li>
    <li>prefixed function with pub keyword: pub fn read_puzzle_input...</li>
    <li>and added small snippet to Cargo.toml:</li>
  </ol>
  <pre>[lib]
name = &quot;utils&quot;
path = &quot;src/utils.rs&quot;
</pre>
  <p>Now in order to use functions from this library i need added crate declaration to top of my file and prefixed function call with utils namespace:</p>
  <pre>extern crate utils;

fn part_one() {
    let input = utils::read_puzzle_input(1);
    let mut result: i32 = 0;

    for line in input.lines() {
        let num = line.parse::&lt;i32&gt;().unwrap();
        result += num;
    }

    println!(&quot;Sum of freq adjustments: {}&quot;, result);
}

</pre>
  <p><a href="https://github.com/antono/aoc2018" target="_blank">The Code</a>.</p>
  <hr />
  <p><a href="https://blog.antono.info/Syuxv7s1E" target="_blank">Disclaimer</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/BJbmAnTJ4</guid><link>https://blog.antono.info/BJbmAnTJ4?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/BJbmAnTJ4?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>Blender: vse proxy generator</title><pubDate>Tue, 11 Dec 2018 22:45:44 GMT</pubDate><media:content medium="image" url="https://teletype.in/files/7d/7d2feee9-2360-4019-9c51-e151450b83c3.png"></media:content><category>python</category><description><![CDATA[<img src="https://teletype.in/files/3c/3c896405-41a7-49a8-b7b8-c2b6e77e5c7c.png"></img>If You use blender as video editor you probably doing a lot of manual work to setup and rebuild strip proxies (Proxy/timecode) in Sequencer. Been there, tired to do that!]]></description><content:encoded><![CDATA[
  <figure id="qn2d" class="m_column">
    <img src="https://teletype.in/files/3c/3c896405-41a7-49a8-b7b8-c2b6e77e5c7c.png" width="3360" />
  </figure>
  <p id="91mk">If You use <a href="https://www.blender.org/" target="_blank">blender</a> as video editor you probably doing a lot of manual work to setup and rebuild strip proxies (Proxy/timecode) in Sequencer. Been there, tired to do that!</p>
  <p id="y6Q7">In order to build proxy <strong>for all you strips</strong> just paste this code in bledner text editor and press &#x27;run script&#x27;:</p>
  <pre id="B1Iz" data-lang="python">import bpy

def proxy_gen_all(proxy_sizes=[25], force=False):
    &quot;&quot;&quot; Rebuilds proxies for all strips&quot;&quot;&quot;
    
    for scene in bpy.data.scenes:
        seqs = scene.sequence_editor.sequences_all

        for seq in seqs:
            # operate only on MOVIE strips
            if seq.type == &#x27;MOVIE&#x27;:
                seq.use_proxy = True
            
                # if we pregenerate proxies in parallel externally
                if force:
                    seq.proxy.use_overwrite = True
                
                if 25 in proxy_sizes:
                    seq.proxy.build_25 = True

                if 50 in proxy_sizes:
                    seq.proxy.build_50 = True
                    
                if 75 in proxy_sizes:
                    seq.proxy.build_75 = True

                if 100 in proxy_sizes:
                    seq.proxy.build_100 = True
                
                seq.proxy.use_overwrite = False
    
    bpy.ops.sequencer.rebuild_proxy()
    
proxy_gen_all([25, 50])
</pre>
  <figure id="By5v" class="m_column">
    <img src="https://teletype.in/files/b9/b9900a0d-a2cf-40bb-97b9-95937ce31820.png" width="1770" />
  </figure>
  <p id="70BC">The script will build 25% and 50% proxies for all strips. It will not rebuild proxies if you run it again. Proxy building is time consuming task and unfortunately it blocks blender UI. So if you want to force rebuild the proxies you can just replace last line with this:</p>
  <pre id="xoPK" data-lang="python">proxy_gen_all([25, 50], True)
</pre>
  <p id="ECAg">Second argument forces rebuild of all proxies.</p>
  <p id="z2YR">Have fun!</p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/r1YKGw3y4</guid><link>https://blog.antono.info/r1YKGw3y4?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/r1YKGw3y4?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>Result&lt;T,E&gt; in Rust</title><pubDate>Mon, 10 Dec 2018 22:03:36 GMT</pubDate><media:content medium="image" url="https://teletype.in/files/c3/c374e826-42d3-4781-8f26-5bb624061fcd.png"></media:content><category>rust</category><description><![CDATA[<img src="https://teletype.in/files/47/475510fa-92f5-486d-a41a-d3c9da93d97b.jpeg"></img>In my first puzzle in advent of code challenge I used some copy/pasted rust code which was not completely clear to me... It's time to understand the code and document it here.]]></description><content:encoded><![CDATA[
  <figure id="so4L" class="m_column">
    <img src="https://teletype.in/files/47/475510fa-92f5-486d-a41a-d3c9da93d97b.jpeg" width="1200" />
  </figure>
  <p id="jt3L">In my <a href="https://blog.antono.info/rysyH35JN" target="_blank">first puzzle in advent of code challenge</a> I used some copy/pasted rust code which was not completely clear to me... It&#x27;s time to understand the code and document it here.</p>
  <p id="jeOd">I talking about .expect and .unwrap() methods.</p>
  <p id="2ARL">File::open() will throw compilation error without .expect() in copy/pasted code</p>
  <pre id="EohA" data-lang="rust">File::open(filename).expect(&quot;error message&quot;);
</pre>
  <p id="MzAz">Parse function will throw compilation error without .unwrap() call in copy/pasted code</p>
  <pre id="8RVl" data-lang="rust">line.parse::&lt;i32&gt;().unwrap();
</pre>
  <p id="hgXi">From signature of <a href="https://doc.rust-lang.org/std/fs/struct.File.html#method.open" target="_blank">std::fs::File::open()</a> I see that it returns <a href="https://doc.rust-lang.org/std/io/type.Result.html" target="_blank">Result</a>&lt;<a href="https://doc.rust-lang.org/std/fs/struct.File.html" target="_blank">File</a>&gt; instead of File. Googling leads to <a href="https://doc.rust-lang.org/1.30.0/book/2018-edition/ch09-00-error-handling.html" target="_blank">Error Handling</a> topic in Rust Book which explains:</p>
  <blockquote id="B2ZY">Rust doesn’t have exceptions. Instead, it has the type <code>Result&lt;T, E&gt;</code> for recoverable errors and the <code>panic!</code> macro that stops execution when the program encounters an unrecoverable error.</blockquote>
  <blockquote id="6MHj"><code><a href="https://doc.rust-lang.org/std/result/enum.Result.html" target="_blank">Result&lt;T, E&gt;</a></code> is the type used for returning and propagating errors. It is an enum with the variants, <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok" target="_blank">Ok(T)</a></code>, representing success and containing a value, and <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err" target="_blank">Err(E)</a></code>, representing error and containing an error value.</blockquote>
  <p id="lzKi">Generic Result enum looks like this:</p>
  <pre id="dWDd" data-lang="rust">enum Result&lt;T, E&gt; {
   Ok(T),
   Err(E),
}
</pre>
  <p id="pX7l">After getting result developer should handle Ok(result) or Err(why) situations. Typical error handling in rust looks like this:</p>
  <pre id="Zjzm" data-lang="rust">use std::fs::File;
use std::error::Error;

fn main() {
    let path = &quot;.gitignore&quot;;
    match File::open(&amp;path) {
        Err(why) =&gt; panic!(&quot;couldn&#x27;t open {}: {}&quot;, path, why.description()),
        Ok(file) =&gt; println!(&quot;{:?}&quot;, file),
    };
}
</pre>
  <p id="t3cP">This is how rust book explains code above:</p>
  <blockquote id="07XL">In the case where <code>File::open</code> succeeds, the value in [match construction] will be an instance of <code>Ok</code> that contains a file handle. In the case where it fails, the value in [match construction] will be an instance of <code>Err</code> that contains more information about the kind of error that happened.</blockquote>
  <p id="bvu2">Only one branch will be executed depending on operation result.</p>
  <p id="DGVj">So what is purpose of <strong>.expect()</strong> in this code?</p>
  <pre id="n5nr">File::open(filename).expect(&quot;error message&quot;);
</pre>
  <p id="7TOe">Looking at documentation for <a href="https://doc.rust-lang.org/std/result/enum.Result.html" target="_blank">std::result::Result</a> and seeing explanation:</p>
  <blockquote id="5l7P">Unwraps a result, yielding the content of an <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok" target="_blank">Ok</a></code>. Panics if the value is an <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err" target="_blank">Err</a></code>, with a panic message<strong> including the passed message</strong>, and the content of the <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err" target="_blank">Err</a></code>.</blockquote>
  <p id="4Lco">So basically .expect() is a shorthand for match construction above. It either takes result or panics with message. I checked the code of std::result::Result and seeing this:</p>
  <pre id="14bQ" data-lang="rust">  #[inline]
  #[stable(feature = &quot;result_expect&quot;, since = &quot;1.4.0&quot;)]
  pub fn expect(self, msg: &amp;str) -&gt; T {
      match self {
          Ok(t) =&gt; t,
          Err(e) =&gt; unwrap_failed(msg, e),
      }
  }
</pre>
  <p id="9gu7">Very similar to example with Result matching i gave above.</p>
  <p id="D3kf">One more note from Rust Book:</p>
  <blockquote id="wMiP">Rust groups errors into two major categories: <em>recoverable </em>and <em>unrecoverable </em>errors. For a recoverable error, such as a file not found error, it’s reasonable to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, like trying to access a location beyond the end of an array.</blockquote>
  <p id="8Jv5">.expect() makes unrecoverable error from recoverable. In simple cases it is okay to handle situation like this but production programs should not panic if file is missing or not readable.</p>
  <p id="lvYS"><a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap" target="_blank">.unwrap()</a> is very similar to .expect:</p>
  <blockquote id="hjsK">Unwraps a result, yielding the content of an <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok" target="_blank">Ok</a></code>. Panics if the value is an <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err" target="_blank">Err</a></code>, with a panic message provided by the <code><a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err" target="_blank">Err</a></code>&#x27;s value.</blockquote>
  <p id="Gy5n">So difference from expect is only that expect takes additional error message.</p>
  <h2 id="CnXq">Additional reading:</h2>
  <ul id="d1uv">
    <li id="BHSb"><a href="https://doc.rust-lang.org/1.30.0/book/2018-edition/ch09-00-error-handling.html" target="_blank">Rust Book: Error Handling</a></li>
    <li id="6nEL"><a href="https://doc.rust-lang.org/rust-by-example/error/result.html" target="_blank">Rust By Example: Result</a></li>
    <li id="hTFW"><a href="https://doc.rust-lang.org/std/result/index.html" target="_blank">std::result</a> module documentation</li>
    <li id="mJru"><a href="https://doc.rust-lang.org/std/result/enum.Result.html" target="_blank">std::result::Result api</a></li>
  </ul>
  <hr />
  <p id="02tK"><a href="https://blog.antono.info/Syuxv7s1E" target="_blank">Disclaimer</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/Syuxv7s1E</guid><link>https://blog.antono.info/Syuxv7s1E?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/Syuxv7s1E?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>AOC Posts disclaimer</title><pubDate>Sun, 09 Dec 2018 23:38:26 GMT</pubDate><media:content medium="image" url="https://teletype.in/files/81/81fc3cb5-b7cd-4d71-aca0-886a0249ac98.png"></media:content><category>aoc</category><category>rust</category><description><![CDATA[<img src="https://teletype.in/files/06/068345b3-0ced-4321-a838-2cf75bf811d8.jpeg"></img>Photo by Mike Baird (CC BY 2.0) Cropped.]]></description><content:encoded><![CDATA[
  <figure class="m_column">
    <img src="https://teletype.in/files/06/068345b3-0ced-4321-a838-2cf75bf811d8.jpeg" width="3912" />
  </figure>
  <p><em>Photo by <a href="https://www.flickr.com/photos/mikebaird/" target="_blank">Mike Baird</a> (<a href="https://creativecommons.org/licenses/by/2.0/" target="_blank">CC BY 2.0</a>) Cropped.</em></p>
  <hr />
  <p>This disclaimer related to <a href="https://blog.antono.info/?topic_id=2787" target="_blank">Advent of code posts</a> i publishing in this blog.</p>
  <p>In those posts I going to document my travel into Rust programming language. The goal of these blog posts is to make my understanding of rust better as a result of documenting my findings and insights. Making public posts makes me more responsible: forces to think twice and read more docs before publishing in order to look less stupid than I am.</p>
  <p>I have basic background in rust and made some small rusty experiments for myself. In terms of theory I had been reading interesting topics of <a href="https://doc.rust-lang.org/book/" target="_blank">The Rust Book</a> a year ago.</p>
  <p>The posts should not be considered as educational material or smart findings. Just personal notes of new rust developer.</p>
  <hr />

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/rkbphGsyE</guid><link>https://blog.antono.info/rkbphGsyE?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/rkbphGsyE?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>Advent of code: Puzzle 1.2</title><pubDate>Sun, 09 Dec 2018 22:52:40 GMT</pubDate><media:content medium="image" url="https://img1.teletype.in/files/4e/29/4e296b92-895c-467d-880b-ff233da8357c.png"></media:content><category>rust</category><description><![CDATA[<img src="https://teletype.in/files/00/00327ce5-8ff5-4ef9-9f8e-39a7c2e193fd.jpeg"></img>Photo by Kevin Utting (CC BY 2.0) Cropped.]]></description><content:encoded><![CDATA[
  <figure id="52R5" class="m_column">
    <img src="https://teletype.in/files/00/00327ce5-8ff5-4ef9-9f8e-39a7c2e193fd.jpeg" width="2676" />
  </figure>
  <p id="ebL1"><em>Photo by <a href="https://www.flickr.com/photos/tallkev/" target="_blank">Kevin Utting</a> (<a href="https://creativecommons.org/licenses/by/2.0/" target="_blank">CC BY 2.0</a>) Cropped.</em></p>
  <hr />
  <p id="z3Mh">Solving part 2 of day 1 in <a href="https://adventofcode.com/" target="_blank">advent of code challenge</a>. Puzzle is based on <a href="https://blog.antono.info/rysyH35JN" target="_blank">day 1 part 1</a>.</p>
  <p id="DTUs">The task is:</p>
  <blockquote id="PaIl">You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.</blockquote>
  <p id="pCvK">So taking a look to solution <a href="https://blog.antono.info/rysyH35JN" target="_blank">from part one</a>:</p>
  <pre id="kN17" data-lang="rust">fn main() {
    let input = read_puzzle_input(1);
    let mut result: i32 = 0;

    for line in input.lines() {
        let num = line.parse::&lt;i32&gt;().unwrap();
        result += num;
    }

    println!(&quot;{}&quot;, result);
}
</pre>
  <p id="ywB0">The task looks like easy one: i just need to collect results and find first duplicate! First idea is to use array and then check wherever it includes current result on each iteration. But arrays search complexity is O(n) and it will slow down the code when i&#x27;ll need too many iterations. Hash might be better here with O(1) access complexity. However hash should keep some kind of value which is not required for my task. So i need some kind of collection with inexpensive inserts and inclusion checks. Let&#x27;s see what rust provide in standard library: <a href="https://doc.rust-lang.org/beta/std/collections/ " target="_blank">collections</a>.</p>
  <p id="P8LG">Rust has 4 major categories of collections:</p>
  <ul id="Ggag">
    <li id="ogke">Sequences: <code><a href="https://doc.rust-lang.org/beta/std/vec/struct.Vec.html" target="_blank">Vec</a></code>, <code><a href="https://doc.rust-lang.org/beta/std/collections/struct.VecDeque.html" target="_blank">VecDeque</a></code>, <code><a href="https://doc.rust-lang.org/beta/std/collections/struct.LinkedList.html" target="_blank">LinkedList</a></code></li>
    <li id="7RvY">Maps: <code><a href="https://doc.rust-lang.org/beta/std/collections/struct.HashMap.html" target="_blank">HashMap</a></code>, <code><a href="https://doc.rust-lang.org/beta/std/collections/struct.BTreeMap.html" target="_blank">BTreeMap</a></code></li>
    <li id="Zebu">Sets: <code><a href="https://doc.rust-lang.org/beta/std/collections/struct.HashSet.html" target="_blank">HashSet</a></code>, <code><a href="https://doc.rust-lang.org/beta/std/collections/struct.BTreeSet.html" target="_blank">BTreeSet</a></code></li>
    <li id="SdpA">Misc: <code><a href="https://doc.rust-lang.org/beta/std/collections/struct.BinaryHeap.html" target="_blank">BinaryHeap</a></code></li>
  </ul>
  <p id="vfta">The documentation is pretty nice and explains pros and cons of each type...</p>
  <blockquote id="dFrT"><a href="https://doc.rust-lang.org/beta/std/collections/#use-the-set-variant-of-any-of-these-maps-when" target="_blank">Use the <code>Set</code> variant of any of these <code>Map</code>s when:</a></blockquote>
  <blockquote id="IRtH">You just want to remember which keys you&#x27;ve seen.</blockquote>
  <blockquote id="QVN3">There is no meaningful value to associate with your keys.</blockquote>
  <blockquote id="Jmtd">You just want a set.</blockquote>
  <p id="Lmmt">Looks like exactly what i need. There is an <a href="https://doc.rust-lang.org/beta/std/collections/struct.BTreeSet.html" target="_blank">BTreeSet</a> and a <a href="https://doc.rust-lang.org/beta/std/collections/struct.HashSet.html" target="_blank">HashSet</a>. I believe second is cheaper for inserts so i&#x27;ll use it.</p>
  <pre id="6qEE" data-lang="rust">fn part_two() {
    let input = read_puzzle_input(1);
    let mut result: i32 = 0;
    let mut seen_freqs: HashSet&lt;i32&gt; = HashSet::new();

    seen_freqs.insert(result);

    for line in input.lines() {
        let num = line.parse::&lt;i32&gt;().unwrap();
        result += num;

        if !seen_freqs.insert(result) {
            println!(&quot;Repeating frequency: {}&quot;, result);
            break
        }
    }
}
</pre>
  <p id="I8f4">Basically doing the same work as before but this time inserting each result to <a href="https://doc.rust-lang.org/beta/std/collections/struct.HashSet.html" target="_blank">HashSet</a>. Insert method returns boolean false if value is already in set.</p>
  <p id="UKQR">Running this and getting no output.</p>
  <p id="zQK0">I cant believe! Getting debug output (one result per line) and comparing using shell tools:</p>
  <pre id="L3Xv" data-lang="shell">cargo run &gt; nums.txt
wc -l nums.txt
989 nums.txt
uniq nums.txt &gt; nums2.txt
wc -l nums2.txt
989 nums2.txt
</pre>
  <p id="HeGq">Looks like the same number of unique values: no duplicates. Carefully rereading the task and seeing something i had missed first time:</p>
  <blockquote id="yXet">Note that your device might need to repeat its list of frequency changes many times before a duplicate frequency is found, and that duplicates might be found while in the middle of processing the list.</blockquote>
  <p id="zNSt">Okay. It means I must iterate over lines again and wait for repeating number. But input.lines() returns Lines struct which is iterator so when it reach the end of sequence it will stop. First idea was to convert iterator to list and then use old good endless loop with index manipulation + break the loop once value found. However after digging in iterator docs i found a way to restart iterator: <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.cycle" target="_blank">std::iter::iterator#cycle</a>. input.lines() returns<a href="https://doc.rust-lang.org/std/str/struct.Lines.html" target="_blank"> Lines struct which implements Iterator Trait</a>. This fact probably means i can use cycle() to endlessly iterate over some values.</p>
  <p id="2zFy">Adding .cycle() call on Lines:</p>
  <pre id="ce4v" data-lang="rust">fn part_two() {
    let input = read_puzzle_input(1);
    let mut result: i32 = 0;
    let mut seen_freqs: HashSet&lt;i32&gt; = HashSet::new();

    seen_freqs.insert(result);

    for line in input.lines().cycle() {
        let num = line.parse::&lt;i32&gt;().unwrap();
        result += num;

        if !seen_freqs.insert(result) {
            println!(&quot;Repeating frequency: {}&quot;, result);
            break
        }
    }
}

</pre>
  <p id="zjxe">Running the code:</p>
  <pre id="lrP9">cargo run
   Compiling aoc2018 v0.1.0 (file:///Users/antono/Code/rust/aoc2018)
    Finished dev [unoptimized + debuginfo] target(s) in 0.62 secs
     Running &#x60;target/debug/1&#x60;
Sum of freq adjustments: 493
Repeating frequency: 413
</pre>
  <p id="tI9H">Submitting result:</p>
  <blockquote id="ObGG">That&#x27;s the right answer! You are one gold star closer to fixing the time stream.</blockquote>
  <p id="SHip">Code pushed to GitHub.</p>
  <hr />
  <h2 id="GvhQ">Findings</h2>
  <ul id="9WTO">
    <li id="rtBe">Read requirements carefully :)</li>
    <li id="C0F9">Unix shell skills are still relevant</li>
    <li id="fKjN">Everything I need to know about <a href="https://doc.rust-lang.org/std/iter/index.html" target="_blank">iterators in rust on one page</a></li>
  </ul>
  <hr />
  <p id="aIon"><a href="https://blog.antono.info/Syuxv7s1E" target="_blank">Disclaimer</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.antono.info/rysyH35JN</guid><link>https://blog.antono.info/rysyH35JN?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono</link><comments>https://blog.antono.info/rysyH35JN?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=antono#comments</comments><dc:creator>antono</dc:creator><title>Advent of Code in Rust</title><pubDate>Sun, 09 Dec 2018 17:35:42 GMT</pubDate><media:content medium="image" url="https://teletype.in/files/c8/c8d55d71-3a2f-4937-aaf8-45c13f2c2041.jpeg"></media:content><category>rust</category><description><![CDATA[<img src="https://teletype.in/files/75/750cae79-3911-480a-aebb-32aaa4d35549.jpeg"></img>Photo by Paul VanDerWerf (CC BY 2.0) Cropped.]]></description><content:encoded><![CDATA[
  <figure id="M2KB" class="m_column">
    <img src="https://teletype.in/files/75/750cae79-3911-480a-aebb-32aaa4d35549.jpeg" width="1219" />
  </figure>
  <p id="lj75"><em>Photo by <a href="https://www.flickr.com/photos/pavdw/" target="_blank">Paul VanDerWerf</a> (<a href="https://creativecommons.org/licenses/by/2.0/" target="_blank">CC BY 2.0</a>) Cropped.</em></p>
  <hr />
  <h2 id="YJfj">Motivation</h2>
  <p id="Kd2d">One <a href="https://github.com/onesk" target="_blank">smart person</a> motivated me to join <a href="https://adventofcode.com/" target="_blank">Advent of Code</a> challenge.</p>
  <p id="qW5c">Here I going to document my travel into Rust programming language. The goal of this blog posts is to make my understanding of rust better as a result of documenting my insights. Making public posts makes me more responsible and forces to think twice and read more docs before publishing in order to look less stupid than I am.</p>
  <p id="EThx">I have basic background in rust making small experiments for myself. In terms of theory I had been reading interesting topics of <a href="https://doc.rust-lang.org/book/" target="_blank">The Rust Book</a> a year ago.</p>
  <p id="eST4">This post will outline all setup steps i made in order to start. Next posts will probably have less instructions and more personal observations about rust.</p>
  <hr />
  <h2 id="Bhy0">Project Layout</h2>
  <p id="XxeE">First I installed rust using <a href="https://rustup.rs/" target="_blank">rustup</a> tool. Easy one liner to get all i need.</p>
  <p id="3JMH">Next i generated new project using awesome <a href="https://doc.rust-lang.org/cargo/" target="_blank">cargo</a> tool:</p>
  <pre id="S1uS">cargo new aoc2018
cd aoc2018
tree .
.
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files
</pre>
  <p id="bCBU">Cargo is a built in package manager and build tool for Rust. It has more functionality than other package managers i used (gem, bundler, npm, pip). Here is incomplete list of tasks cargo can do for you:</p>
  <ul id="8nZb">
    <li id="cqX0">Generate new project</li>
    <li id="o59H">Build your project and run tests</li>
    <li id="CYv8">Manage project dependencies specified in Cargo.toml</li>
    <li id="iMHZ">Publish your package on <a href="https://crates.io/" target="_blank">crates.io</a></li>
    <li id="LPiS">Format your code</li>
  </ul>
  <p id="GzOF">Other languages provide different tools for above mentioned tasks but approach taken by rust team makes it really easy to start without all those problems with moving parts.</p>
  <p id="g6TJ">Default generated code contains &quot;Hello World&quot; program and its as easy to run as:</p>
  <pre id="G7C5">cargo run  
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running &#x60;target/debug/aoc2018&#x60;
Hello, world!
</pre>
  <p id="EmBq">Next I going to change my project layout to have one binary output for each puzzle.</p>
  <p id="hK3j"><a href="https://doc.rust-lang.org/cargo/guide/project-layout.html" target="_blank">Section about project layout</a> in Cargo Book says that binaries should go to src/bin/*.rs.</p>
  <p id="lIIu">Reorganizing the project:</p>
  <pre id="1Dy3">cd src 
mkdir bin 
mv main.rs bin/1.rs
cd ../../
cargo run
   Compiling aoc2018 v0.1.0 (file:///private/tmp/aoc2018)
    Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs
     Running &#x60;/private/tmp/aoc2018/target/debug/1&#x60;
Hello, world!
</pre>
  <h2 id="NUs2">Puzzle #1</h2>
  <p id="dJIs">It&#x27;s time to get into code.</p>
  <p id="uQV0">Making long story short: you getting list of newline separated numbers prefixed with plus or minus signs. Solution is sum of them. Input looks like:</p>
  <pre id="CKAx">+13
+9
+8
+1
-15
+10
...
</pre>
  <p id="Zx6Z">I pasted this input to inputs/1.txt in root of the project. I going to put all inputs to the folder and want to create universal function to read these files. I&#x27;m too lazy to read the api docs but google gives <a href="https://doc.rust-lang.org/1.30.0/book/second-edition/ch12-02-reading-a-file.html" target="_blank">good example from rust book</a>.</p>
  <p id="U65u">Tailoring example to my needs:</p>
  <pre id="RjkN" data-lang="rust">use std::fs::File;
use std::io::prelude::*;

fn read_puzzle_input(number: u8) -&gt; String {
    let mut input =
        File::open(format!(&quot;./inputs/{}.txt&quot;, number))
            .expect(&quot;Puzzle input not found...&quot;);
    let mut text = String::new();

    input
        .read_to_string(&amp;mut text)
        .expect(&quot;cannot read input file&quot;);

    return text;
}
</pre>
  <p id="OLMR">Ok. Now i going to iterate over lines, parse them and sum. Luckily rust has built in <a href="https://doc.rust-lang.org/std/string/struct.String.html#method.lines" target="_blank"><em>lines()</em> method on String</a>. This method returns <a href="https://doc.rust-lang.org/std/str/struct.Lines.html" target="_blank">Lines iterator</a> which can be used in loops:</p>
  <pre id="pg7H" data-lang="rust">fn main() {
    let input = read_puzzle_input(1);

    for line in input.lines() {
        println!(&quot;{}&quot;, result);
    }
}
</pre>
  <p id="AtNo">It was easy. Time to parse numbers. My first idea was to get sign from each line at position 0 and parse the rest of the string as integer. Then using <a href="https://doc.rust-lang.org/rust-by-example/flow_control/match.html" target="_blank">match keyword</a> either add or subtract from some variable. When i tried to parse integers i found that rust has <a href="https://doc.rust-lang.org/std/primitive.str.html#method.parse" target="_blank">str::parse</a> method that converts strings to other types. Even easier than i thought!</p>
  <pre id="MI8O" data-lang="rust">fn main() {
    let input = read_puzzle_input(1);
    let mut result: i32 = 0;

    for line in input.lines() {
        let num = line.parse::&lt;i32&gt;().unwrap();
        result += num;
    }

    println!(&quot;{}&quot;, result);
}
</pre>
  <p id="AH1H">Running the code:</p>
  <pre id="cYhx"> cargo run
   Compiling aoc2018 v0.1.0 (file:///Users/antono/Code/rust/aoc2018)
    Finished dev [unoptimized + debuginfo] target(s) in 0.92 secs
     Running &#x60;target/debug/1&#x60;
493
</pre>
  <p id="tz8U">It works. Result accepted and i got first star in the challenge.</p>
  <p id="s0yl">Awesome!</p>
  <p id="3oUj">My <a href="https://github.com/antono/aoc2018" target="_blank">code published on GitHub</a> if someone cares.</p>
  <hr />
  <h2 id="zT29">Things to investigate</h2>
  <p id="tjGR">Some things in code still need to be explained to myself.</p>
  <p id="pcNd">File::open() will throw compilation error without .expect()</p>
  <pre id="BUoS" data-lang="rust">File::open(filename).expect(&quot;error message&quot;);
</pre>
  <p id="1mSQ">Parse function will throw compilation error without .unwrap() call.</p>
  <pre id="xDXj" data-lang="rust">line.parse::&lt;i32&gt;().unwrap();
</pre>
  <p id="tCtV">Using File looks obvious but why should i use prelude?</p>
  <pre id="zoAh" data-lang="rust">use std::fs::File;
use std::io::prelude::*;
</pre>
  <p id="uIGh">I will document the answers in my next posts.</p>
  <hr />
  <p id="q3FT"><a href="https://blog.antono.info/Syuxv7s1E" target="_blank">Disclaimer</a></p>

]]></content:encoded></item></channel></rss>