blog/assets/js/4200b1a9.e049437f.js
github-actions[bot] 8b13093ebd deploy: 4d3c19fce0
2024-07-20 21:53:38 +00:00

1 line
No EOL
194 KiB
JavaScript

"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[866],{24612:e=>{e.exports=JSON.parse('{"blogPosts":[{"id":"/2024/07/20/raspberry-alma","metadata":{"permalink":"/blog/2024/07/20/raspberry-alma","editUrl":"https://github.com/mfocko/blog/tree/main/blog/2024-07-20-raspberry-alma.md","source":"@site/blog/2024-07-20-raspberry-alma.md","title":"Raspberry Alma","description":"Finally migrating to a stable distro on Raspberry\u2026\\n","date":"2024-07-20T00:00:00.000Z","formattedDate":"July 20, 2024","tags":[{"label":"raspberry-pi","permalink":"/blog/tags/raspberry-pi"},{"label":"opensuse","permalink":"/blog/tags/opensuse"},{"label":"almalinux","permalink":"/blog/tags/almalinux"},{"label":"ansible","permalink":"/blog/tags/ansible"},{"label":"self-hosting","permalink":"/blog/tags/self-hosting"}],"readingTime":5.945,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. useless admin or \u201cSir Tweak-a-Lot\u201d","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"Raspberry Alma","description":"Finally migrating to a stable distro on Raspberry\u2026\\n","date":"2024-07-20T00:00:00.000Z","authors":[{"key":"mf","title":"a.k.a. useless admin or \u201cSir Tweak-a-Lot\u201d"}],"tags":["raspberry-pi","opensuse","almalinux","ansible","self-hosting"]},"unlisted":false,"nextItem":{"title":"DevConf.cz 2024","permalink":"/blog/2024/06/19/devconf-2024"}},"content":"Every now and then I get angry at something not working on the Raspberry and so\\nI decide to swap the OSs. Now it\'s time for something new and not expected.\\n\\n\x3c!--truncate--\x3e\\n\\n## Purpose and past\\n\\nAfter I\'ve subscribed a VPS at vpsfree.cz for myself, I got an opportunity to\\ndrop using an old laptop for running a local \u201cserver\u201d. At that point all I\'ve\\nhad was self-hosted Gitea, some aliases on nginx and that was all. Out with the\\nold laptop and let\'s begin experimenting with the Raspberry, right?\\n\\nThe first OS that got on the Raspberry was _archLinux_ (BTW\u2026). I\'ve been using\\nit for a long time and had the best experience with. I haven\'t hit any issues,\\nbut at the same time, you need to keep in mind we\'re running it off the SD card\\nand they are known to get worn out quickly, especially if you write **a lot**\\nwhich\u2026 guess what, is quite common with rolling and bleeding-edge distribution\\n:smile: And the worst part is keeping up with the updates.\\n\\nAnd that\'s how I migrated to openSUSE Leap :) I\'ve been using openSUSE for at\\nleast 4 years during the high school and a bit more before and after\u2026 openSUSE\\nis very user-friendly (YaST is amazing) distribution and honestly just works.\\nHowever the cost lies in Cockpit not being available[^1] and some weird design\\ndecision, e.g., networking stack is very fragile[^2].\\n\\nAnd I\'ve got finished in the recent weeks with some issues during updates, but\\nthose can be, of course, blamed on me, cause I don\'t watch over it as I should\\n:)\\n\\nI should probably sum up the latest state of what was running before I decided\\nto go for a merciless wipe. So here it is:\\n\\n- local Gitea instance, just in case and out of habit\\n- Wireguard connection for easy administration\\n- Certbot & nginx; nginx is probably the biggest piece of work as it also\\n provides reverse proxy for mikrotik router and Ubiquiti AP provided by ISP\\n- CUPS server that has joined the journey once the HP printer was too big of\\n a pain in the :peach: to handle via USB\\n- DDNS service, cause there\'s public, but dynamic IP from ISP\\n\\n## Choosing the next distro\\n\\nI had the switch in mind for some time, but I couldn\'t decide on the\\ndistribution\u2026 In the ideal world, I\'d just slap CentOS Stream on it, **but**\\nthere\'s no Raspberry \u201csupport\u201d for CentOS[^3]. So the other choices were plain\\nDebian and something else from the RHEL-family which could be either Fedora[^4],\\nAlmaLinux or Rocky Linux.\\n\\nI should admit that I\'m not a big Debian fan :smile: Even though _12 bookworm_\\nis relatively on the same terms as anything that tries to match RHEL9, it still\\nfeels weird. That might be caused by the fact that I\'ve switched RPM-based\\ndistributions a long time ago (including screwing around with archLinux and\\n_Jean Tux_[^5]) and never looked back (except for the desktop with NVIDIA GPU\\nthat\'s pain in the :peach: and only Ubuntu runs reasonably\u2026 well).\\n\\nWearing the _red fedora_ also ruled out the Rocky Linux :slightly*smiling_face:\\nas I don\'t endorse nor support their \\\\_way of operation*\\n\\nSo AlmaLinux it is!\\n\\n## Installing AlmaLinux 9\\n\\nI\'m going with AlmaLinux 9.4 on Raspberry Pi 3B. Opened the AlmaLinux\'s wiki and\\nfirst thing I got slapped by is\\n\\n> original Raspberry Pi 3 (without \\"+\\" models) are not supported\\n\\nGREAT! I took the risk, installed it. And it didn\'t boot :grin: It turns out\\nthat the WiFi kernel module caused a kernel panic on the boot. From some people\\non Reddit I found that it caused some issues, **but** worked, so I\'ve just\\ndecided to pop the SD card back in a PC and deny the module from loading. Voil\xe0!\\nIt boots!\\n\\n## Setting up the \u201clocal server\u201d\\n\\n:::caution Public disclaimer\\n\\nI suck as admin\u2026\\n\\n:::\\n\\nBoth the Raspberry and my VPS are maintained in the _caveman-style_ :smile: And\\nthat\'s why I\'ve decided to start with the less painful one (the Raspberry) to\\nwrite the Ansible playbooks for :)\\n\\nI have already managed to migrate my dotfiles and \u201cbootstrap\u201d to be run via\\nAnsible, so I\'ve just proceeded to extend that and also reorganize it a bit,\\ncause the roles grew in size :eyes:\\n\\nAnd I have to admit that I\'ve been mostly successful. Let\'s delve into details!\\n\\n### SELinux\\n\\nYeah\u2026 that\'s something that hasn\'t been running on the openSUSE and I totally\\nforgot that hardening the SSHD config (including port change) requires notifying\\nSELinux about the port change :) Of course I managed to cut myself off :smile:\\n\\n### Certbot\\n\\nCertbot was the service I feared the most, as there is no reasonable way to\\nautomate this. You need to run it manually at least the first time. But in the\\nend, it was quite OK.\\n\\n### Cockpit\\n\\nOne downside of _caveman-style_ administration is the fact that you forget about\\nthe tweaking you do. Reverse proxy breaks Cockpit by default. I was reading\\nthrough the documentation, but haven\'t managed to find the part that mentioned\\nthe specific settings I had to change. When I was about to open the PR with\\nproposed changes, I noticed that it was in a different chapter :man_facepalming:\\n\\n### CUPS\\n\\nCups went rather smoothly\u2026 except for the fact that it doesn\'t work on the one\\nand only Ubuntu desktop and there are no logs with reason why it fails to add\\nthe printer :slightly_smiling_face:\\n\\nAdditionally installing the HP printer via `hp-setup` is very interesting\\nexperience\u2026 I would\'ve never expected the CLI to have a progress bar that opens\\nup at 0% and then just switches into _terms & conditions_\u2026 Yes, that progress\\nbar stayed at 0% even though it was downloading a PPD file **and progressing**.\\n\\n### DDNS\\n\\nI had smallish issue with deciding how to run the DDNS service. I went with\\ndropping my own buggy script and had to choose a DDNS client. Found _inadyn_\\n(that isn\'t built at all for Fedora and family) and _ddclient_. The _ddclient_\\nhad some not very nice feedback, and the version that introduced the Cloudflare\\nsupport I need, was not included, so I dropped that. _inadyn_ is not packaged,\\nso I\'ve set it up as systemd timer spawning a container :)\\n\\n## Summary\\n\\nOverall I\'ve had a very pleasant experience setting up the AlmaLinux on the\\nRaspberry. Even though I took a gamble with the officially unsupported model of\\nRPi, it works. And it also seems to be filling the purpose it has!\\n\\n[^1]:\\n AFAIK there was some issue with dependencies, so it is available on\\n Tumbleweed and also in the latest Leap 15.6\\n\\n[^2]:\\n By default uses _wicked_ and even when running it on desktop via\\n _NetworkManager_ I\'ve hit some inconsistencies with DNS, but\u2026 DNS **is** the\\n Devil, right? :grin:\\n\\n[^3]: And neither RHEL to be fair ;)\\n[^4]:\\n 6-month release cycle goes against the idea to have the least amount of\\n updates as possible\u2026 and on top of that I think that we can safely agree on\\n the fact that Fedora feels like _archLinux with extra steps_\\n\\n[^5]: Gentoo\u2026"},{"id":"/2024/06/19/devconf-2024","metadata":{"permalink":"/blog/2024/06/19/devconf-2024","editUrl":"https://github.com/mfocko/blog/tree/main/blog/2024-06-19-devconf-2024.md","source":"@site/blog/2024-06-19-devconf-2024.md","title":"DevConf.cz 2024","description":"Sharing my experience on DevConf.cz 2024.\\n","date":"2024-06-19T00:00:00.000Z","formattedDate":"June 19, 2024","tags":[{"label":"\ud83c\udfed","permalink":"/blog/tags/\ud83c\udfed"},{"label":"red-hat","permalink":"/blog/tags/red-hat"},{"label":"fedora","permalink":"/blog/tags/fedora"},{"label":"devconf","permalink":"/blog/tags/devconf"},{"label":"conferences","permalink":"/blog/tags/conferences"}],"readingTime":5.36,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. exhausted DevConf attendee","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"DevConf.cz 2024","description":"Sharing my experience on DevConf.cz 2024.\\n","date":"2024-06-19T00:00:00.000Z","authors":[{"key":"mf","title":"a.k.a. exhausted DevConf attendee"}],"tags":["\ud83c\udfed","red-hat","fedora","devconf","conferences"]},"unlisted":false,"prevItem":{"title":"Raspberry Alma","permalink":"/blog/2024/07/20/raspberry-alma"},"nextItem":{"title":"LTS distributions","permalink":"/blog/2024/02/07/lts-distros"}},"content":"I\'d like to share my experience and views on some of the talks that I\'ve\\nattended on the DevConf.cz 2024.\\n\\n\x3c!--truncate--\x3e\\n\\n## Day 1\\n\\nLet\'s start with the first day which was Thursday this year as opposed to the\\nprevious years when the conference started on Friday and finished on Sunday.\\n\\nLet\'s start with the _[keynote]_. The keynote wasn\'t very interesting, at some of\\nthe slides actually felt like advertisement for other talks on the topic of the\\nAI\u2026\\n\\nNext talk about _[event-driven Ansible]_ was way more interesting. It allows you\\nto run Ansible playbooks after provisioning hosts, or on certain events, such as\\ndiscovered vulnerabilities. On one hand it feels like a very nice thing, but on\\nthe other one I can\'t help but to think how you need to write the playbooks, so\\nthat they are generic enough. One more example that\'s been given comes from the\\npossibility to react to tickets, e.g., outages and this feels like something\\nthat could be abused to cause DoS.\\n\\nAfterwards we\'ve seen two lightning talks, one about\\n_[choosing the right OpenShift size]_ which was a pretty quick, but listed all\\nof the possible ways you can deploy OpenShift in detail. This lightning talk\\nwas followed by the first AI (lightning) talk I\'ve attended about\\n_[rapid prototyping]_ of the open-source AI models.\\n\\nAs someone who\'s involved in the automation of the RPM packaging and testing, of\\ncourse, we had to attend _[Learning from Nix]_. Nix has a very intriguing\\nconcept which is pretty powerful, but painful at the same time. This can be\\nsummed up pretty nicely by [Tsoding] who got asked about some tips & tricks for\\nsomeone who wants to try out NixOS:\\n\\n> Just don\'t.\\n\\nAnd now we\'re moving into a section where everything revolves about the Packit\\nTeam :)\\n\\nFirst talk about _[changelogs]_ was an interactive session that was (probably)\\nmeant to share different approaches we take to handle this rather convoluted\\ntopic that involves changelogs on both upstream and also on downstream with no\\nrules[^1].\\n\\n![changelogs](https://i.imgur.com/YHstMAt.jpg)\\n\\nNext one was about _[static analysis]_ done by [OpenScanHub]. I like the idea of\\nrunning the static analysis that can uncover nasty bugs (as it has been even\\nshowed in the talk) at the same time as they are introduced. I gotta admit that\\nafter seeing the UI of the [deployed OpenScanHub] on the Fedora Infra, I couldn\'t\\nhelp but to think about the [United States Graphics Company] :smile: The UI is\\nto the point, no fancy annoying shit, you get what you need, it\'s hard to get\\nlost. **Just simplicity.** Best kind of UI/UX in my opinion.\\n\\nAfter the OpenScanHub talk we\'re getting to talks that were taken in a totally\\ndifferent direction from the usual talks you\'re used to :wink: First one was\\ngiven title of _[\u201cIndiana Jones and obsoleted projects\u201d]_ by [Mirek]. He talked\\nabout projects that got obsoleted, but started with projects that had no\\nrelation to IT field at all. I\'d mark this talk as a _stand up_ without any\\nhesitation.\\n\\nAnd finally we will wrap up the first day with the talk where speakers spoke the\\nleast\u2026 _[\u201cLet the users speak!\u201d]_ that involved users of both Packit and\\nTesting Farm who spoke about their use case and benefits they gained from using\\nboth services in a symbiosis.\\n\\n## Day 2\\n\\nOn the second day I\'ve attended less talks to not burn myself out :) I\'ve\\nstarted with an AI-related talk with title _[\u201cAI: Open source will save us!\u201d]_,\\neven though this talk has been improvised, as the speakers from the schedule\\ncouldn\'t have attended, it provided a nice overview what [InstructLab] can do\\nand how can you \u201cfeed\u201d the relevant info into the language models by yourself.\\n\\nAfter that I attended a _\u201ccoffee enthusiasts Meetup\u201d_ which was very nice and,\\nof course, an organized chaos :wink:\\n\\nBefore attending the social event I wrapped up the second day with a lightning\\ntalk about _[recent updates in Toolbx]_. I\'ve used both [toolbx] and\\n[distrobox], so it\'s nice to see the improvements in progress and also that both\\nprojects are well and lively.\\n\\n## Day 3\\n\\nOn the third day I\'ve attended only in the afternoon. \u201cStarted\u201d my day with\\na discussion _[\u201cLeadership: Where people skills meet programmers\u201d]_ which was\\nvery nice for gaining an insight into how developer, manager and QE lead roles\\noverlap.\\n\\nThat talk has been followed up by a talk about [role rotation] in our Packit\\nTeam. I would say it is a nice \u201cupgrade\u201d to the agile process which allows you\\nto not create a single point of failure in the mundane and repetitive processes\\nwithin your team.\\n\\nAnd this day has been finished off with a talk about [shifting left] in Podman.\\nIt\'s nice to see how other teams utilize our Packit Service and also the\\nservices we rely on, such as [Copr] or [Testing Farm]. With the help of Cockpit\\ntests they can catch breaking changes early on, or even bugs that have been\\nintroduced and break usage of the dependent projects.\\n\\n![shifting left](https://i.imgur.com/bp6FxT9.jpg)\\n\\n## Picks from the Packit Team\\n\\nOn the Tuesday, during our Packit stand up, I have managed to abuse my\\nKanban Lead role to collect some of the talks that each of us would recommend:\\n\\n- [Rapid Prototyping] with Open Source AI Models\\n- Do you like your [changelogs]?\\n- OpenScanHub - [Static Analysis] of a Linux Distribution\\n- Creating a [Language Server] for RPM Spec Files\\n- Containers and Kubernetes Made Easy: A 15-minute dive into [Podman Desktop]\\n- [\u201cLeadership: Where people skills meet programmers\u201d]\\n\\n## Wrap up\\n\\nI have to admit that these 3 days have been pretty exhaustive, including\\ninformation overload :smile: but at the same time it was really nice to meet\\nwith the colleagues and at least some of our users who are not based in Brno.\\n\\n[^1]: except for the Fedora\'s downstream ;)\\n\\n[keynote]: https://pretalx.com/devconf-cz-2024/talk/AD3HWR/\\n[event-driven ansible]: https://pretalx.com/devconf-cz-2024/talk/3UKGLB/\\n[choosing the right openshift size]: https://pretalx.com/devconf-cz-2024/talk/KSDRWL/\\n[rapid prototyping]: https://pretalx.com/devconf-cz-2024/talk/H9QFLM/\\n[learning from nix]: https://pretalx.com/devconf-cz-2024/talk/NNKT3F/\\n[tsoding]: https://twitch.tv/tsoding\\n[changelogs]: https://pretalx.com/devconf-cz-2024/talk/ECU7QS/\\n[static analysis]: https://pretalx.com/devconf-cz-2024/talk/7C38GJ/\\n[openscanhub]: https://openscanhub.dev/\\n[deployed openscanhub]: https://openscanhub.fedoraproject.org/\\n[united states graphics company]: https://x.com/usgraphics\\n[\u201cindiana jones and obsoleted projects\u201d]: https://pretalx.com/devconf-cz-2024/talk/X8SYDG/\\n[mirek]: https://rodina-sucha.cz/@mirek\\n[\u201clet the users speak!\u201d]: https://pretalx.com/devconf-cz-2024/talk/BDMWF3/\\n[\u201cai: open source will save us!\u201d]: https://pretalx.com/devconf-cz-2024/talk/QSF9QQ/\\n[instructlab]: https://github.com/instructlab/instructlab\\n[recent updates in toolbx]: https://pretalx.com/devconf-cz-2024/talk/SXWE7K/\\n[toolbx]: https://containertoolbx.org/\\n[distrobox]: https://distrobox.it/\\n[\u201cleadership: where people skills meet programmers\u201d]: https://pretalx.com/devconf-cz-2024/talk/8PARM8/\\n[role rotation]: https://pretalx.com/devconf-cz-2024/talk/8T88MT/\\n[shifting left]: https://pretalx.com/devconf-cz-2024/talk/WVNJZS/\\n[copr]: https://copr.fedorainfracloud.org/\\n[testing farm]: https://docs.testing-farm.io/Testing%20Farm/0.1/index.html\\n[language server]: https://pretalx.com/devconf-cz-2024/talk/RXKMKA/\\n[podman desktop]: https://pretalx.com/devconf-cz-2024/talk/HKWP7V/"},{"id":"/2024/02/07/lts-distros","metadata":{"permalink":"/blog/2024/02/07/lts-distros","editUrl":"https://github.com/mfocko/blog/tree/main/blog/2024-02-07-lts-distros.md","source":"@site/blog/2024-02-07-lts-distros.md","title":"LTS distributions","description":"Shower thoughts on the LTS Linux distributions.\\n","date":"2024-02-07T00:00:00.000Z","formattedDate":"February 7, 2024","tags":[{"label":"lts","permalink":"/blog/tags/lts"},{"label":"linux distributions","permalink":"/blog/tags/linux-distributions"},{"label":"support","permalink":"/blog/tags/support"},{"label":"paywall","permalink":"/blog/tags/paywall"}],"readingTime":14.515,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. small Fedora maintainer","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"LTS distributions","description":"Shower thoughts on the LTS Linux distributions.\\n","date":"2024-02-07T00:00:00.000Z","authors":[{"key":"mf","title":"a.k.a. small Fedora maintainer"}],"tags":["lts","linux distributions","support","paywall"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"DevConf.cz 2024","permalink":"/blog/2024/06/19/devconf-2024"},"nextItem":{"title":"Mixed feelings on Rust","permalink":"/blog/2024/01/28/rust-opinion"}},"content":"Linux distributions are a common choice for running the servers. There\'s a wide\\nvariety of distributions, but on the servers majority is made by only a few.\\n\\nSome corporations also profit from the support of the \u201cbig\u201d distributions. Let\'s\\ndive into the pros, cons and peculiarities of such _business_.\\n\\nThis post is inspired/triggered by the following Mastodon post:\\n[![Mastodon post about Ubuntu Pro](https://i.imgur.com/mh5RAlV.png)](https://hackers.town/@antijingoist/111864760073049505)\\n\\n\x3c!--truncate--\x3e\\n\\n:::warning Disclaimer\\n\\nYou may take my opinion with a grain of salt, since I\'m affiliated with Red Hat,\\nbut at the same time I\'ve also seen the other side of the fence, so I know how\\nit works from the perspective of the provider/maintainer.\\n\\n:::\\n\\n:::tip\\n\\nIf you are not very oriented in the matters of Linux distributions and\\nmaintaining of packages, I suggest looking at the [glossary](#glossary) at the\\nend to have a better grasp of the terms that are used throughout the post.\\n\\n:::\\n\\n## Point of linux distributions\\n\\nFirst thing I\'d like to point out is the point of the Linux distributions. What\\nbenefit do they provide? And why there are so many of them\u2026\\n\\nAs it has been brought up many times by the _rms_[^1], Linux by itself is not\\nenough, it\'s just the kernel that does the underlying work. We need more\\nsoftware to utilize the hardware. That\'s the gap that Linux distributions bridge\\nby providing the Linux and much more other software that we need.\\n\\nEach distribution is unique in its own way. Some prefer different ways of\\nhandling the software (like Gentoo that allows you to compile it yourself) and\\nothers stable releases of software (like Debian).\\n\\nIn the end it mostly boils down to the packaging. I, as a user, want to do\\nsomething like\\n\\n```\\n$ sudo dnf5 install firefox\\n```\\n\\nand not bother about anything else. I don\'t want to open browser to look the\\nthing up, download it and then click mindlessly 500\xd7 \u201cNext\u201d. I just want to run\\none command and when the maintainers decide it\'s time to move on, another one to\\nupgrade the software to the newer version.\\n\\nOf course, for some use cases you want to minimize the latter. And even make\\nsure that it\'s safe to do it when you need to. You don\'t want to break your\\nproduction deployment just because someone decided it\'s time to push something\\nout.\\n\\nThat\'s when the _maintainers_ come in. They take upon themselves the\\nresponsibility of maintaining the packages. If you\'ve ever used the Debian, you\\nknow very well how _old_ the software is, but that\'s what you might need for\\nyour servers.\\n\\n## Pain of packaging\\n\\nPackaging software _is not_ cost-free. You may as well have 80 % of packages\\nthat don\'t need much care and it\'s rather easy to push them forward, but those\\nremaining, which are complicated and raise issues regularly, will make it up and\\ntake a lot of time and also pain.\\n\\nLibraries are the most common example that might not need much work to be done.\\nOn the other hand, Linux kernel itself is a rather complicated machinery that\\nis patched **a lot** and its build process is not simple either.\\n\\nEven if you consider just those _easily-maintainble_ packages, the process can\\nbe tedious, boring and overall time consuming.\\n\\n:::tip Shameless RHEL-based ecosystem plug\\n\\n[Packit] can help tremendously with the _easily-maintainable_ packages, since it\\n**can** be automated.\\n\\n:::\\n\\n### Packaging whole ecosystems\\n\\nNow it\'s time to talk about whole ecosystems that have some kind of a packaging\\nby themselves. Yes, I mean Python (with its continuous stream of different\\npackage managers), Rust, Go, etc.\\n\\nWhole point of packaging is to have some form of _gating_. In other words, you\\nwant some kind of _quality control_ when pushing changes into the Linux distros.\\n\\nIf you want to package some tool (or even library) from the aforementioned\\necosystems, you need to package all of the dependencies to make sure something\\ndoesn\'t get updated in the meantime (and also that you can safely reproduce the\\nbuilds, if need be).\\n\\nI\'ve tried to package some utilities for EPEL both in Rust and Go. Dependencies\\nform a DAG[^2] and in case of Rust, it\'s _very_ similar to the way `npm` does\\nits packaging.\\n\\n:::danger Spoiler alert\\n\\nYou get a lot of dependencies. And since it\'s a tree of dependencies, there may\\nbe **a lot** of them.\\n\\n:::\\n\\nI have no clue how do the Rust maintainers operate, but I\'m tipping my fedora in\\ntheir direction, since it must be a _pain in the ass_.\\n\\n## Paid distributions\\n\\nYou can find few Linux distributions that are \u201cpaid\u201d. I\'m very well aware of the\\nfact I\'ve used quotes around the word, cause it\'s not that easy and not even\\nsame for all of the distributions that involve some kind of a payment.\\n\\nOne of the first non-free distributions I\'ve come into contact was _[Zorin OS]_\\nwhich basically tries to be the best _transition_ solution when moving away from\\nthe Windows or macOS. If you have a look at the _perks_ of its _Pro_ version\\nthat\'s paid, you may as well decide they are rather questionable\u2026\\n\\nIt\'s time to move into the _Ubuntu Pro_, _RHEL_ and _SLE_ territory. What\'s the\\npoint of those? They definitely offer different kind of, let\'s say,\\n_non-free experience_.\\n\\nWith those you are paying mainly for the support and bug/security patches.\\n\\n:::tip Fun fact\\n\\nThere\'s no mention of any kind of support on the Zorin page\u2026 Apart from the fact\\nthat _you are supporting_ the Zorin development.\\n\\n:::\\n\\n## Repository structure\\n\\nAs I have mentioned above, the three _services_[^3] I mentioned are providing\\nsupport with regards to bugs and security vulnerabilites. Therefore it makes\\nsense to have some kind of a process in place when you\'re pushing changes\\n(either updates, patches or _security_ patches) to the distribution. And yes,\\nthese processes are _in place_.\\n\\nIf you think about the amount of packages that is present in the community\\ndistributions like _archLinux_ (14,830 packages) or _Fedora_ (74,309 packages),\\nit is safe to come to a conclusion that _there\'s no way_ to support all of them.\\n\\n:::tip archLinux\\n\\nIt may seem that archLinux contains rather small set of packages, but one of the\\n_killer features_ of archLinux lies in the AUR (archLinux User Repository) where\\nyou can find additional **93,283** packages.\\n\\n:::\\n\\nThat\'s why the Linux distributions have some structure to their repositories\\nthat contain packages. The way you go around this is rather simple, you choose\\nsome set of _critical_ packages that you guarantee support for (like Linux\\nkernel, openSSL, etc.) and maintain those with all the QA processes in place.\\n\\n:::warning Unpopular opinion\\n\\nThis is also one of the reasons why I\'m quite against packaging anything and\\neverything into the Linux distribution. In my opinion it is impossible to\\n**properly** maintain **huge** set of packages and enforce some kind of\\n**quality control**.\\n\\n:::\\n\\n### Ubuntu\\n\\nUbuntu has pretty granular structure of their repositories, namely:\\n\\n- `main` containing the \u201ccore\u201d of the Ubuntu that is maintained by the Canonical,\\n- `universe` containing literally the \u201cuniverse\u201d, packages that everyone likes,\\n but they\'re not crucial, this repo is maintained mostly by the community,\\n- `multiverse` containing packages with some license or copyright issues, and\\n- `restricted` containing _proprietary_ packages like nvidia drivers and such.\\n\\nBy briefly checking my Ubuntu 23.10 installation, here are stats of packages in\\ntheir respective repositories:\\n\\n- `main` with 6,128 packages,\\n- `universe` with 63,380 packages,\\n- `multiverse` with 997 packages, and finally\\n- `restricted` with 784 packages.\\n\\nAs you can see, if we sum them up, they are relatively similar to the Fedora\\nnumbers.\\n\\n### CentOS\\n\\nCentOS on the other hand has a bit simpler structure with BaseOS for the base\\nand AppStream for additional packages:\\n\\n- `baseos` with 1,058 packages,\\n- `appstream` with 5,646 packages, and\\n- `extras-common` with 42 packages.\\n\\nOverall they make up the similar number as the Ubuntu\'s `main` repository. And\\nyou can also notice that there are no additional repositories.\\n\\n:::tip\\n\\nThere\'s also a CRB (CodeReady Builder) repository with dev packages like headers\\nand such.\\n\\nAnd you can also enable EPEL (Extra Packages for Enterprise Linux) which is\\ncommunity-supported and provides another 19,903 packages.\\n\\n:::\\n\\n## Ubuntu Pro\\n\\nNow it\'s time to get back to the Ubuntu Pro. There are multiple points that need\\nto be taken in account to be either positive or negative about it\u2026\\n\\nWe can start with the way Ubuntu is released and maintained. Ubuntu has regular\\n6-month release cycle and biannual LTS release. Releases are normally supported\\nfor 9 months with the exception of the LTS releases being supported for 5 years.\\n\\nIf you check out the _[Ubuntu Pro]_ website, you can find the following\\nstatement:\\n\\n> **Ubuntu Pro**\\n>\\n> The most comprehensive subscription for open-source software security\\n>\\n> 30-day trial for enterprises. Always free for personal use.\\n\\n:::tip Personal use\\n\\nUbuntu Pro for _personal use_ consists of 5 installations and in case of the\\ncommunity _ambassadors_ 50.\\n\\n:::\\n\\nOverall if you try to find what is included in the Ubuntu Pro:\\n\\n- high and critical patches,\\n- 10 years of maintenance, and\\n- (optional) 24/7 enterprise-grade support.\\n\\nIf we get back to the screenshot all the way at the beginning of the post:\\n[![Mastodon post about Ubuntu Pro](https://i.imgur.com/mh5RAlV.png)](https://hackers.town/@antijingoist/111864760073049505)\\n\\nand try to look up to which repository the packages mentioned in the screenshot\\nbelong, we will find out that they belong to `universe` repository which is\\nmaintained by the community. Not to mention nature of the packages: multimedia.\\n\\nYou may think about this as a scam, but considering repository consisting of 70k\\npackages, it is not an easy task to do. And with LTS releases we\'re talking\\nabout 5+ years of support.\\n\\n:::info Fedora\\n\\nTry to compare this state to Fedora. It also has a 6-month release cycle, but\\nthere are no LTS releases and each release is supported only for a year.\\n\\n:::\\n\\nCommon strategy, at this point, is to pull out the _open-source_. Yes, we are\\nstill dealing with the open-source, but keep in mind that you\'re trying to patch\\nsome issue in a version that\'s 5 years old, upstream definitely doesn\'t care\\nanymore[^4], the development didn\'t stop 5 years ago, it\'s going on and fixing\\nthis issue in a release from 5 years is not the same as fixing it in the current\\nrelease. At this point, if you are paying for such support, you are actually\\npaying for someone to do _software archaeology_ which **can be** _non-trivial_\\nto do.\\n\\nIn the case of Ubuntu Pro we\'re talking about community support and best-effort\\nsupport by Canonical for the paying customers. And that makes sense to me,\\nrunning LTS distro for 5+ years on a desktop seems like an odd choice, even\\nwith the help of _[podman]_ and _[distrobox]_ or _[toolbx]_ that allow us to use\\nstable or LTS distro as a base and containerized development environments on top\\nof that.\\n\\n## RHEL ecosystem\\n\\nRHEL ecosystem is much more complicated in this matter. However it\'s very\\nsimilar to the way SUSE operates with few exceptions.\\n\\nYou can see a flow diagram here:\\n\\n```mermaid\\nflowchart LR;\\n U[upstream] --\x3e FR[Fedora Rawhide];\\n FR --\x3e F[Fedora release];\\n F --\x3e C[CentOS Stream];\\n C --\x3e R[RHEL];\\n```\\n\\nKey things to take and not to take from the flow diagram:\\n\\n- getting from one upstream to its respective downstream is not as simple as the\\n presence of an arrow and it\'s not the same process for all of them\\n- lengths of the arrows are not proportional, specifically:\\n - Fedora Rawhide is _supposed to_ consume updates as soon as possible,\\n - depending on the decision of the maintainer they can, but _don\'t have to_ be\\n included in the currently supported Fedora releases (you can take [Emacs] as\\n an example of such package), but Rawhide eventually becomes the next Fedora\\n release,\\n - CentOS Stream gets branched off a specific Fedora release, and then\\n - ultimately CentOS Stream becomes the next **minor** release of RHEL.\\n- this diagram is simplified by **a lot**\\n\\n:::tip SUSE flow for comparison\\n\\nI\'ll also include a SUSE flow, so you can compare:\\n\\n```mermaid\\nflowchart LR;\\n U[upstream] --\x3e T[openSUSE Tumbleweed];\\n T --\x3e L[openSUSE Leap];\\n L --\x3e S[SUSE Linux Enterprise];\\n S --\x3e L;\\n```\\n\\nYou can notice, as opposed to the RHEL ecosystem, some changes are being\\nbackported to the openSUSE Leap.\\n\\nHowever this is subject to change as there is a new [ALP] project arising which\\nis, more than likely, going to replace the Leap.\\n\\n:::\\n\\n### Change in the model\\n\\nThe flow I\'ve shown above is in effect since late \u201820 and early \u201821. I hope you\\ncan see that it is quite similar to the way SUSE operates too. Before late \u201820\\nthe flow was following:\\n\\n```mermaid\\nflowchart LR;\\n U[upstream] --\x3e FR[Fedora Rawhide];\\n FR --\x3e F[Fedora release];\\n F --\x3e R[RHEL];\\n R --- C[CentOS];\\n```\\n\\nCentOS was the last distribution in that \u201cchain\u201d. This provides some benefits\\nand some negatives.\\n\\n#### Before the change\\n\\nFrom the point of a developer, unless you have some kind of an early access to\\nRHEL, you don\'t see the changes until they land and are already released. This\\nimpairs your ability to test and verify your software before shipping it to your\\nclients that use RHEL.\\n\\nFrom the point of a user, there is one positive, you basically get \u201cfree RHEL\u201d\\nwithout the support. This also allowed you to report bugs against the RHEL,\\nsince they were 1:1 distros (minus the branding and support). So you\'d\\ntechnically get RHEL free of charge.\\n\\nBenefit of such project, except for the cost, is questionable. The main issue,\\nwhich actually became even more apparent after changing the flow, is someone\\nelse repackaging your own product and selling it again.\\n\\n#### After the change\\n\\nFirst of all, the current flow counters the issue mentioned above. You can test\\nyour projects against the _next minor RHEL release_. CentOS Stream is free, so\\nyou can freely incorporate it into your CI pipelines.\\n\\n:::tip Shameless plug pt. 2\\n\\nAgain, [Packit] can help you on upstream to verify that you\'re not breaking your\\nRPM builds and on top of that you can also use [Testing Farm] to run tests on a\\nspecific Fedora or CentOS Stream releases.\\n\\n> Green tests may not be green everywhere and catching such issues as soon as\\n> possible costs much less than catching them further down the chain.\\n\\n:::\\n\\nThere are many people thinking that RHEL has become closed-source. It is not.\\nThe development happens _out in the open_, it\'s more open that it was before.\\nHowever with the cost of not getting the exact same thing for free. You can get\\nthe next minor RHEL, not the same that\'s normally paid for. [Packit] is an\\nexample of a service that is deployed on the CentOS 9 Stream and even used to be\\ndeployed on Fedora, but the regular 6-month release cycle caused some minor\\nissues here and there.\\n\\n_Production-ready_ is something that heavily depends on the context\u2026\\n\\n:::tip Free \u201cclones\u201d\\n\\nAfter this change so-called _free \u201cclones\u201d_ emerged. I have to admit that in\\ncase of _[AlmaLinux]_ I can see some benefits e.g., pushing for live images and\\nsupport of various desktop environments, Raspberry Pi support or even WSL images\\nbeing present in the M$ Store and easy to install.\\n\\n:::\\n\\n## Open-source and paid support\\n\\nOverall I don\'t think that paying for the support of 5 years old _non-critical_\\npackages is going against the open-source. It is a non-trivial work that, in\\nmajority of cases, cannot be included in the upstream, therefore the benefit is\\nreapt only by the paying customers. I have to admit that in the case of the\\nUbuntu Pro it may seem a bit weird (hiding patches behind the paywall). However\\nwe\'re still talking about rather big set of packages that will affect a minority\\nof server workloads, if any.\\n\\n## Glossary\\n\\n- _rolling release_ - continuously released without \u201csignificant milestones\u201d\\n\\n :::tip\\n\\n As an example of rolling distribution you can take archLinux, openSUSE\\n Tumbleweed, Fedora Rawhide, or even CentOS 9 Stream.\\n\\n As en example of **not** rolling distribution you can take Ubuntu, openSUSE\\n Leap or Fedora.\\n\\n :::\\n\\n- _bleeding edge_ - contains the latest versions as they are released on the\\n upstream\\n\\n :::tip\\n\\n As an example you can take archLinux, openSUSE Tumbleweed or Fedora Rawhide.\\n You can also notice how common it is to combine _rolling release_ with\\n _bleeding edge_.\\n\\n :::\\n\\n- _upstream_ & _downstream_\\n\\n You\'re most likely to meet these terms in the meaning of upstream being the\\n project itself and downstream being the packaging of said project in some\\n distribution.\\n\\n However this can also apply to distributions like _openSUSE Tumbleweed_ with\\n _openSUSE Leap_, _Fedora_ with _CentOS Stream_, or even _CentOS Stream_ with\\n _RHEL_. This basically means that the packages/software is being released into\\n the upstream (Tumbleweed, Fedora, or even CentOS) and then after being tested\\n is taken further down into their respective downstreams (Leap, CentOS, RHEL).\\n\\n[almalinux]: https://almalinux.org/\\n[alp]: https://susealp.io/\\n[distrobox]: https://distrobox.it/\\n[emacs]: https://src.fedoraproject.org/rpms/emacs/\\n[packit]: https://packit.dev/\\n[podman]: https://podman.io/\\n[testing farm]: https://docs.testing-farm.io/Testing%20Farm/0.1/index.html\\n[toolbx]: https://containertoolbx.org/\\n[ubuntu pro]: https://ubuntu.com/pro/\\n[zorin os]: https://zorin.com/os/pro/\\n\\n[^1]: Richard Stallman\\n[^2]: directed acyclic graph\\n[^3]:\\n Ubuntu Pro is technically a service whereas the RHEL and SLE are distros\\n with the support included.\\n\\n[^4]:\\n There are upstream projects that keep LTS branches, such as Linux kernel,\\n but even in the case of the kernel itself, they\'re planning on ending it,\\n since the cost outweighs the benefits at this point."},{"id":"/2024/01/28/rust-opinion","metadata":{"permalink":"/blog/2024/01/28/rust-opinion","editUrl":"https://github.com/mfocko/blog/tree/main/blog/2024-01-28-rust-opinion.md","source":"@site/blog/2024-01-28-rust-opinion.md","title":"Mixed feelings on Rust","description":"Discussing my mixed feelings about the Rust language.\\n","date":"2024-01-28T00:00:00.000Z","formattedDate":"January 28, 2024","tags":[{"label":"rust","permalink":"/blog/tags/rust"},{"label":"memory safety","permalink":"/blog/tags/memory-safety"},{"label":"cult","permalink":"/blog/tags/cult"},{"label":"hype","permalink":"/blog/tags/hype"}],"readingTime":15.395,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. passionate language hater","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"Mixed feelings on Rust","description":"Discussing my mixed feelings about the Rust language.\\n","date":"2024-01-28T00:00:00.000Z","authors":[{"key":"mf","title":"a.k.a. passionate language hater"}],"tags":["rust","memory safety","cult","hype"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"LTS distributions","permalink":"/blog/2024/02/07/lts-distros"},"nextItem":{"title":"How can Copr help with broken dependencies","permalink":"/blog/2023/08/02/copr"}},"content":"Rust has become a rather popular language these days. I\'ve managed to get my\\nhands dirty with it during _[Advent of Code]_ \u201822 and partially \u201823. I\'ve also\\nused it for few rounds of _[Codeforces]_ and I have to try very hard to maintain\\nsome variety of languages for LeetCode challenges along with the Rust. I\'ll\\ndisclaim up front that I won\'t be only positive, since this post is a result of\\nmultiple discussions about Rust and I stand by\\n_\u201cAll that glitters is not gold\u201d_, so if you can\'t stand your favorite language\\nbeing criticized in any way, don\'t even proceed. :wink:\\n\\n\x3c!--truncate--\x3e\\n\\n## Memory safety\\n\\nI\'ll start by kicking the biggest benefit of the language, the memory safety.\\nLet\'s be honest here, majority of the checks rely on the static analysis, cause\\nyou can\'t do anything else during the compile-time, right? Therefore we can\\nbasically say that we are relying on the compiler to \u201csolve\u201d all of our issues.\\n\\n:::danger\\n\\nI\'m not doubting the fact that compiler can prevent **a lot** of the memory\\nerrors, I\'m just saying it\'s not realistic to cover **everything**.\\n\\n:::\\n\\n### Compiler\\n\\nI guess we can safely[^2] agree on the fact that we 100% rely on the compiler to\\n_have our back_. Is the compiler bug-free? I doubt it. This is not meant in an\\noffensive way to the Rust compiler developers, but we need to be realistic here.\\nIt\'s a compiler, even older and larger projects like _gcc_ or _llvm_ can\'t avoid\\nbugs to appear.\\n\\nWhen I was trying out Rust for some of the LeetCode challenges I\'ve stumbled\\nupon the following warning:\\n![Example of a compiler bug](https://i.imgur.com/NfPLF6o.png)\\n\\n:::danger [Issue](https://github.com/rust-lang/rust/issues/59159)\\n\\nThe issue here comes from the fact that we have 2 simultaneous references to the\\nsame memory (one is mutable and one immutable). If you cannot think of any way\\nthis can break, I\'ll give you a rather simple example from C++ where this could\\ncause an issue.\\n\\nImagine a function that has some complex object and also calls a coroutine which\\nutilizes read-only reference to that object. When the coroutine suspends, the\\ncaller can modify the object. This can break the integrity of data read by the\\ncoroutine.\\n\\n- Yes, this **can** cause a memory error.\\n- Yes, this **hasn\'t** been handled until someone noticed it.\\n\\nFixing this bug is not backwards compatible, cause you\'re covering a case that\\nhasn\'t been covered before.\\n\\n:::\\n\\n### Enforcing the safety\\n\\nOne of the ways Rust enforces the safety is by restricting what you can do, like\\nthe example above. Aforementioned issue _can_ happen, but **doesn\'t have to**.\\nRule of the thumb in the Rust compiler is to _\u201cblock\u201d_ anything that can be an\\nissue, static analysis can\'t do much more, it cannot decide whether it\'s safe to\\ndo it or not.\\n\\nSatisfying the Rust compiler is sometimes a brutal pain in the ass, because you\\ncannot do things like you\'re used to, you need to work around them _somehow_.\\n\\n:::tip\\n\\nKey difference between Rust and C or C++ lies in the fact that Rust chooses to\\n_ban_ all \u201cpotentially offensive\u201d actions, C and C++ _relies_ on **you** to be\\nsure it\'s safe to do.\\n\\n![C++ v. Rust](https://i.imgur.com/0vbkYPp.png)\\n\\n:::\\n\\n### Consequences\\n\\nWhere are we heading with this approach of \u201cif it compiles, it runs\u201d though?\\nIn this aspect I have a rather similar opinion as with regards to the ChatGPT\\nand its derivatives.\\n\\nIf you teach people to 100% depend on the compiler, they will do it, cause it\'s\\n_easy_. All you need to do is make the compiler _shut up_[^3]. Giving up the\\n_intellectual masturbation_ about the memory safety will make you lose your edge\\nover the time. When we get to the point of everyone being in the mindset\\nmentioned above, who\'s going to maintain the compiler? This is the place where\\nyou **need to** think about the memory safety and furthermore in a much more\\ngeneral way than in your own projects, because it is the thing that everyone\\n_blindly believes in_ in the end.\\n\\nI\'m not saying that everyone should give up Rust and think about their memory\\nmanagement and potential memory issues. I\'m just saying that going the easy way\\nwill make people _dull_ and they should think about it anyways, that\'s how the\\nissue above has been discovered. If everyone walked past and didn\'t think about\\nit, no one would discover this issue till it bit them hard.\\n\\n:::tip Standard library\\n\\nEven the standard library is littered with `unsafe` blocks that are prefixed\\nwith comments in style:\\n\\n```rs\\n// SAFETY: \u2026\\n```\\n\\nThe fact that the _casual_ Rust dev doesn\'t have to think much about safety,\\ncause the compiler has their back, doesn\'t mean that the Rust compiler dev\\ndoesn\'t either.\\n\\nI gotta admit that I adopted this concept in other languages (even in Python),\\ncause you can encounter situations where it doesn\'t have to be clear _why_ you\\ncan do _what_ you\'re doing.\\n\\n:::\\n\\n## Development & design\\n\\nDevelopment of Rust is\u2026 very fast. One positive is that they\'re trying to be as\\nbackward compatible as possible at least by verifying against all the published\\ncrates in the process. Of course, you cannot be backward compatible about fixing\\nthe bugs that have been found, but such is life.\\n\\n### Fast development cycle\\n\\nOne of the negatives of the fast development cycle is the fact that they\'re\\nusing the latest features already in the next release of the Rust. Yes, it is\\nsomething that you can use for verifying and testing your own changes, but at\\nthe same time it places a requirement of the latest release to compile the next\\none.\\n\\n:::tip\\n\\nIf you check `gcc` for example, they have a requirement of minimal version of\\ncompiler that you need for the build. Though gcc\'s requirement is not so _needy_\\nas the Rust one.\\n\\n:::\\n\\nOne of the other negatives is the introduction of bugs. If you\'re pushing\\nchanges, somewhat mindlessly, at such a fast pace, it is inevitable to introduce\\na bunch bugs in the process. Checking the GitHub issue tracker with\\n\\n```\\nis:issue is:open label:C-bug label:T-compiler\\n```\\n\\nyields **2,224** open issues at the time of writing this post.\\n\\n### RFCs\\n\\nYou can find **a lot** of RFCs for the Rust. Some of them are more questionable\\nthan the others. Fun thing is that a lot of them make it to the nightly builds,\\nso they can be tested and polished off. Even the questionable ones\u2026 I\'ll leave\\nfew examples for a better understanding.\\n\\nOne of such features is the `do yeet` expression:\\n\\n```rust\\n#![feature(yeet_expr)]\\n\\nfn foo() -> Result<String, i32> {\\n do yeet 4;\\n}\\nassert_eq!(foo(), Err(4));\\n\\nfn bar() -> Option<String> {\\n do yeet;\\n}\\nassert_eq!(bar(), None);\\n```\\n\\nIt allows you to \u201cyeet\u201d the errors out of the functions that return `Result` or\\n`Option`.\\n\\n[One](https://github.com/rust-lang/rfcs/pull/3503) of the more recent ones is\\nthe ability to include Cargo manifests into the sources, so you can do something\\nlike:\\n\\n```rust\\n#!/usr/bin/env cargo\\n---\\n[dependencies]\\nclap = { version = \\"4.2\\", features = [\\"derive\\"] }\\n---\\n\\nuse clap::Parser;\\n\\n#[derive(Parser, Debug)]\\n#[clap(version)]\\nstruct Args {\\n #[clap(short, long, help = \\"Path to config\\")]\\n config: Option<std::path::PathBuf>,\\n}\\n\\nfn main() {\\n let args = Args::parse();\\n println!(\\"{:?}\\", args);\\n}\\n```\\n\\nI would say you can get almost anything into the language\u2026\\n\\n## Community and hype train\\n\\nRust community is a rather unique thing. A lot of people will hate me for this,\\nbut I can\'t help, but to compare them to _militant vegans_. I\'ll go through some\\nof the things related to it, so I can support my opinion at least.\\n\\n_Rust is the best language._ It is not. There is no best language, each has its\\nown positives and negatives, you need to choose the language that\'s **the most**\\n**suitable for your use case**. There are areas where Rust excels, though I have\\nto admit it\'s very close to being a universal hammer regardless of how suitable\\nit is. There is a very steep learning curve to it, beginnings in Rust are very\\npainful.\\n\\n_Rewrite everything in Rust._ Just no. There are multiple feedbacks on doing\\nrewrites, it is very common to fix _N_ bugs with a rewrite while introducing\\n_N + 1_ other bugs in the process. It doesn\'t solve anything unless there are\\nsome strong reasons to go with it. Majority of such suggested rewrites don\'t\\nhave those reasons though.\\n\\n_Language \u2039x\u203a is bad, though in Rust\u2026_ Cherry-picking one specific pain point of\\none language and reflecting how it is better in other language can go both ways.\\nFor example it is rather easy to pick the limitations imposed by Rust compiler\\nand show how it\'s possible in other languages :man_shrugging:\\n\\nI don\'t mind any of those opinions, you\'re free to have them, as long as you\\ndon\'t rub them in my face which is not the usual case\u2026 This experience makes it\\njust worse for me, part of this post may be also influenced by this fact.\\n\\n### Rust in Linux\\n\\n:::warning[caution]\\n\\nAs someone who has seen the way Linux kernel is built in the RHEL ecosystem, how\\ncomplex the whole thing is and how much resources you need to proceed, I have\\nvery strong opinions on this topic.\\n\\n:::\\n\\nIt took years of work to even \u201cincorporate\u201d Rust into the Linux codebase, just\\nto get the \u201cHello World!\u201d. I don\'t have anything against the idea of writing\\ndrivers in the Rust, I bet it can catch a lot of common mistakes, but still\\nintroducing Rust to the kernel is another step to enlarge the monster.\\n\\nI have to admit though that the _Apple GPU_ driver for Linux written in Rust is\\nquite impressive. Apart from that there are not so many benefits, yet\u2026\\n\\n## Packaging\\n\\nI\'ll divide the packaging into the packaging of the language itself and the\\nprograms written in Rust.\\n\\nLet\'s start with the `cargo` itself though. Package managers of the languages\\nusually get a lot of hate (you can take `npm` or `pip` as examples[^1]). If\\nyou\'ve ever tried out Rust, I bet you already know where I\'m going with this.\\nYes, I mean the compilation times, or even Cargo downloading _whole_ index of\\ncrates just so you can update that one dependency (and 3 millions of indirect\\ndeps). When I was doing AoC \u201822 in Rust, I\'ve set up `sccache` right away on the\\nfirst day.\\n\\nLet\'s move to the packaging of the Rust itself, it\'s tedious. Rust has a very\\nfast development cycle and doesn\'t even try to make the builds backward\\ncompatible. If there is a new release of Rust, there is a very high chance that\\nyou cannot build that release with anything other than **the latest** Rust\\nrelease. If you have ever touched the packaging, you know that this is something\\nthat can cause a lot of problems, cause you need the second-to-latest version to\\ncompile the latest version, don\'t forget that this applies inductively\u2026 People\\nrunning _Gentoo_ could tell you a lot about this.\\n\\n:::info\\n\\nCompiling the compilers takes usually more time than compiling the kernel\\nitself\u2026\\n\\n:::\\n\\nI cannot speak about packaging of Rust programs in other than RHEL-based\\ndistros, though I can speak about RHEL ecosystem. Fedora packaging guidelines\\nspecify that you need to build each and every dependency of the program\\nseparately. I wanted to try out _AlmaLinux_ and install Alacritty there and I\\nfailed miserably. The solution that worked, consisted of ignoring the packaging\\nguidelines, running `cargo build` and consuming the binaries afterwards.\\nDependencies of the Rust programs are of a similar nature as JS dependencies.\\n\\n> I\'m tipping my fedora[^2] in the general direction of the maintainers of Rust\\n> packages in RHEL ecosystem. I wouldn\'t be able to do this without losing my\\n> sanity.\\n\\n## Likes\\n\\nIf you\'ve come all the way here and you\'re a Rustacean, I believe I\'ve managed\\nto get your blood boiling, so it\'s time to finish this off by stuff I like about\\nRust. I doubt I will be able to cover everything, but I can try at least. You\\nhave to admit it\'s much easier to remember the bad stuff as opposed to the good.\\n:wink:\\n\\n### Workflow and toolchain\\n\\nI prefered using Rust for the _Advent of Code_ and _Codeforces_ as it provides\\na rather easy way to test the solutions before running them with the challenge\\ninput (or test runner). I can give an example from the _Advent of Code_:\\n\\n```rust\\nuse aoc_2023::*;\\n\\ntype Output1 = i32;\\ntype Output2 = Output1;\\n\\nstruct DayXX {}\\nimpl Solution<Output1, Output2> for DayXX {\\n fn new<P: AsRef<Path>>(pathname: P) -> Self {\\n let lines: Vec<String> = file_to_lines(pathname);\\n\\n todo!()\\n }\\n\\n fn part_1(&mut self) -> Output1 {\\n todo!()\\n }\\n\\n fn part_2(&mut self) -> Output2 {\\n todo!()\\n }\\n}\\n\\nfn main() -> Result<()> {\\n DayXX::main()\\n}\\n\\ntest_sample!(day_XX, DayXX, 42, 69);\\n```\\n\\nThis was the skeleton I\'ve used and the macro at the end is my own creation that\\nexpands to:\\n\\n```rust\\n#[cfg(test)]\\nmod day_XX {\\n use super::*;\\n\\n #[test]\\n fn part_1() {\\n let path = DayXX::get_sample(1);\\n let mut day = DayXX::new(path);\\n assert_eq!(day.part_1(), 42);\\n }\\n\\n #[test]\\n fn part_2() {\\n let path = DayXX::get_sample(2);\\n let mut day = DayXX::new(path);\\n assert_eq!(day.part_2(), 69);\\n }\\n}\\n```\\n\\nWhen you\'re solving the problem, all you need to do is switch between\\n`cargo test` and `cargo run` to check the answer to either sample or the\\nchallenge input itself.\\n\\nIntroduce [bacon] and it gets even better. Bacon is a CLI tool that wraps around\\nthe `cargo` and allows you to check, run, lint or run tests on each file save.\\nIt\'s a very pleasant thing for a so-called _compiler-assisted_ development.\\n\\nSpeaking of linting from within the bacon, you cannot leave out the [clippy].\\nNot only it can whip your ass because of errors, but it can also produce a lot\\nof helpful suggestions, for example passing slices by borrow instead of\\nborrowing the `Vec` itself when you don\'t need it.\\n\\n### Standard library\\n\\nThere\'s **a lot** included in the standard library. It almost feels like you\\nhave all you need[^4]. I like placeholders (like `todo!()`, `unreachable!()`,\\n`unimplemented!()`) to the extent of\\n[implementing](/cpp/exceptions-and-raii/placeholders) them as exceptions in C++.\\n\\nYou can find almost anything. Though you can also hit some very weird issues\\nwith some of the nuances of the type system.\\n\\n### `unsafe`\\n\\nThis might be something that people like to avoid as much as possible. However I\\nthink that forming a habit of commenting posibly unsafe operations in **any**\\nlanguage is a good habit, as I\'ve mentioned above. You should be able to argue\\nwhy you can do something safely, even if the compiler is not kicking your ass\\nbecause of it.\\n\\nExcerpt of such comment from work:\\n\\n```py\\n# SAFETY: Taking first package instead of specific package should be\\n# safe, since we have put a requirement on \xbbone\xab \u2039upstream_project_url\u203a\\n# per Packit config, i.e. even if we\'re dealing with a monorepo, there\\n# is only \xbbone\xab upstream. If there is one upstream, there is only one\\n# set of GPG keys that can be allowed.\\nreturn self.downstream_config.packages[\\n self.downstream_config._first_package\\n].allowed_gpg_keys\\n```\\n\\n### Traits\\n\\nOne of the other things I like are the traits. They are more restrictive than\\ntemplates or concepts in C++, but they\'re doing their job pretty good. If you\\nare building library and require multiple traits to be satisfied it means a lot\\nof copy-paste, but that\'s soon to be fixed by the [trait aliases].\\n\\n:::tip Comparing to other languages\\n\\nOn Wikipedia I\'ve seen trait being defined as a more restrictive type class as\\nyou may know it from the Haskell for example. C++ isn\'t behind either with its\\n_constraints and concepts_. I would say that we can order them in the following\\norder based on the complexity they can express:\\n\\n```\\nRust\'s trait < Haskell\'s type class < C++\'s concept\\n```\\n\\n:::\\n\\nYou can also hit some issues, like me when trying to support conversions between\\nunderlying numeric types of a 2D vectors or support for using an operator from\\nboth sides (I couldn\'t get `c * u` to work in the same way as `u * c` because\\nthe first one requires you to implement the trait of a built-in type).\\n\\n:::warning Implementation\\n\\nImplementing traits lies in\\n\\n```rust\\nimpl SomeTrait for SomeStruct {\\n // implementation goes here\\n}\\n```\\n\\nOne of the things I **would love to** see is being able to define the helper\\nfunctions within the same block. As of now, the only things allowed are the ones\\nthat are required by the trait, which in the end results in a randomly lying\\nfunctions around (or in a implementation of the structure itself). I don\'t like\\nthis mess at all\u2026\\n\\n:::\\n\\n### Influence of functional paradigm\\n\\nYou can see a big influence of the functional paradigm. Not only in iterators,\\nbut also in the other parts of the language. For example I prefer `Option<T>` or\\n`Result<T, E>` to `null`s and exceptions. Pattern matching together with\\ncompiler both enforces handling of the errors and rather user-friendly way of\\ndoing it.\\n\\nNot to mention `.and_then()` and such. However spending most of the time with\\nthe AoC you get pretty annoyed of the repetitive `.unwrap()` during parsing,\\nsince you are guaranteed correct input.\\n\\n### Macros\\n\\nMacros are a very strong pro of the Rust. And no, we\'re not going to talk about\\nthe procedural macros\u2026\\n\\nAs I\'ve shown above I\'ve managed to \u201ctame\u201d a lot of copy-paste in the tests for\\nthe AoC by utilizing a macro that generated a very basic template for the tests.\\n\\nAs I have mentioned the traits above, I cannot forget to give props to `derive`\\nmacro that allows you to \u201cdeduce\u201d the default implementation. It is very helpful\\nfor a tedious tasks like implementing `Debug` (for printing out the structures)\\nor comparisons, though with the comparisons you need to be careful about the\\ndefault implementation, it has already bitten me once or twice.\\n\\n## Summary\\n\\nOverall there are many things about the Rust I like and would love to see them\\nimplemented in other languages. However there are also many things I don\'t like.\\nNothing is **exclusively** black and white.\\n\\n[advent of code]: https://adventofcode.com\\n[bacon]: https://dystroy.org/bacon/\\n[clippy]: https://github.com/rust-lang/rust-clippy\\n[codeforces]: https://codeforces.com\\n[trait aliases]: https://github.com/rust-lang/rfcs/blob/master/text/1733-trait-alias.md\\n\\n[^1]:\\n not to even mention multiple different packaging standards Python has, which\\n is borderline https://xkcd.com/927/\\n\\n[^2]: pun intended\\n[^3]: It\'s not that easy with the Rust compiler, but OK\u2026\\n[^4]:\\n unlike Python where there\'s whole universe in the language itself, yet there\\n are essential things not present\u2026"},{"id":"/2023/08/02/copr","metadata":{"permalink":"/blog/2023/08/02/copr","editUrl":"https://github.com/mfocko/blog/tree/main/blog/2023-08-02-copr.md","source":"@site/blog/2023-08-02-copr.md","title":"How can Copr help with broken dependencies","description":"Copr comes to save you when maintainer doesn\'t care.","date":"2023-08-02T00:00:00.000Z","formattedDate":"August 2, 2023","tags":[{"label":"\ud83c\udfed","permalink":"/blog/tags/\ud83c\udfed"},{"label":"red-hat","permalink":"/blog/tags/red-hat"},{"label":"copr","permalink":"/blog/tags/copr"},{"label":"admin","permalink":"/blog/tags/admin"},{"label":"vps","permalink":"/blog/tags/vps"}],"readingTime":3.44,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. your opinionated admin","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"How can Copr help with broken dependencies","description":"Copr comes to save you when maintainer doesn\'t care.","date":"2023-08-02T00:00:00.000Z","authors":[{"key":"mf","title":"a.k.a. your opinionated admin"}],"tags":["\ud83c\udfed","red-hat","copr","admin","vps"]},"unlisted":false,"prevItem":{"title":"Mixed feelings on Rust","permalink":"/blog/2024/01/28/rust-opinion"},"nextItem":{"title":"4th week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/4th-week"}},"content":"When you decide to run Fedora on your VPS, you might get screwed over by using\\nrandom repositories\u2026\\n\\n\x3c!--truncate--\x3e\\n\\nWhen I \u201creserved\u201d my VPS[^1] back in June \'20, I slapped Fedora on it without\\nthinking. I bet 99% of people would say that I\'m crazy for doing such thing[^2],\\n**BUT** I\'ve been using Fedora on my PCs for some time already and it felt very\\nstable and natural to just use, even for VPS.\\n\\nOne of the first things I\'ve done was setting up a mail server. You may guess\\nwhat\'s the fun part about having a mail server\u2026 Yes, it\'s all the spam you\\nreceive and only then you realize how much \u201ccrap\u201d gets filtered on free mail\\nservices. To battle this problem I chose to use\\n[rspamd](https://github.com/rspamd/rspamd) that had CentOS support, but someone\\nhad a [Copr](https://copr.fedorainfracloud.org/) repository that I used to\\ninstall it.\\n\\n## How does Copr repositories work?\\n\\nIf you have ever used Ubuntu, you might be familiar with the concept since it is\\nvery close to [PPAs](https://help.ubuntu.com/community/PPA).\\n\\ntl;dr of the whole process consists of\\n\\n1. enabling the Copr repository, and\\n2. installing the desired package.\\n\\nSo in shell you would do\\n\\n```\\n# dnf copr enable \u2039copr-repository\u203a\\n# dnf install \u2039package-from-the-repository\u203a\\n```\\n\\nAnd\u2026 that\'s it! Nothing else needed! Simple, right? And literally same process\\nas you would do for the PPA.\\n\\n:::tip AUR\\n\\nOn the other hand, if you are familiar with the archLinux, you definitely know\\nAUR and what it can do for you. Copr repository is pretty similar, but the\\npackages are prebuilt in Copr and Copr repositories can carry the required\\ndependencies for said packages, which simplifies the distribution, and can even\\nhelp with installing singular packages (when you just need the dependency, not\\neverything).\\n\\n:::\\n\\n## My issue\\n\\nNow you might wonder how would I use it on my VPS. It\'s rather simple, once in\\n6 months a new Fedora release comes out. And you need to upgrade to newer\\nrelease\u2026 You don\'t need to do it right away and for such setup it probably isn\'t\\neven recommended.\\n\\n:::tip\\n\\nFedora releases are supported for a year, i.e. they live 6 months till the next\\nrelease and then another 6 months till another release.\\n\\nSome people prefer to run one version \u201cbehind\u201d. If you ever decide to run it on\\nyour home server or in a similar setup, it might be a pretty good idea to\\nfollow. I\'m using the \u201clatest greatest\u201d, cause why not :smile:\\n\\nOne way or another, you still need to bump the release every six months, unless\\nyou\'d bump 2 releases at once every year, which would be a decision, since, at\\nleast I, cannot see any benefits in it\u2026 You don\'t go for \u201cstability\u201d, cause once\\na year you switch to the latest release and then, before you bump, you use one\\nyear old software, so you\'re not even using the latest.\\n\\n:::\\n\\nFast-forward 2 years in the future, new Fedora release came out (October \'22)\\nand I was doing an upgrade. Dependencies of the rspamd have been updated and\\nrspamd builds in Copr have failed and no one fixed it. Cool, so now I can\\nupgrade, but can either ignore the dependencies or uninstall the rspamd\u2026\\n\\n## How can Copr help?\\n\\nI have managed to find\\n[specfile](https://github.com/rspamd/rspamd/blob/master/rpm/rspamd.spec) for the\\nrspamd package that they use for CentOS. There were some files apart from the\\nspecfile, so I had to make an SRPM locally and then\u2026 I just uploaded the SRPM\\nto the Copr to\\n[build](https://copr.fedorainfracloud.org/coprs/mfocko/rspamd/build/5046567/)\\nan RPM.\\n\\nI have switched the previous Copr repository for rspamd with my own and happily\\nproceeded with the upgrade.\\n\\n## Conclusion\\n\\nCopr is heavily used for testing builds on the upstream with\\n[Packit](https://packit.dev). However, as you can see, it is possible to use it\\n**very well** for packaging your own stuff and avoiding issues (such as the one\\nI have described above), if need be.\\n\\n[^1]: [vpsFree.cz](https://vpsfree.cz)\\n[^2]:\\n Even though I\'ve been running archLinux on some Raspberry Pi\'s and also\\n on one of my \u201chome servers\u201d, before getting the VPS. You could say I like\\n to live on the edge\u2026"},{"id":"aoc-2022/4th-week","metadata":{"permalink":"/blog/aoc-2022/4th-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/04-week-4.md","source":"@site/blog/aoc-2022/04-week-4.md","title":"4th week of Advent of Code \'22 in Rust","description":"Surviving fourth week in Rust.","date":"2023-07-07T15:14:00.000Z","formattedDate":"July 7, 2023","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":15.315,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"4th week of Advent of Code \'22 in Rust","description":"Surviving fourth week in Rust.","date":"2023-07-07T15:14","slug":"aoc-2022/4th-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"How can Copr help with broken dependencies","permalink":"/blog/2023/08/02/copr"},"nextItem":{"title":"3rd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/3rd-week"}},"content":"Let\'s go through the fourth week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n## [Day 22: Monkey Map](https://adventofcode.com/2022/day/22)\\n\\n:::info tl;dr\\n\\nSimulating a movement on a 2D map with given instructions. Map becomes a cube in\\nthe 2nd part\u2026\\n\\n:::\\n\\n:::danger Rant\\n\\nThis was the most obnoxious problem of this year\u2026 and a lot of Rust issues have\\nbeen hit.\\n\\n:::\\n\\n### Solution\\n\\nIt seems like a very simple problem to solve, but with very obnoxious changes in\\nthe 2nd part and also it\'s relatively hard to decompose \xbbproperly\xab.\\n\\n#### Column iterator\\n\\nIn the first part of the problem it was needed to know the boundaries of each\\nrow and column, since I stored them in `Vec<Vec<char>>` and padded with spaces\\nto ensure I have a rectangular 2D \u201carray\u201d. However when you wanted to go through\\neach row and column to determine the boundaries, it was very easy to do for the\\nrows (cause each row is a `Vec` element), but not for the columns, since they\\nspan multiple rows.\\n\\nFor this use case I have implemented my own _column iterator_:\\n\\n```rust\\npub struct ColumnIterator<\'a, T> {\\n map: &\'a [Vec<T>],\\n column: usize,\\n\\n i: usize,\\n}\\n\\nimpl<\'a, T> ColumnIterator<\'a, T> {\\n pub fn new(map: &\'a [Vec<T>], column: usize) -> ColumnIterator<\'a, T> {\\n Self { map, column, i: 0 }\\n }\\n}\\n\\nimpl<\'a, T> Iterator for ColumnIterator<\'a, T> {\\n type Item = &\'a T;\\n\\n fn next(&mut self) -> Option<Self::Item> {\\n if self.i >= self.map.len() {\\n return None;\\n }\\n\\n self.i += 1;\\n Some(&self.map[self.i - 1][self.column])\\n }\\n}\\n```\\n\\nGiven this piece of an iterator, it is very easy to factor out the common\\nfunctionality between the rows and columns into:\\n\\n```rust\\nlet mut find_boundaries = |constructor: fn(usize) -> Orientation,\\n iterator: &mut dyn Iterator<Item = &char>,\\n upper_bound,\\n i| {\\n let mut first_non_empty = iterator.enumerate().skip_while(|&(_, &c)| c == \' \');\\n let start = first_non_empty.next().unwrap().0 as isize;\\n\\n let mut last_non_empty = first_non_empty.skip_while(|&(_, &c)| c != \' \');\\n let end = last_non_empty.next().unwrap_or((upper_bound, &\'_\')).0 as isize;\\n\\n boundaries.insert(constructor(i), start..end);\\n};\\n```\\n\\nAnd then use it as such:\\n\\n```rust\\n// construct all horizontal boundaries\\n(0..map.len()).for_each(|row| {\\n find_boundaries(\\n Orientation::horizontal,\\n &mut map[row].iter(),\\n map[row].len(),\\n row,\\n );\\n});\\n\\n// construct all vertical boundaries\\n(0..map[0].len()).for_each(|col| {\\n find_boundaries(\\n Orientation::vertical,\\n &mut ColumnIterator::new(&map, col),\\n map.len(),\\n col,\\n );\\n});\\n```\\n\\n#### Walking around the map\\n\\nOnce the 2nd part got introduced, you start to think about a way how not to\\ncopy-paste a lot of stuff (I haven\'t avoided it anyways\u2026). In this problem, I\'ve\\nchosen to introduce a trait (i.e. _interface_) for 2D and 3D walker.\\n\\n```rust\\ntrait Wrap: Clone {\\n type State;\\n\\n // simulation\\n fn is_blocked(&self) -> bool;\\n fn step(&mut self, steps: isize);\\n fn turn_left(&mut self);\\n fn turn_right(&mut self);\\n\\n // movement\\n fn next(&self) -> (Self::State, Direction);\\n\\n // final answer\\n fn answer(&self) -> Output;\\n}\\n```\\n\\nEach walker maintains its own state and also provides the functions that are\\nused during the simulation. The \u201cpromised\u201d methods are separated into:\\n\\n- _simulation_-related: that are used during the simulation from the `.fold()`\\n- _movement_-related: just a one method that holds most of the logic differences\\n between 2D and 3D\\n- _final answer_: which extracts the _proof of solution_ from the\\n implementation-specific walker\\n\\nBoth 2D and 3D versions borrow the original input and therefore you must\\nannotate the lifetime of it:\\n\\n```rust\\nstruct Wrap2D<\'a> {\\n input: &\'a Input,\\n position: Position,\\n direction: Direction,\\n}\\nimpl<\'a> Wrap2D<\'a> {\\n fn new(input: &\'a Input) -> Wrap2D<\'a> {\\n// \u2026\\n```\\n\\n#### Problems\\n\\nI have used a lot of closures for this problem and once I introduced a parameter\\nthat was of unknown type (apart from the fact it implements a specific trait), I\\ngot suggested a \u201cfix\u201d for the compilation error that resulted in something that\\nwas not possible to parse, cause it, more than likely, violated the grammar.\\n\\nIn a similar fashion, I have been suggested changes that led to a code that\\ndidn\'t make sense by just looking at it (there was no need to try the changes),\\nfor example one suggested change in the closure parameter caused disapperance of\\nthe parameter name. :smile:\\n\\n#### Clippy\\n\\nI have to admit that Clippy was rather helpful here, I\'ll include two examples\\nof rather smart suggestions.\\n\\nWhen writing the parsing for this problem, the first thing I have spotted on the\\n`char` was the `.is_digit()` function that takes a radix as a parameter. Clippy\\nnoticed that I use `radix = 10` and suggested switching to `.is_ascii_digit()`\\nthat does exactly the same thing:\\n\\n```diff\\n- .take_while(|c| c.is_digit(10))\\n+ .take_while(|c| c.is_ascii_digit())\\n```\\n\\nAnother useful suggestion appeared when working with the iterators and I wanted\\nto get the $n$-th element from it. You know the `.skip()`, you know the\\n`.next()`, just \u201cslap\u201d them together and we\'re done for :grin: Well, I got\\nsuggested to use `.nth()` that does exactly the combination of the two mentioned\\nmethods on iterators:\\n\\n```diff\\n- match it.clone().skip(skip).next().unwrap() {\\n+ match it.clone().nth(skip).unwrap() {\\n```\\n\\n## [Day 23: Unstable Diffusion](https://adventofcode.com/2022/day/23)\\n\\n:::info tl;dr\\n\\nSimulating movement of elves around with a set of specific rules.\\n\\n:::\\n\\n### Solution\\n\\nThere\'s not much to mention since it\'s just a cellular automaton simulation\\n(even though the AoC rules for cellular automatons usually get out of hand\\n:wink:).\\n\\nAlthough I had a need to determine boundaries of the elves\' positions and ended\\nup with a nasty DRY violation. Knowing that you you\'re looking for maximum and\\nminimum that are, of course, exactly the same except for initial values and\\ncomparators, it looks like a rather simple fix, but typing in Rust is something\\nelse, right? In the end I settled for a function that computes both boundaries\\nwithout any duplication while using a closure:\\n\\n```rust\\nfn get_bounds(positions: &Input) -> (Vector2D<isize>, Vector2D<isize>) {\\n let f = |init, cmp: &dyn Fn(isize, isize) -> isize| {\\n positions\\n .iter()\\n .fold(Vector2D::new(init, init), |acc, elf| {\\n Vector2D::new(cmp(acc.x(), elf.x()), cmp(acc.y(), elf.y()))\\n })\\n };\\n\\n (f(isize::MAX, &min::<isize>), f(isize::MIN, &max::<isize>))\\n}\\n```\\n\\nThis function returns a pair of 2D vectors that represent opposite points of the\\nbounding rectangle of all elves.\\n\\nYou might ask why would we need a closure and the answer is that `positions`\\ncannot be captured from within the nested function, only via closure. One more\\nfun fact on top of that is the type of the comparator\\n\\n```rust\\n&dyn Fn(isize, isize) -> isize\\n```\\n\\nOnce we remove the `dyn` keyword, compiler yells at us and also includes a way\\nhow to get a more thorough explanation of the error by running\\n\\n```shell\\n$ rustc --explain E0782\\n```\\n\\nwhich shows us\\n\\n> Trait objects must include the `dyn` keyword.\\n>\\n> Erroneous code example:\\n>\\n> ```\\n> trait Foo {}\\n> fn test(arg: Box<Foo>) {} // error!\\n> ```\\n>\\n> Trait objects are a way to call methods on types that are not known until\\n> runtime but conform to some trait.\\n>\\n> Trait objects should be formed with `Box<dyn Foo>`, but in the code above\\n> `dyn` is left off.\\n>\\n> This makes it harder to see that `arg` is a trait object and not a\\n> simply a heap allocated type called `Foo`.\\n>\\n> To fix this issue, add `dyn` before the trait name.\\n>\\n> ```\\n> trait Foo {}\\n> fn test(arg: Box<dyn Foo>) {} // ok!\\n> ```\\n>\\n> This used to be allowed before edition 2021, but is now an error.\\n\\n:::danger Rant\\n\\nNot all of the explanations are helpful though, in some cases they might be even\\nmore confusing than helpful, since they address _very simple_ use cases.\\n\\nAs you can see, even in this case there are two sides to the explanations:\\n\\n- it explains why you need to use `dyn`, but\\n- it still mentions that trait objects need to be heap-allocated via `Box<T>`\\n that, as you can see in my snippet, **does not** apply here :smile: IMO it\'s\\n caused by the fact that we are borrowing it and therefore we don\'t need to\\n care about the size or whereabouts of it.\\n\\n:::\\n\\n:::info C++ parallel\\n\\nIf you dive into the explanation above, you can notice that the `Box<dyn Trait>`\\npattern is very helpful for using types that are not known during compile-time.\\nYou would use a very similar approach in C++ when parsing some data structure\\nfrom input (let\'s say JSON for example).\\n\\nOn the other hand, in this case, it doesn\'t really make much sense, cause you\\ncan clearly see that the types **are known** during the compile-time, which in\\nC++ could be easily resolved by templating the helper function.\\n\\n:::\\n\\n## [Day 24: Blizzard Basin](https://adventofcode.com/2022/day/24)\\n\\n:::info tl;dr\\n\\nNavigating your way through a basin with series of blizzards that move around\\nyou as you move.\\n\\n:::\\n\\n:::warning[caution]\\n\\nIt\'s second to last day and I went \u201c_bonkers_\u201d on the Rust :smile: Proceed to\\nread _Solution_ part on your own risk.\\n\\n:::\\n\\n### Solution\\n\\nYou are given a map with blizzards all over the place and you\'re supposed to\\nfind the minimum time it requires you to walk through the basin without getting\\nin any of the blizzards.\\n\\n#### Breakdown\\n\\nRelatively simple, yet a bit annoying, approach can be taken. It\'s technically\\na shortest-path algorithm implementation with some relaxation restrictions and\\nbeing able to stay on one position for some time, so each _vertex_ of the graph\\nis determined by the position on the map and the _timestamp_. I have chosen to\\nuse `Vector3D<usize>`, since `x` and `y` attributes can be used for the position\\nand, well, let\'s use `z` for a timestamp, cause why not, right? :wink:\\n\\n#### Evaluating the blizzards\\n\\n:::warning[caution]\\n\\nI think that this is the most perverted abuse of the traits in the whole 4 weeks\\nof AoC in Rust\u2026\\n\\n:::\\n\\nThe blizzards move along their respective directions in time and loop around in\\ntheir respective row/column. Each vertex holds position **and** time, so we can\\n_just_ index the basin with the vertex itself, right? Yes, we can :smiling_imp:\\n\\n:::tip Fun fact\\n\\nWhile writing this part, I\'ve recognized unnecessary verbosity in the code and\\ncleaned it up a bit. The changed version is shown here and the original was just\\nmore verbose.\\n\\n:::\\n\\nI\'ll skip the boring parts of checking bounds and entry/exit of the basin :wink:\\nWe can easily calculate positions of the blizzards using a modular arithmetics:\\n\\n```rust\\nimpl Index<Position> for Basin {\\n type Output = char;\\n\\n fn index(&self, index: Position) -> &Self::Output {\\n // \u2039skipped boring parts\u203a\\n\\n // We need to account for the loops of the blizzards\\n let width = self.cols - 2;\\n let height = self.rows - 2;\\n\\n let blizzard_origin = |size, d, t, i| ((i - 1 + size + d * (t % size)) % size + 1) as usize;\\n [\\n (\\n index.y() as usize,\\n blizzard_origin(width, -1, index.z(), index.x()),\\n \'>\',\\n ),\\n (\\n index.y() as usize,\\n blizzard_origin(width, 1, index.z(), index.x()),\\n \'<\',\\n ),\\n (\\n blizzard_origin(height, -1, index.z(), index.y()),\\n index.x() as usize,\\n \'v\',\\n ),\\n (\\n blizzard_origin(height, 1, index.z(), index.y()),\\n index.x() as usize,\\n \'^\',\\n ),\\n ]\\n .iter()\\n .find_map(|&(y, x, direction)| {\\n if self.map[y][x] == direction {\\n Some(&self.map[y][x])\\n } else {\\n None\\n }\\n })\\n .unwrap_or(&\'.\')\\n }\\n}\\n```\\n\\nAs you can see, there is an expression for calculating the original position and\\nit\'s used multiple times, so why not take it out to a lambda, right? :wink:\\n\\nI couldn\'t get the `rustfmt` to format the `for`-loop nicely, so I\'ve just\\ndecided to go with iterating over an elements of a slice. I have used, once\\nagain, a combination of two functions (`find_map` in this case) to do 2 things\\nat once and at the end, if we haven\'t found any blizzard, we just return the\\nempty space.\\n\\nI think it\'s a very _nice_ (and naughty) way how to use the `Index` trait, don\'t\\nyou think?\\n\\n#### Shortest-path algorithm\\n\\nFor the shortest path you can choose and adjust any of the common shortest-path\\nalgorithms, in my case, I have decided to use [_A\\\\*_] instead of Dijkstra\'s\\nalgorithm, since it better reflects the _cost_ function.\\n\\n:::info Comparison of costs\\n\\nWith the Dijkstra\'s algorithm I would proceed with the `time` attribute used as\\na priority for the queue.\\n\\nWhereas with the _A\\\\*_, I have chosen to use both time and Manhattan distance\\nthat promotes vertices closer to the exit **and** with a minimum time taken.\\n\\n:::\\n\\nCost function is, of course, a closure :wink:\\n\\n```rust\\nlet cost = |p: Position| p.z() as usize + exit.y().abs_diff(p.y()) + exit.x().abs_diff(p.x());\\n```\\n\\nAnd also for checking the possible moves from the current vertex, I have\\nimplemented, yet another, closure that yields an iterator with the next moves:\\n\\n```rust\\nlet next_positions = |p| {\\n [(0, 0, 1), (0, -1, 1), (0, 1, 1), (-1, 0, 1), (1, 0, 1)]\\n .iter()\\n .filter_map(move |&(x, y, t)| {\\n let next_p = p + Vector3D::new(x, y, t);\\n\\n if basin[next_p] == \'.\' {\\n Some(next_p)\\n } else {\\n None\\n }\\n })\\n};\\n```\\n\\n#### Min-heap\\n\\nIn this case I had a need to use the priority queue taking the elements with the\\nlowest cost as the prioritized ones. Rust only offers you the [`BinaryHeap`] and\\nthat is a max-heap. One of the ways how to achieve a min-heap is to put the\\nelements in wrapped in a [`Reverse`] (as is even showed in the linked [docs of\\nthe `BinaryHeap`]). However the wrapping affects the type of the heap and also\\npopping the most prioritized elements yields values wrapped in the `Reverse`.\\n\\nFor this purpose I have just taken the max-heap and wrapped it as a whole in a\\nseparate structure providing just the desired methods:\\n\\n```rust\\nuse std::cmp::{Ord, Reverse};\\nuse std::collections::BinaryHeap;\\n\\npub struct MinHeap<T> {\\n heap: BinaryHeap<Reverse<T>>,\\n}\\n\\nimpl<T: Ord> MinHeap<T> {\\n pub fn new() -> MinHeap<T> {\\n MinHeap {\\n heap: BinaryHeap::new(),\\n }\\n }\\n\\n pub fn push(&mut self, item: T) {\\n self.heap.push(Reverse(item))\\n }\\n\\n pub fn pop(&mut self) -> Option<T> {\\n self.heap.pop().map(|Reverse(x)| x)\\n }\\n}\\n\\nimpl<T: Ord> Default for MinHeap<T> {\\n fn default() -> Self {\\n Self::new()\\n }\\n}\\n```\\n\\nRest is just the algorithm implementation which is not that interesting.\\n\\n## [Day 25: Full of Hot Air](https://adventofcode.com/2022/day/25)\\n\\n:::info tl;dr\\n\\nPlaying around with a numbers in a _special_ base.\\n\\n:::\\n\\nGetting flashbacks to the _IB111 Foundations of Programming_\u2026 Very nice \u201cproblem\u201d\\nwith a rather easy solution, as the last day always seems to be.\\n\\n### Solution\\n\\nImplementing 2 functions, converting from the _SNAFU base_ and back to the _SNAFU_\\n_base_ representation. Let\'s do a bit more though! I have implemented two functions:\\n\\n- `from_snafu`\\n- `to_snafu`\\n\\nNow it is apparent that all I do is number to string and string to number. Hmm\u2026\\nthat sounds familiar, doesn\'t it? Let\'s introduce a structure for the SNAFU numbers\\nand implement the traits that we need.\\n\\nLet\'s start with a structure:\\n\\n```rust\\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]\\nstruct SNAFU {\\n value: i64,\\n}\\n```\\n\\n#### Converting from `&str`\\n\\nWe will start by implementing the `FromStr` trait that will help us parse our input.\\nThis is rather simple, I can just take the `from_snafu` function, copy-paste it\\ninto the `from_str` method and the number I get will be wrapped in `Result` and\\n`SNAFU` structure.\\n\\n#### Converting to `String`\\n\\nThis is more fun. In some cases you need to implement only one trait and others\\nare automatically implemented using that one trait. In our case, if you look in\\nthe documentation, you can see that `ToString` trait is automatically implemented\\nfor any type that implements `Display` trait.\\n\\nLet\'s implement the `Display` trait then. We should be able to use the `to_snafu`\\nfunction and just take the `self.value` from the `SNAFU` structure.\\n\\nAnd for the convenience of tests, we can also implement a rather simple `From<i64>`\\ntrait for the `SNAFU`.\\n\\n#### Adjusting the code\\n\\nAfter those changes we need to adjust the code and tests.\\n\\nParsing of the input is very easy, before we have used the lines, now we parse\\neverything:\\n\\n```diff\\n fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {\\n- file_to_lines(pathname)\\n+ file_to_structs(pathname)\\n }\\n```\\n\\nPart 1 needs to be adjusted a bit too:\\n\\n```diff\\n fn part_1(input: &Input) -> Output {\\n- to_snafu(input.iter().map(|s| from_snafu(s)).sum())\\n+ SNAFU::from(input.iter().map(|s| s.value).sum::<i64>()).to_string()\\n }\\n```\\n\\nYou can also see that it simplifies the meaning a bit and it is more explicit than\\nthe previous versions.\\n\\nAnd for the tests:\\n\\n```diff\\n #[test]\\n fn test_from() {\\n- for (n, s) in EXAMPLES.iter() {\\n- assert_eq!(from_snafu(s), *n);\\n+ for (&n, s) in EXAMPLES.iter() {\\n+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);\\n }\\n }\\n\\n #[test]\\n fn test_to() {\\n- for (n, s) in EXAMPLES.iter() {\\n- assert_eq!(to_snafu(*n), s.to_string());\\n+ for (&n, s) in EXAMPLES.iter() {\\n+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());\\n }\\n```\\n\\n## Summary\\n\\nLet\'s wrap the whole thing up! Keeping in mind both AoC and the Rust\u2026\\n\\n![Finished advent calendar :smile:](/img/blog/aoc-2022/04-week-4/calendar.png)\\n\\n### Advent of Code\\n\\nThis year was quite fun, even though most of the solutions and posts came in\\nlater on (_cough_ in \'23 _cough_). Day 22 was the most obnoxious one\u2026 And also\\nit feels like I used priority queues and tree data structures **a lot** :eyes:\\n\\n### with Rust\\n\\nI must admit that a lot of compiler warnings and errors were very useful. Even\\nthough I still found some instances where they didn\'t help at all or cause even\\nworse issues than I had. Compilation times have been addressed with the caching.\\n\\nBuilding my first tree data structure in Rust has been a very \u201cinteresting\u201d\\njourney. Being able to write a more generic BFS algorithm that allows you to not\\nduplicate code while still mantaining the desired functionality contributes to\\na very readable code.\\n\\nI am definitely much more aware of the basic things that bloated Python is\\nmissing, yet Rust has them\u2026\\n\\nUsing explicit types and writing down placeholder functions with `todo!()`\\nmacros is very pleasant, since it allows you to easily navigate the type system\\nduring the development when you don\'t even need to be sure how are you going to\\nput the smaller pieces together.\\n\\nI have used a plethora of traits and also implemented some of them to either be\\nidiomatic, or exploit the syntactic sugar they offer. Deriving the default trait\\nimplementation is also very helpful in a lot of cases, e.g. debugging output,\\ncopying, equality comparison, etc.\\n\\nI confess to touching more \u201ccursed\u201d parts of the Rust, such as macros to\\ndeclutter the copy-paste for tests or writing my own structures that need to\\ncarry a lifetime for their own fields.\\n\\ntl;dr Relatively pleasant language until you hit brick wall :wink:\\n\\n---\\n\\nSee you next year! Maybe in Rust, maybe not :upside_down_face:\\n\\n[_advent of code_]: https://adventofcode.com\\n[_a\\\\*_]: https://en.wikipedia.org/wiki/A*_search_algorithm\\n[`binaryheap`]: https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html\\n[`reverse`]: https://doc.rust-lang.org/std/cmp/struct.Reverse.html\\n[docs of the `binaryheap`]: https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html#min-heap"},{"id":"aoc-2022/3rd-week","metadata":{"permalink":"/blog/aoc-2022/3rd-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/03-week-3.md","source":"@site/blog/aoc-2022/03-week-3.md","title":"3rd week of Advent of Code \'22 in Rust","description":"Surviving third week in Rust.","date":"2023-07-06T21:00:00.000Z","formattedDate":"July 6, 2023","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":11.57,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"3rd week of Advent of Code \'22 in Rust","description":"Surviving third week in Rust.","date":"2023-07-06T21:00","slug":"aoc-2022/3rd-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"4th week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/4th-week"},"nextItem":{"title":"Sort the matrix diagonally","permalink":"/blog/leetcode/sort-diagonally"}},"content":"Let\'s go through the third week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n## [Day 15: Beacon Exclusion Zone](https://adventofcode.com/2022/day/15)\\n\\n:::info tl;dr\\n\\nTriangulating a distress beacon based on the information from the sensors.\\n\\n:::\\n\\n### Solution\\n\\nRelatively easy thing to implement, no major Rust issues hit.\\n\\n## [Day 16: Proboscidea Volcanium](https://adventofcode.com/2022/day/16)\\n\\n:::info tl;dr\\n\\nFinding a max flow in a graph given some time constraints.\\n\\n:::\\n\\n### Solution\\n\\nI have used some interesting things to implement this and make it easier for me.\\n\\n#### Indexing in graph\\n\\nI have come across a situation where I needed to keep more information regarding\\nthe graph\u2026 In that case you can, of course, create a structure and keep it in,\\nbut once you have multiple members in the structure it gets harder to work with\\nsince you need to address the fields in the structure. When you work with graph,\\nyou frequently need to access the vertices and in this case it felt a lot easier\\nto implement the indexing in a graph, rather than explicitly access the\\nunderlying data structure.\\n\\nHere you can see a rather short snippet from the solution that allows you to\\n\u201cindex\u201d the graph:\\n\\n```rust\\nimpl Index<&str> for Graph {\\n type Output = Vertex;\\n\\n fn index(&self, index: &str) -> &Self::Output {\\n &self.g[index]\\n }\\n}\\n```\\n\\n#### Cartesian product\\n\\nDuring the implementation I had to utilize Floyd-Warshall algorithm for finding\\nthe shortest path between pairs of vertices and utilized the `iproduct!` macro\\nfrom the [`itertools`]. It is a very useful higher-order function that allows\\nyou to keep the nesting of the loops at a minimum level while still maintaining\\nthe same functionality.\\n\\n#### \u201cImplementing\u201d an iterator\\n\\nFor the second part, you get to split the work between 2 actors. That way you\\ncan achieve higher efficiency of the whole process that you\'re planning, but it\\nalso makes it harder to evaluate algorithmically, since you need to check the\\ndifferent ways the work can be split.\\n\\nBeing affected by _functional programming brain damage_:tm:, I have chosen to\\ndo this part by function that returns an iterator over the possible ways:\\n\\n```rust\\nfn pairings(\\n valves: &BTreeSet<String>,\\n) -> impl Iterator<Item = (BTreeSet<String>, BTreeSet<String>)> + \'_ {\\n let mapping = valves.iter().collect_vec();\\n\\n let max_mask = 1 << (valves.len() - 1);\\n\\n (0..max_mask).map(move |mask| {\\n let mut elephant = BTreeSet::new();\\n let mut human = BTreeSet::new();\\n\\n for (i, &v) in mapping.iter().enumerate() {\\n if (mask & (1 << i)) == 0 {\\n human.insert(v.clone());\\n } else {\\n elephant.insert(v.clone());\\n }\\n }\\n\\n (human, elephant)\\n })\\n}\\n```\\n\\n## [Day 17: Pyroclastic Flow](https://adventofcode.com/2022/day/17)\\n\\n:::info tl;dr\\n\\nSimulating an autonomous Tetris where pieces get affected by a series of jets of\\nhot gas.\\n\\n:::\\n\\n### Solution\\n\\nSimilarly to the previous day I have created some iterators :smile:\\n\\n#### Collision detection\\n\\nOnce you need to check for collisions it is very helpful to be able to just\\niterate through the positions that can actually collide with the wall or other\\npiece.\\n\\nTo get the desired behaviour, you can just compose few smaller functions:\\n\\n```rust\\nfn occupied(shape: &[Vec<char>]) -> impl Iterator<Item = Position> + \'_ {\\n shape.iter().enumerate().flat_map(|(y, row)| {\\n row.iter().enumerate().filter_map(move |(x, c)| {\\n if c == &\'#\' {\\n Some(Vector2D::new(x as isize, y as isize))\\n } else {\\n None\\n }\\n })\\n })\\n}\\n```\\n\\nIn the end, we get relative positions which we can adjust later when given the\\nspecific positions from iterator. You can see some interesting parts in this:\\n\\n- `.enumerate()` allows us to get both the indices (coordinates) and the line\\n or, later on, the character itself,\\n- `.flat_map()` flattens the iterator, i.e. when we return another iterator,\\n they just get chained instead of iterating over iterators (which sounds pretty\\n disturbing, doesn\'t it?),\\n- and finally `.filter_map()` which is pretty similar to the \u201cbasic\u201d `.map()`\\n with a one, key, difference that it expects the items of an iterator to be\\n mapped to an `Option<T>` from which it ignores nothing (as in `None` :wink:)\\n and also unwraps the values from `Some(\u2026)`.\\n\\n#### Infinite iterator\\n\\nIn the solution we cycle through both Tetris-like shapes that fall down and the\\njets that move our pieces around. Initially I have implemented my own infinite\\niterator that just yields the indices. It is a very simple, yet powerful, piece\\nof code:\\n\\n```rust\\nstruct InfiniteIndex {\\n size: usize,\\n i: usize,\\n}\\n\\nimpl InfiniteIndex {\\n fn new(size: usize) -> InfiniteIndex {\\n InfiniteIndex { size, i: size - 1 }\\n }\\n}\\n\\nimpl Iterator for InfiniteIndex {\\n type Item = usize;\\n\\n fn next(&mut self) -> Option<Self::Item> {\\n self.i = (self.i + 1) % self.size;\\n Some(self.i)\\n }\\n}\\n```\\n\\nHowever when I\'m looking at the code now, it doesn\'t really make much sense\u2026\\nGuess what, we can use a built-in function that is implemented on iterators for\\nthat! The function is called `.cycle()`\\n\\nOn the other hand, I am not going to switch to that function, since it would\\nintroduce an another myriad of issues caused by the fact that I create iterators\\nright away in the constructor of my structure and the iterators would borrow\\nboth the jets and shapes which would introduce a lifetime dependency into the\\nstructure.\\n\\n## [Day 18: Boiling Boulders](https://adventofcode.com/2022/day/18)\\n\\n:::info tl;dr\\n\\nLet\'s compute a surface area of some obsidian approximated via coordinates of\\ncubes.\\n\\n:::\\n\\n### Solution\\n\\nThis day is kinda interesting, because it shows how easily you can complicate the\\nproblem and also how much can you screw yourself over with the optimization and\\n\u201csmart\u201d approach.\\n\\nFor the first part you need to find the surface area of an obsidian that is\\napproximated by cubes. Now, that is a very easy thing to do, just keep the track\\nof already added cubes, and check if the newly added cube touches any face of any\\nother cube. Simple, and with a `BTreeSet` relatively efficient way to do it.\\n\\nHowever the second part lets you on a secret that there may be some surface area\\nfrom the \u201cinside\u201d too and you want to know only the one from the outside of the\\nobsidian. I have seen some solutions later, but if you check your data, you might\\nnotice that the bounding box of all the cubes isn\'t that big at all. Therefore I\\nchose to pre-construct the box beforehand, fill in the cubes and then just run a\\nBFS turning all the lava on the outside into the air. Now you just need to check\\ncubes and count how many of their faces touch the air.\\n\\n## [Day 19: Not Enough Minerals](https://adventofcode.com/2022/day/19)\\n\\n:::info tl;dr\\n\\nFinding out the best strategy for building robots to collect geodes.\\n\\n:::\\n\\n### Solution\\n\\nNot much interesting stuff to mention apart from the suggestion to never believe\\nthat the default implementation given by `derive` macro is what you want, it\\ndoesn\'t have to be. :smile:\\n\\n## [Day 20: Grove Positioning System](https://adventofcode.com/2022/day/20)\\n\\n:::info tl;dr\\n\\nShuffling around the _circular linked list_ to find the coordinates.\\n\\n:::\\n\\nNow, small rant for this day is in place. They\'ve never mentioned that coordinates\\ncan repeat and therefore the values are non-unique. This is something that did\\nnot happen in the given sample, but was present in the user input. It took \xbba lot\xab\\nto realize that this is the issue.\\n\\n### Solution\\n\\nI have tried implementing a circular linked list for this\u2026 and I have failed\\nmiserably. To be fair, I still have no clue why. It was \u201cfun\u201d to play around with\\nthe `Rc<RefCell<T>>`. In the end I failed on _wrong answer_. I have also encountered\\na rather interesting issue with `.borrow_mut()` method being used on `Rc<RefCell<T>>`.\\n\\n#### `.borrow_mut()`\\n\\nConsider the following snippet of the code (taken from the documentation):\\n\\n```rust\\nuse std::cell::{RefCell, RefMut};\\nuse std::collections::HashMap;\\nuse std::rc::Rc;\\n// use std::borrow::BorrowMut;\\n\\nfn main() {\\n let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));\\n // Create a new block to limit the scope of the dynamic borrow\\n {\\n let mut map: RefMut<_> = shared_map.borrow_mut();\\n map.insert(\\"africa\\", 92388);\\n map.insert(\\"kyoto\\", 11837);\\n map.insert(\\"piccadilly\\", 11826);\\n map.insert(\\"marbles\\", 38);\\n }\\n\\n // Note that if we had not let the previous borrow of the cache fall out\\n // of scope then the subsequent borrow would cause a dynamic thread panic.\\n // This is the major hazard of using `RefCell`.\\n let total: i32 = shared_map.borrow().values().sum();\\n println!(\\"{total}\\");\\n}\\n```\\n\\nWe allocate a hash map on the heap and then in the inner block, we borrow it as\\na mutable reference, so that we can use it.\\n\\n:::note\\n\\nIt is a very primitive example for `Rc<RefCell<T>>` and mutable borrow.\\n\\n:::\\n\\nIf you uncomment the 4th line with `use std::borrow::BorrowMut;`, you cannot\\ncompile the code anymore, because of\\n\\n```\\n Compiling playground v0.0.1 (/playground)\\nerror[E0308]: mismatched types\\n --\x3e src/main.rs:10:34\\n |\\n10 | let mut map: RefMut<_> = shared_map.borrow_mut();\\n | --------- ^^^^^^^^^^^^^^^^^^^^^^^ expected struct `RefMut`, found mutable reference\\n | |\\n | expected due to this\\n |\\n = note: expected struct `RefMut<\'_, _>`\\n found mutable reference `&mut Rc<RefCell<HashMap<_, _>>>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:11:13\\n |\\n11 | map.insert(\\"africa\\", 92388);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:12:13\\n |\\n12 | map.insert(\\"kyoto\\", 11837);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:13:13\\n |\\n13 | map.insert(\\"piccadilly\\", 11826);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:14:13\\n |\\n14 | map.insert(\\"marbles\\", 38);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nSome errors have detailed explanations: E0308, E0599.\\nFor more information about an error, try `rustc --explain E0308`.\\nerror: could not compile `playground` due to 5 previous errors\\n```\\n\\nIt might seem **a bit** ridiculous. However, I got to a point where the compiler\\nsuggested `use std::borrow::BorrowMut;` and it resulted in breaking parts of the\\ncode that worked previously. I think it may be a good idea to go over what is\\nhappening here.\\n\\n##### `.borrow_mut()` on `Rc<RefCell<T>>`\\n\\nLet\'s consider a variable `x` of type `Rc<RefCell<T>>`. What happens when you\\ncall `.borrow_mut()` on it? We can look at the `Rc` type, and\u2026 hang on! There is\\nneither `.borrow_mut()` method or `BorrowMut` trait implemented. How can we do it\\nthen?\\n\\nLet\'s go further and we can see that `RefCell<T>` implements a `.borrow_mut()`\\nmethod. OK, but how can we call it on the `Rc<T>`? Easily! `Rc<T>` implements\\n`Deref<T>` and therefore you can call methods on `Rc<T>` objects as if they were\\n`T` objects. If we read on _`Deref` coercion_, we can see the following:\\n\\n> If `T` implements `Deref<Target = U>`, \u2026:\\n>\\n> - \u2026\\n> - `T` implicitly implements all the (immutable) methods of the type `U`.\\n\\nWhat is the requirement for the `.borrow_mut()` on `RefCell<T>`? Well, it needs\\n`&self`, so the `Deref` implements the `.borrow_mut()` for the `Rc<RefCell<T>>`.\\n\\n##### `BorrowMut` trait\\n\\nI have not been able to find a lot on this trait. My guess is that it provides a\\nmethod instead of a syntactic sugar (`&mut x`) for the mutable borrow. And also\\nit provides default implementations for the types:\\n\\n```rust\\nimpl BorrowMut<str> for String\\n\\nimpl<T> BorrowMut<T> for &mut T\\nwhere\\n T: ?Sized,\\n\\nimpl<T> BorrowMut<T> for T\\nwhere\\n T: ?Sized,\\n\\nimpl<T, A> BorrowMut<[T]> for Vec<T, A>\\nwhere\\n A: Allocator,\\n\\nimpl<T, A> BorrowMut<T> for Box<T, A>\\nwhere\\n A: Allocator,\\n T: ?Sized,\\n\\nimpl<T, const N: usize> BorrowMut<[T]> for [T; N]\\n```\\n\\n##### Conflict\\n\\nNow the question is why did it break the code\u2026 My first take was that the type\\n`Rc<RefCell<T>>` has some _specialized_ implementation of the `.borrow_mut()` and\\nthe `use` overrides it with the default, which is true **in a sense**. However\\nthere is no _specialized_ implementation. Let\'s have a look at the trait and the\\ntype signature on the `RefCell<T>`:\\n\\n```rust\\n// trait\\npub trait BorrowMut<Borrowed>: Borrow<Borrowed>\\nwhere\\n Borrowed: ?Sized,\\n{\\n fn borrow_mut(&mut self) -> &mut Borrowed;\\n}\\n\\n// \u2039RefCell<T>.borrow_mut()\u203a type signature\\npub fn borrow_mut(&self) -> RefMut<\'_, T>\\n```\\n\\nI think that we can definitely agree on the fact that `RefMut<\'_, T>` is not the\\n`RefCell<T>`.\\n\\n**In my opinion**, `RefCell<T>` implements a **separate** `.borrow_mut()` rather\\nthan implementing the interface, because it **cannot** satisfy the type requirements\\nof the trait.\\n\\n:::warning[caution]\\n\\nI wonder how are we expected to deal with this conflict, if and when, we need\\nboth the `.borrow_mut()` of the trait and `.borrow_mut()` of the `RefCell<T>`.\\n\\n:::\\n\\n:::tip Fun fact\\n\\nI was suggested by the compiler to do `use std::borrow::BorrowMut;` and break the\\ncode.\\n\\nSo much for the _almighty_ and _helpful_ compiler\u2026\\n\\n:::\\n\\n## [Day 21: Monkey Math](https://adventofcode.com/2022/day/21)\\n\\n:::info tl;dr\\n\\nComputing an expression tree and then also finding ideal value for a node.\\n\\n:::\\n\\n### Solution\\n\\nRelatively simple, until you get to the 2nd part where you start to practice\\na lot of the copy-paste. I have managed to sneak some perverted stuff in there\\nthough :) Let\'s go through the details.\\n\\n#### `Default` trait\\n\\nFor the first time and twice I had a need to have a default value for my types,\\nenumerations in this case. Rust offers a very nice trait[^1] that is described\\nas:\\n\\n> A trait for giving a type a useful default value.\\n\\nI guess it sums it up nicely. The more interesting part about this is the fact\\nthat you can use the _macro machinery_ to save yourself some typing. If you have\\nenumeration of which the default value doesn\'t bear any parameter, you can just\\ndo[^2]:\\n\\n```rust\\n#[derive(Default)]\\nenum Color {\\n #[default]\\n White,\\n Gray,\\n Black,\\n}\\n```\\n\\n#### Abusing negation\\n\\nIf you want to use a _unary minus_ operator on your own type, you can implement\\na `Neg` trait[^3]. I was dealing with a binary tree and needed a way how to look\\nat the other side, so I have just implemented the negation for flipping between\\nleft and right :smile:\\n\\n[^1]: [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) docs\\n[^2]: Pardon my example from the graph algorithms ;)\\n[^3]: [`Neg`](https://doc.rust-lang.org/std/ops/trait.Neg.html) docs\\n\\n[_advent of code_]: https://adventofcode.com\\n[`itertools`]: https://crates.io/crates/itertools\\n[this reddit post and the comment]: https://www.reddit.com/r/adventofcode/comments/zb98pn/comment/iyq0ono"},{"id":"leetcode/sort-diagonally","metadata":{"permalink":"/blog/leetcode/sort-diagonally","editUrl":"https://github.com/mfocko/blog/tree/main/blog/leetcode/sort-matrix-diagonally.md","source":"@site/blog/leetcode/sort-matrix-diagonally.md","title":"Sort the matrix diagonally","description":"Compiler assisted development.","date":"2023-03-04T23:15:00.000Z","formattedDate":"March 4, 2023","tags":[{"label":"cpp","permalink":"/blog/tags/cpp"},{"label":"leetcode","permalink":"/blog/tags/leetcode"},{"label":"iterators","permalink":"/blog/tags/iterators"}],"readingTime":16.99,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"Sort the matrix diagonally","description":"Compiler assisted development.","date":"2023-03-04T23:15","slug":"leetcode/sort-diagonally","authors":"mf","tags":["cpp","leetcode","iterators"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"3rd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/3rd-week"},"nextItem":{"title":"2nd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/2nd-week"}},"content":"Let\'s try to solve one of the LeetCode challenges in easy and hard mode at the\\nsame time.\\n\\n\x3c!--truncate--\x3e\\n\\n- Link to the problem: https://leetcode.com/problems/sort-the-matrix-diagonally/\\n\\n## Problem description\\n\\nA **matrix diagonal** is a diagonal line of cells starting from some cell in\\neither the topmost row or leftmost column and going in the bottom-right direction\\nuntil reaching the matrix\'s end. For example, the **matrix diagonal** starting\\nfrom `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`,\\n`mat[3][1]`, and `mat[4][2]`.\\n\\nGiven an `m x n` matrix `mat` of integers, sort each matrix diagonal in ascending\\norder and return the resulting matrix.\\n\\n### Example\\n\\n![Image describing the problem](https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png)\\n\\n## Skeleton and initial adjustments\\n\\nWe are given the following skeleton for the C++ and the given challenge:\\n\\n```cpp\\nclass Solution {\\npublic:\\n vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {\\n\\n }\\n};\\n```\\n\\nThe task is to sort the passed matrix diagonally and then return it. First of all,\\nI don\'t like to solve this in a web browser, so we\'ll need to adjust it accordingly\\nfor running it locally. We\'ll start by including the `vector` header and using\\nfully-qualified namespaces[^1] and also adding few tests:\\n\\n```cpp\\n#include <cassert>\\n#include <vector>\\n\\nusing matrix = std::vector<std::vector<int>>;\\n\\nclass Solution {\\npublic:\\n matrix diagonalSort(matrix& mat)\\n {\\n }\\n};\\n\\nstatic void test_case_1()\\n{\\n // Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\\n // Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\\n\\n Solution s;\\n assert((s.diagonalSort(std::vector { std::vector { 3, 3, 1, 1 },\\n std::vector { 2, 2, 1, 2 },\\n std::vector { 1, 1, 1, 2 } })\\n == std::vector { std::vector { 1, 1, 1, 1 },\\n std::vector { 1, 2, 2, 2 },\\n std::vector { 1, 2, 3, 3 } }));\\n}\\n\\nstatic void test_case_2()\\n{\\n // Input: mat =\\n // [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\\n // Output:\\n // [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]\\n\\n Solution s;\\n assert((s.diagonalSort(std::vector { std::vector { 11, 25, 66, 1, 69, 7 },\\n std::vector { 23, 55, 17, 45, 15, 52 },\\n std::vector { 75, 31, 36, 44, 58, 8 },\\n std::vector { 22, 27, 33, 25, 68, 4 },\\n std::vector { 84, 28, 14, 11, 5, 50 } })\\n == std::vector { std::vector { 5, 17, 4, 1, 52, 7 },\\n std::vector { 11, 11, 25, 45, 8, 69 },\\n std::vector { 14, 23, 25, 44, 58, 15 },\\n std::vector { 22, 27, 31, 36, 50, 66 },\\n std::vector { 84, 28, 75, 33, 55, 68 } }));\\n}\\n\\nint main()\\n{\\n test_case_1();\\n test_case_2();\\n\\n return 0;\\n}\\n```\\n\\nWe need to return the matrix, but we\'re given a reference to the input matrix. We\\ncan easily abuse the C++ here and just switch the reference to value, this way\\nthe matrix will be copied when passed to the function, we can sort the copy and\\njust return it back. And we also get yelled by the compiler for the fact that the\\nmethod doesn\'t return anything yet, so to make it \u201cshut up\u201d we will just return\\nthe input for now:\\n\\n```diff\\n- matrix diagonalSort(matrix& mat)\\n+ matrix diagonalSort(matrix mat)\\n {\\n+ return mat;\\n }\\n```\\n\\nNow, we get the copy and we\'re good to go.\\n\\n## Na\xefve solution\\n\\nAs you may know, C++ offers a plethora of functions that can be used to your\\nadvantage, given that you know how to \u201cbend\u201d the data structures accordingly.\\n\\nWhat does that mean for us? Well, we have an `std::sort`, we can use it, right?\\nLet\'s have a look at it:\\n\\n```cpp\\ntemplate< class RandomIt >\\nvoid sort( RandomIt first, RandomIt last );\\n```\\n\\nThis overload is more than we need. What does it do? It just sorts the elements\\nin the range `[first, last)` using `operator<` on them. We can\'t sort the whole\\nmatrix using this, but\u2026 we can sort just \xbbone\xab diagonal without doing much work\\non our end.\\n\\nWhat is the `RandomIt` type though? If we look more into the documentation, we\\ncan easily find the requirements for it and also learn that it\'s a _random access_\\n_iterator_ and allows swapping its values at the same time.\\n\\n:::tip Random access iterator\\n\\nWhat is the _random access iterator_ though? We can find it in a documentation\\nand see the following description:\\n\\n> A **LegacyRandomAccessIterator** is a [LegacyBidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator)\\n> that can be moved to point to any element in constant time.\\n\\nAfter that we can see all the requirements for it being listed. I don\'t feel like\\nreading them right now, so we will just use it and see where the compilation blows\\nup, i.e. \u201c_compiler-assisted development_\u201d[^2] if you will ;)\\n\\n:::\\n\\nNow we know that we can use `std::sort` to sort the diagonal itself, but we also\\nneed to get the diagonals somehow. I\'m rather lazy, so I\'ll just delegate it to\\nsomeone else[^3]. And that way we get\\n\\n```cpp\\nmatrix diagonalSort(matrix mat)\\n{\\n // we iterate over the diagonals\\n for (auto d : diagonals(mat)) {\\n // and we sort each diagonal\\n std::sort(d.begin(), d.end());\\n }\\n\\n // we take the matrix by copy, so we can sort in-situ and return the copy\\n // that we sorted\\n return mat;\\n}\\n```\\n\\nThis solution looks very simple, doesn\'t it? Well, cause it is.\\nLet\'s try compiling it:\\n\\n```\\nmatrix-sort.cpp:11:23: error: use of undeclared identifier \'diagonals\' [clang-diagnostic-error]\\n for (auto d : diagonals(mat)) {\\n ^\\nFound compiler error(s).\\nmake: *** [makefile:14: tidy] Error 1\\n```\\n\\nOK, seems about right. We haven\'t implemented the `diagonals` yet. And based on\\nwhat we\'ve written so far, we need a function or a class `diagonals` that will\\ngive us the diagonals we need.\\n\\n## Implementing the `diagonals`\\n\\nCool, so we need the function that will let us go through each and every diagonal\\nin our matrix. We use the _for-range_ loop, so whatever we get back from the\\n`diagonals` must support `.begin()` and `.end()`. Since I am a masochist, we will\\ndo such functionality for a matrix of any type, not just the `int` from the challenge.\\n\\nAs I said, we need to be able to\\n\\n- construct the object\\n- get the beginning\\n- get the end (the \u201csentinel\u201d)\\n\\n```cpp\\ntemplate <typename T>\\nclass diagonals {\\n using matrix_t = std::vector<std::vector<T>>;\\n\\n matrix_t& _matrix;\\n\\npublic:\\n diagonals(matrix_t& m)\\n : _matrix(m)\\n {\\n }\\n diagonals_iter begin()\\n {\\n /* TODO */\\n }\\n diagonals_iter end()\\n {\\n /* TODO */\\n }\\n};\\n```\\n\\nNow we have a `diagonals` that we can use to go through the diagonals. We haven\'t\\nimplemented the core of it yet. Let\'s go through what we have for now.\\n\\nWe have a templated class with templated `T` that is used as a placeholder for any\\ntype we would store in the matrix. Because I\'m lazy, I have defined the `matrix_t`\\ntype that is a \u201cshortcut\u201d for `std::vector<std::vector<T>>`, so I don\'t have to\\ntype it out all the time. Of course, we need to store the matrix, we are given,\\nas a private attribute. And then just have the constructor and the 2 methods we\\nneed for the _for-range_.\\n\\n### Iterating over diagonals\\n\\nNow that we have an object that will allow us to iterate through the diagonals,\\nwe need to implement the iterating itself. We need to go through all of them, so\\nwe have multiple options how to do so. I have decided to start from the \u201cmain\u201d\\ndiagonal that starts at `(0, 0)` index and then proceed with the diagonals starting\\nin the first row, followed by the rest of the diagonals in the first column.\\n\\nWe need to be able to tell that we\'ve iterated through all of them, and also we\\nneed to know which diagonal is next. For that purpose we will pass the indices\\nof the first cell on the diagonal. That way we can always tell how to move forward.\\n\\nWe will start by updating the `begin` and `end` to reflect our choice accordingly.\\n\\n```cpp\\ndiagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; }\\ndiagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; }\\n```\\n\\nFor the `begin` we return the first diagonal that starts at `(0, 0)`. And because\\nwe have decided to do the diagonals in the first column at the end, the first\\ndiagonal that is not a valid one is the one at `(0, height)`. Apart from the\\nindices, we also need to pass reference to the matrix itself.\\n\\n:::note\\n\\nYou may have noticed that we also include the diagonals that have length 1,\\nspecifically the ones at `(0, height - 1)` and `(width - 1, 0)`. We are implementing\\nan iterator that **should not** care about the way it\'s being used. Therefore, we\\ndon\'t care about the fact they don\'t need to be sorted.\\n\\n:::\\n\\nCool, let\'s leave the iterator itself to someone else, right?[^4]\\n\\n### Implementing the iterator over diagonals\\n\\nWe can start with a simple skeleton based on the information that we pass from\\nthe `diagonals`. Also to utilize the `matrix_t` and also contain implementation\\ndetails hidden away, we will put this code into the `diagonals` class.\\n\\n```cpp\\nclass diagonals_iter {\\n matrix_t& m;\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n};\\n```\\n\\nIn this case we will be implementing a \u201csimple\u201d forward iterator, so we don\'t\\nneed to implement a lot. Notably it will be:\\n\\n- inequality operator (we need to know when we reach the end and have nothing to\\n iterate over)\\n- preincrementation operator (we need to be able to move around the iterable)\\n- dereference operator (we need to be able to retrieve the objects we iterate\\n over)\\n\\n```cpp\\nclass diagonals_iter {\\n matrix_t& m;\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n bool operator!=(const diagonals_iter& rhs) const\\n {\\n // iterators are not equal if they reference different matrices, or\\n // their positions differ\\n return m != rhs.m || x != rhs.x || y != rhs.y;\\n }\\n\\n diagonals_iter& operator++()\\n {\\n if (y != 0) {\\n // iterating through diagonals down the first column\\n y++;\\n return *this;\\n }\\n\\n // iterating the diagonals along the first row\\n x++;\\n if (x == m.front().size()) {\\n // switching to diagonals in the first column\\n x = 0;\\n y++;\\n }\\n\\n return *this;\\n }\\n\\n diagonal<T> operator*() const { return diagonal { m, x, y }; }\\n};\\n```\\n\\nLet\'s go one-by-one. Inequality operator is rather simple, just compare iterator\'s\\nattributes field-by-field. If you think about it, checking inequality of two 2D\\nvectors may be a bit inefficient, therefore, we can swap around and check it as\\na last thing.\\n\\n```diff\\n- return m != rhs.m || x != rhs.x || y != rhs.y;\\n+ return x != rhs.x || y != rhs.y || m != rhs.m;\\n```\\n\\nPreincrementation is where the magic happens. If you have a better look, you can\\nsee two branches of this operation:\\n\\n1. When `y != 0` (we\'re iterating over the diagonals in the first column)\\n In this case, we just bump the row and we\'re done.\\n2. When `y == 0` (we\'re iterating over the diagonals in the first row)\\n In this case, we bump the column and check if we haven\'t gotten out of bounds,\\n i.e. the end of the first row. If we get out of the bounds, we\'re continuing\\n with the second diagonal in the first column.\\n\\nDereferencing the iterator must \u201cyield\u201d something. In our case it will be the\\ndiagonal that we want to sort. For sorting we need just the iterators that can\\nmove around said diagonal. The simplest thing, we can do, is to delegate it to\\nsomething else. In our case it will be a class called `diagonal`.\\n\\n## Implementing the `diagonal` itself\\n\\nAfter implementing the iterator over diagonals, we know that all we need to describe\\na diagonal is the matrix itself and the \u201cstart\u201d of the diagonal (row and column).\\nAnd we also know that the diagonal must provide some iterators for the `std::sort`\\nfunction. We can start with the following skeleton:\\n\\n```cpp\\ntemplate <typename T>\\nclass diagonal {\\n using matrix_t = std::vector<std::vector<T>>;\\n\\n matrix_t& matrix;\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n diagonal(matrix_t& matrix, std::size_t x, std::size_t y)\\n : matrix(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n diagonal_iter begin() const { return diagonal_iter { matrix, x, y }; }\\n\\n diagonal_iter end() const\\n {\\n auto max_x = matrix[y].size();\\n auto max_y = matrix.size();\\n\\n // we need to find the distance in which we get out of bounds (either in\\n // column or row)\\n auto steps = std::min(max_x - x, max_y - y);\\n\\n return diagonal_iter { matrix, x + steps, y + steps };\\n }\\n};\\n```\\n\\nInitialization is rather simple, we just \u201ckeep\u201d the stuff we get, `begin` is the\\nsimplest, we just delegate.\\n\\nIn case of the `end`, it gets more complicated. We need to know where is the \u201cend\u201d\\nof the diagonal. Since `end` should point to the first element \u201cafter\u201d the iterable,\\nwe know that it\'s the first position of the iterator where either `y` becomes\\n`matrix.size()` or `x` becomes `matrix[y].size()`. Also we are moving along diagonal,\\nduh, therefore we can deduce the first \u201cposition\u201d afterwards by minimal amount of\\nsteps to get out of the any column or row, hence `std::min(max_x - x, max_y - y)`.\\nFinal position is then computed simply by adding the steps to the beginning of\\nthe diagonal.\\n\\nNow we just need to finish the iterator for the diagonal itself and we\'re done.\\n\\n### Implementing `diagonal_iter`\\n\\nThis part is the hardest from all we need to do. It\'s because of the requirements\\nof the `std::sort` that requires us to implement a _random access iterator_. I have\\nbriefly described it above, and \u201cin a nutshell\u201d it means that we need to implement\\nan iterator that can move in constant time along the diagonal in any amount of\\nsteps.\\n\\nLet\'s go through all of the functionality that our iterator needs to support to\\nbe used in `std::sort`. We need the usual operations like:\\n\\n- equality/inequality\\n- incrementation\\n- dereferencing\\n\\nWe will also add all the types that our iterator uses with the category of the\\niterator, i.e. what interface it supports:\\n\\n```cpp\\nclass diagonal_iter {\\n // we need to keep reference to the matrix itself\\n matrix_t& m;\\n\\n // we need to be able to tell our current position\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n using difference_type = std::ptrdiff_t;\\n using value_type = T;\\n using pointer = T*;\\n using reference = T&;\\n using iterator_category = std::random_access_iterator_tag;\\n\\n diagonal_iter(matrix_t& matrix,\\n std::size_t x,\\n std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n bool operator==(const diagonal_iter& rhs) const\\n {\\n return x == rhs.x && y == rhs.y && m == rhs.m;\\n }\\n\\n diagonal_iter& operator++()\\n {\\n // we are moving along the diagonal, so we increment both \u2039x\u203a and \u2039y\u203a at\\n // the same time\\n x++;\\n y++;\\n return *this;\\n }\\n\\n reference operator*() const { return m[y][x]; }\\n};\\n```\\n\\nThis is pretty similar to the previous iterator, but now we need to implement the\\nremaining requirements of the _random access iterator_. Let\'s see what those are:\\n\\n- decrementation - cause we need to be able to move backwards too, since _random _\\n _access iterator_ extends the interface of _bidirectional iterator_\\n- moving the iterator in either direction by steps given as an integer\\n- being able to tell the distance between two iterators\\n- define an ordering on the iterators\\n\\nLet\'s fill them in:\\n\\n```cpp\\nclass diagonal_iter {\\n // we need to keep reference to the matrix itself\\n matrix_t& m;\\n\\n // we need to be able to tell our current position\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n using difference_type = std::ptrdiff_t;\\n using value_type = T;\\n using pointer = T*;\\n using reference = T&;\\n using iterator_category = std::random_access_iterator_tag;\\n\\n diagonal_iter(matrix_t& matrix,\\n std::size_t x,\\n std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n bool operator==(const diagonal_iter& rhs) const\\n {\\n return x == rhs.x && y == rhs.y && m == rhs.m;\\n }\\n\\n diagonal_iter& operator++()\\n {\\n // we are moving along the diagonal, so we increment both \u2039x\u203a and \u2039y\u203a at\\n // the same time\\n x++;\\n y++;\\n return *this;\\n }\\n\\n reference operator*() const { return m[y][x]; }\\n\\n // exactly opposite to the incrementation\\n diagonal_iter operator--()\\n {\\n x--;\\n y--;\\n return *this;\\n }\\n\\n // moving \u2039n\u203a steps back is same as calling decrementation \u2039n\u203a-times, so we\\n // can just return a new iterator and subtract \u2039n\u203a from both coordinates in\\n // the matrix\\n diagonal_iter operator-(difference_type n) const\\n {\\n return diagonal_iter { m, x - n, y - n };\\n }\\n\\n // here we assume that we are given two iterators on the same diagonal\\n difference_type operator-(const diagonal_iter& rhs) const\\n {\\n assert(m == rhs.m);\\n return x - rhs.x;\\n }\\n\\n // counterpart of moving \u2039n\u203a steps backwards\\n diagonal_iter operator+(difference_type n) const\\n {\\n return diagonal_iter { m, x + n, y + n };\\n }\\n\\n // we compare the coordinates, and also assume that those 2 iterators are\\n // lying on the same diagonal\\n bool operator<(const diagonal_iter& rhs) const\\n {\\n assert(m == rhs.m);\\n return x < rhs.x && y < rhs.y;\\n }\\n};\\n```\\n\\nAt this point we could probably try and compile it, right? If we do so, we will\\nget yelled at by a compiler for the following reasons:\\n\\n```\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type \'diagonal<int>::diagonal_iter\' cannot be assigned because its copy assignment operator is implicitly deleted [clang-diagnostic-error]\\n __last = __next;\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1817:11: note: in instantiation of function template specialization \'std::__unguarded_linear_insert<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Val_less_iter>\' requested here\\n std::__unguarded_linear_insert(__i,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1849:9: note: in instantiation of function template specialization \'std::__insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__insertion_sort(__first, __first + int(_S_threshold), __comp);\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1940:9: note: in instantiation of function template specialization \'std::__final_insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__final_insertion_sort(__first, __last, __comp);\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:4820:12: note: in instantiation of function template specialization \'std::__sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());\\n ^\\nmatrix-sort.cpp:161:18: note: in instantiation of function template specialization \'std::sort<diagonal<int>::diagonal_iter>\' requested here\\n std::sort(d.begin(), d.end());\\n ^\\nmatrix-sort.cpp:17:19: note: copy assignment operator of \'diagonal_iter\' is implicitly deleted because field \'m\' is of reference type \'diagonal<int>::matrix_t &\' (aka \'vector<std::vector<int>> &\')\\n matrix_t& m;\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1830:2: error: no matching function for call to \'__unguarded_linear_insert\' [clang-diagnostic-error]\\n std::__unguarded_linear_insert(__i,\\n ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1850:9: note: in instantiation of function template specialization \'std::__unguarded_insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__unguarded_insertion_sort(__first + int(_S_threshold), __last,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1940:9: note: in instantiation of function template specialization \'std::__final_insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__final_insertion_sort(__first, __last, __comp);\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:4820:12: note: in instantiation of function template specialization \'std::__sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());\\n ^\\nmatrix-sort.cpp:161:18: note: in instantiation of function template specialization \'std::sort<diagonal<int>::diagonal_iter>\' requested here\\n std::sort(d.begin(), d.end());\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1782:5: note: candidate template ignored: substitution failure [with _RandomAccessIterator = diagonal<int>::diagonal_iter, _Compare = __gnu_cxx::__ops::_Val_less_iter]\\n __unguarded_linear_insert(_RandomAccessIterator __last,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1923:11: error: object of type \'diagonal<int>::diagonal_iter\' cannot be assigned because its copy assignment operator is implicitly deleted [clang-diagnostic-error]\\n __last = __cut;\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1937:9: note: in instantiation of function template specialization \'std::__introsort_loop<diagonal<int>::diagonal_iter, long, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__introsort_loop(__first, __last,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:4820:12: note: in instantiation of function template specialization \'std::__sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());\\n ^\\nmatrix-sort.cpp:161:18: note: in instantiation of function template specialization \'std::sort<diagonal<int>::diagonal_iter>\' requested here\\n std::sort(d.begin(), d.end());\\n ^\\nmatrix-sort.cpp:17:19: note: copy assignment operator of \'diagonal_iter\' is implicitly deleted because field \'m\' is of reference type \'diagonal<int>::matrix_t &\' (aka \'vector<std::vector<int>> &\')\\n matrix_t& m;\\n ^\\n```\\n\\nThat\'s a lot of noise, isn\'t it? Let\'s focus on the important parts:\\n\\n```\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type \'diagonal<int>::diagonal_iter\' cannot be assigned because its copy assignment operator is implicitly deleted [clang-diagnostic-error]\\n\u2026\\nmatrix-sort.cpp:17:19: note: copy assignment operator of \'diagonal_iter\' is implicitly deleted because field \'m\' is of reference type \'diagonal<int>::matrix_t &\' (aka \'vector<std::vector<int>> &\')\\n matrix_t& m;\\n ^\\n```\\n\\nAh! We have a reference in our iterator, and this prevents us from having a copy\\nassignment operator (that is used \u201csomewhere\u201d in the sorting algorithm). Well\u2026\\nLet\'s just wrap it!\\n\\n```diff\\n# we need to keep a different type than reference\\n- matrix_t& m;\\n+ std::reference_wrapper<matrix_t> m;\\n\\n# in comparison we need to get the reference out of the wrapper first\\n- return x == rhs.x && y == rhs.y && m == rhs.m;\\n+ return x == rhs.x && y == rhs.y && m.get() == rhs.m.get();\\n\\n# same when we return a reference to the \u201ccell\u201d in the matrix\\n- reference operator*() const { return m[y][x]; }\\n+ reference operator*() const { return m.get()[y][x]; }\\n\\n# and finally in the assertions that we set for the \u201cdistance\u201d and \u201cless than\u201d\\n- assert(m == rhs.m);\\n+ assert(m.get() == rhs.m.get());\\n```\\n\\nWe\'re done now! We have written an iterator over diagonals for a 2D `vector`. You can have a look at the final result [here](pathname:///files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp).\\n\\n[^1]: just because I\'m used to it and don\'t care about your opinion ;)\\n[^2]: exercise at your own risk\\n[^3]: me in 5 minutes in fact, but don\'t make me scared\\n[^4]: me in the next section\u2026"},{"id":"aoc-2022/2nd-week","metadata":{"permalink":"/blog/aoc-2022/2nd-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/02-week-2.md","source":"@site/blog/aoc-2022/02-week-2.md","title":"2nd week of Advent of Code \'22 in Rust","description":"Surviving second week in Rust.","date":"2022-12-25T23:15:00.000Z","formattedDate":"December 25, 2022","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":20.875,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"2nd week of Advent of Code \'22 in Rust","description":"Surviving second week in Rust.","date":"2022-12-25T23:15","slug":"aoc-2022/2nd-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"Sort the matrix diagonally","permalink":"/blog/leetcode/sort-diagonally"},"nextItem":{"title":"1st week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/1st-week"}},"content":"Let\'s go through the second week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n## [Day 8: Treetop Tree House](https://adventofcode.com/2022/day/8)\\n\\n:::info tl;dr\\n\\nWe get a forest and we want to know how many trees are visible from the outside.\\nApart from that we want to find the best view.\\n\\n:::\\n\\nNothing interesting. We are moving around 2D map though. And indexing can get a\\nbit painful when doing so, let\'s refactor it a bit ;) During the preparation for\\nthe AoC, I have written `Vector2D` and now it\'s time to extend it with indexing\\nof `Vec` of `Vec`s. In my solution I was manipulating with indices in the following\\nway:\\n\\n- swapping them\\n- checking whether they are correct indices for the `Vec<Vec<T>>`\\n- indexing `Vec<Vec<T>>` with them\\n\\n:::warning[caution]\\n\\nI\'m getting familiar with Rust and starting to \u201cabuse\u201d it\u2026 While doing so, I\'m\\nalso uncovering some \u201cfeatures\u201d that I don\'t really like. Therefore I will mark\\nall of my rants with _thicc_ **\xab\u21af\xbb** mark and will try to \u201clock\u201d them into their\\nown \u201cbox of hell\u201d.\\n\\n:::\\n\\n#### Swapping indices\\n\\nRelatively simple implementation, just take the values, swap them and return new\\nvector.\\n\\n```rust\\nimpl<T: Copy> Vector2D<T> {\\n pub fn swap(&self) -> Self {\\n Self {\\n x: self.y,\\n y: self.x,\\n }\\n }\\n}\\n```\\n\\nPretty straight-forward implementation, but let\'s talk about the `T: Copy`. We\\nneed to use it, since we are returning a **new** vector, with swapped **values**.\\nIf we had values that cannot be copied, the only thing we could do, would be a\\nvector of references (and it would also introduce a lifetime, to which we\'ll get\\nlater on). This is pretty similar with the operations on sets from the first week.\\n\\n#### Indexing `Vec`\\n\\nI will start with the indexing, cause bound-checking is a bit more\u2026 complicated\\nthan I would like to.\\n\\n```rust\\npub fn index<\'a, T, U>(v: &\'a [Vec<U>], idx: &Vector2D<T>) -> &\'a U\\nwhere\\n usize: TryFrom<T>,\\n <usize as TryFrom<T>>::Error: Debug,\\n T: Copy,\\n{\\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\\n &v[y][x]\\n}\\n```\\n\\nLet\'s talk about this mess\u2026 Body of the function is probably the most easy part\\nand should not be hard to understand, we just take the `x` and `y` and convert\\nthem both to `usize` type that can be used later on for indexing.\\n\\nThe type signature of the function is where the fun is at :wink: We are trying\\nto convert unknown type to `usize`, so we must bound the `T` as a type that can\\nbe converted to `usize`, that\'s how we got `usize: TryFrom<T>` which basically\\nsays that `usize` must implement `TryFrom<T>` trait and therefore allows us to\\nconvert the indices to actual `usize` indices. Using `.unwrap()` also forces us\\nto bound the error that can occur when converting `T` into `usize`, that\'s how\\nwe get `<usize as TryFrom<T>>::Error: Debug` which loosely means\\n\\n> error during conversion of `T` into `usize` must implement `Debug`,\\n> i.e. can be printed in some way or other\\n\\n`T: Copy` is required by `.try_into()` which takes `T` by-value.\\n\\nAnd now we are left only with the first line of the definition.\\n\\n:::note\\n\\nSkilled Rustaceans might notice that this implementation is rather flaky and can\\nbreak in multiple places at once. I\'ll get back to it\u2026\\n\\n:::\\n\\nLet\'s split it in multiple parts:\\n\\n- `v: &\'a [Vec<U>]` represents the 2D `Vec`, we are indexing, `Vec` implements\\n `Slice` trait and _clippy_ recommends using `&[T]` to `&Vec<T>`, exact details\\n are unknown to me\\n- `idx: &Vector2D<T>` represents the _indices_ which we use, we take them by\\n reference to avoid an unnecessary copy\\n- `-> &\'a U` means that we are returning a _reference_ to some value of type `U`.\\n Now the question is what does the `\'a` mean, we can also see it as a generic\\n type declared along `T` and `U`. And the answer is _relatively_ simple, `\'a`\\n represents a _lifetime_. We take the `v` by a reference and return a reference,\\n borrow checker validates all of the _borrows_ (or references), so we need to\\n specify that our returned value has _the same lifetime_ as the vector we have\\n taken by a reference, i.e. returned reference must live at least as long as the\\n `v`. This way we can \u201cbe sure\u201d that the returned reference is valid.\\n\\n##### Issues\\n\\nFirst issue that our implementation has is the fact that we cannot get a mutable\\nreference out of that function. This could be easily resolved by introducing new\\nfunction, e.g. `index_mut`. Which I have actually done while writing this part:\\n\\n```rust\\npub fn index_mut<\'a, T, U>(v: &\'a mut [Vec<U>], idx: &Vector2D<T>) -> &\'a mut U\\nwhere\\n usize: TryFrom<T>,\\n <usize as TryFrom<T>>::Error: Debug,\\n T: Copy,\\n{\\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\\n &mut v[y][x]\\n}\\n```\\n\\n:::warning **\xab\u21af\xbb** Why can\'t we use one function?\\n\\nWhen we consider a `Vec<T>`, we don\'t need to consider containers as `T`, Rust\\nimplements indexing as traits `Index<T>` and `IndexMut<T>` that do the dirty work\\nbehind syntactic sugar of `container[idx]`.\\n\\nHowever, implementing of traits is not allowed for _external_ types, i.e. types\\nthat you haven\'t defined yourself. This means that you can implement indexing\\nover containers that you have implemented yourself, but you cannot use your own\\ntypes for indexing \u201cbuilt-in\u201d types.\\n\\nAnother part of this rabbit hole is trait `SliceIndex<T>` that is of a relevance\\nbecause of\\n\\n```rust\\nimpl<T, I> Index<I> for [T]\\nwhere\\n I: SliceIndex<[T]>\\n\\nimpl<T, I, A> Index<I> for Vec<T, A>\\nwhere\\n I: SliceIndex<[T]>,\\n A: Allocator\\n\\nimpl<T, I, const N: usize> Index<I> for [T; N]\\nwhere\\n [T]: Index<I>\\n```\\n\\nIn other words, if your type implements `SliceIndex<T>` trait, it can be used\\nfor indexing. As of now, this trait has all of its required methods experimental\\nand is marked as `unsafe`.\\n\\n:::\\n\\nAnother problem is a requirement for indexing either `[Vec<T>]` or `Vec<Vec<T>>`.\\nThis requirement could be countered by removing inner type `Vec<T>` and constraining\\nit by a trait `Index` (or `IndexMut` respectively) in a following way\\n\\n```rust\\npub fn index<\'a, C, T>(v: &\'a [C], idx: &Vector2D<T>) -> &\'a C::Output\\nwhere\\n usize: TryFrom<T>,\\n <usize as TryFrom<T>>::Error: Debug,\\n T: Copy,\\n C: Index<usize>\\n{\\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\\n &v[y][x]\\n}\\n```\\n\\nGiven this, we can also give a more meaningful typename for indexing type, such\\nas `I`.\\n\\n#### Checking bounds\\n\\nNow we can get to the boundary checks, it is very similar, but a more\u2026 dirty.\\nFirst approach that came up was to convert the indices in `Vector2D` to `usize`,\\nbut when you add the indices up, e.g. when checking the neighbors, you can end\\nup with negative values which, unlike in C++, causes an error (instead of underflow\\nthat you can use to your advantage; you can easily guess how).\\n\\nSo how can we approach this then? Well\u2026 we will convert the bounds instead of\\nthe indices and that lead us to:\\n\\n```rust\\npub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool\\nwhere\\n usize: TryInto<T>,\\n <usize as TryInto<T>>::Error: Debug,\\n T: PartialOrd + Copy,\\n{\\n idx.y >= 0.try_into().unwrap()\\n && idx.y < v.len().try_into().unwrap()\\n && idx.x >= 0.try_into().unwrap()\\n && idx.x\\n < v[TryInto::<usize>::try_into(idx.y).unwrap()]\\n .len()\\n .try_into()\\n .unwrap()\\n}\\n```\\n\\nYou can tell that it\'s definitely a shitty code. Let\'s improve it now! We will\\nget back to the original idea, but do it better. We know that we cannot convert\\nnegative values into `usize`, **but** we also know that conversion like that\\nreturns a `Result<T, E>` which we can use to our advantage.\\n\\n```rust\\npub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool\\nwhere\\n T: Copy,\\n usize: TryFrom<T>,\\n{\\n usize::try_from(idx.y)\\n .and_then(|y| usize::try_from(idx.x).map(|x| y < v.len() && x < v[y].len()))\\n .unwrap_or(false)\\n}\\n```\\n\\n`Result<T, E>` is a type similar to `Either` in Haskell and it allows us to chain\\nmultiple operations on correct results or propagate the original error without\\ndoing anything. Let\'s dissect it one-by-one.\\n\\n`try_from` is a method implemented in `TryFrom` trait, that allows you to convert\\ntypes and either successfully convert them or fail (with a reasonable error). This\\nmethod returns `Result<T, E>`.\\n\\nWe call `and_then` on that _result_, let\'s have a look at the type signature of\\n`and_then`, IMO it explains more than enough:\\n\\n```rust\\npub fn and_then<U, F>(self, op: F) -> Result<U, E>\\nwhere\\n F: FnOnce(T) -> Result<U, E>\\n```\\n\\nOK\u2026 So it takes the result and a function and returns another result with\\ndifferent value and different error. However we can see that the function, which\\nrepresents an operation on a result, takes just the value, i.e. it doesn\'t care\\nabout any previous error. To make it short:\\n\\n> `and_then` allows us to run an operation, which can fail, on the correct result\\n\\nWe parsed a `y` index and now we try to convert the `x` index with `try_from`\\nagain, but on that result we use `map` rather than `and_then`, why would that be?\\n\\n```rust\\npub fn map<U, F>(self, op: F) -> Result<U, E>\\nwhere\\n F: FnOnce(T) -> U\\n```\\n\\nHuh\u2026 `map` performs an operation that **cannot** fail. And finally we use\\n`unwrap_or` which takes the value from result, or in case of an error returns the\\ndefault that we define.\\n\\nHow does this work then? If `y` is negative, the conversion fails and the error\\npropagates all the way to `unwrap_or`, if `y` can be a correct `usize` value, then\\nwe do the same with `x`. If `x` is negative, we propagate the error as with `y`,\\nand if it\'s not, then we check whether it exceeds the higher bounds or not.\\n\\n### Solution\\n\\nRelatively simple, you just need follow the rules and not get too smart, otherwise\\nit will get back at you.\\n\\n## [Day 9: Rope Bridge](https://adventofcode.com/2022/day/9)\\n\\n:::info tl;dr\\n\\nWe get a rope with knots and we want to track how many different positions are\\nvisited with the rope\'s tail.\\n\\n:::\\n\\nBy this day, I have come to a conclusion that current skeleton for each day\\ngenerates a lot of boilerplate. And even though it can be easily copied, it\'s\\njust a waste of space and unnecessary code. Let\'s \u201csimplify\u201d this (on one end\\nwhile creating monster on the other end). I\'ve gone through what we need in the\\npreparations for the AoC. Let\'s sum up our requirements:\\n\\n- parsing\\n- part 1 & 2\\n- running on sample / input\\n- tests\\n\\nParsing and implementation of both parts is code that changes each day and we\\ncannot do anything about it. However running and testing can be simplified!\\n\\nLet\'s introduce and export a new module `solution` that will take care of all of\\nthis. We will start by introducing a trait for each day.\\n\\n```rust\\npub trait Solution<Input, Output: Display> {\\n fn parse_input<P: AsRef<Path>>(pathname: P) -> Input;\\n\\n fn part_1(input: &Input) -> Output;\\n fn part_2(input: &Input) -> Output;\\n}\\n```\\n\\nThis does a lot of work for us already, we have defined a trait and for each day\\nwe will create a structure representing a specific day. That structure will also\\nimplement the `Solution` trait.\\n\\nNow we need to get rid of the boilerplate, we can\'t get rid of the `main` function,\\nbut we can at least move out the functionality.\\n\\n```rust\\nfn run(type_of_input: &str) -> Result<()>\\nwhere\\n Self: Sized,\\n{\\n tracing_subscriber::fmt()\\n .with_env_filter(EnvFilter::from_default_env())\\n .with_target(false)\\n .with_file(true)\\n .with_line_number(true)\\n .without_time()\\n .compact()\\n .init();\\n color_eyre::install()?;\\n\\n let input = Self::parse_input(format!(\\"{}s/{}.txt\\", type_of_input, Self::day()));\\n\\n info!(\\"Part 1: {}\\", Self::part_1(&input));\\n info!(\\"Part 2: {}\\", Self::part_2(&input));\\n\\n Ok(())\\n}\\n\\nfn main() -> Result<()>\\nwhere\\n Self: Sized,\\n{\\n Self::run(\\"input\\")\\n}\\n```\\n\\nThis is all part of the `Solution` trait, which can implement methods while being\\ndependent on what is provided by the implementing types. In this case, we just\\nneed to bound the `Output` type to implement `Display` that is necessary for the\\n`info!` and format string there.\\n\\nNow we can get to first of the nasty things we are going to do\u2026 And it is the\\n`day()` method that you can see being used when constructing path to the input\\nfile. That method will generate a name of the file, e.g. `day01` and we know that\\nwe can _somehow_ deduce it from the structure name, given we name it reasonably.\\n\\n```rust\\nfn day() -> String {\\n let mut day = String::from(type_name::<Self>().split(\\"::\\").next().unwrap());\\n day.make_ascii_lowercase();\\n\\n day.to_string()\\n}\\n```\\n\\n:::warning `type_name`\\n\\nThis feature is still experimental and considered to be internal, it is not\\nadvised to use it any production code.\\n\\n:::\\n\\nAnd now we can get to the nastiest stuff :weary: We will **generate** the tests!\\n\\nWe want to be able to generate tests for sample input in a following way:\\n\\n```rust\\ntest_sample!(day_01, Day01, 42, 69);\\n```\\n\\nThere\'s not much we can do, so we will write a macro to generate the tests for us.\\n\\n```rust\\n#[macro_export]\\nmacro_rules! test_sample {\\n ($mod_name:ident, $day_struct:tt, $part_1:expr, $part_2:expr) => {\\n #[cfg(test)]\\n mod $mod_name {\\n use super::*;\\n\\n #[test]\\n fn test_part_1() {\\n let sample =\\n $day_struct::parse_input(&format!(\\"samples/{}.txt\\", $day_struct::day()));\\n assert_eq!($day_struct::part_1(&sample), $part_1);\\n }\\n\\n #[test]\\n fn test_part_2() {\\n let sample =\\n $day_struct::parse_input(&format!(\\"samples/{}.txt\\", $day_struct::day()));\\n assert_eq!($day_struct::part_2(&sample), $part_2);\\n }\\n }\\n };\\n}\\n```\\n\\nWe have used it in a similar way as macros in C/C++, one of the things that we\\ncan use to our advantage is defining \u201ctype\u201d of the parameters for the macro. All\\nparameters have their name prefixed with `$` sign and you can define various \u201cforms\u201d\\nof your macro. Let\'s go through it!\\n\\nWe have following parameters:\\n\\n- `$mod_name` which represents the name for the module with tests, it is typed\\n with `ident` which means that we want a valid identifier to be passed in.\\n- `$day_struct` represents the structure that will be used for tests, it is typed\\n with `tt` which represents a _token tree_, in our case it is a type.\\n- `$part_X` represents the expected output for the `X`th part and is of type `expr`\\n which literally means an _expression_.\\n\\nApart from that we need to use `#[macro_export]` to mark the macro as exported\\nfor usage outside of the module. Now our skeleton looks like:\\n\\n```rust\\nuse aoc_2022::*;\\n\\ntype Input = String;\\ntype Output = String;\\n\\nstruct DayXX;\\nimpl Solution<Input, Output> for DayXX {\\n fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {\\n file_to_string(pathname)\\n }\\n\\n fn part_1(input: &Input) -> Output {\\n todo!()\\n }\\n\\n fn part_2(input: &Input) -> Output {\\n todo!()\\n }\\n}\\n\\nfn main() -> Result<()> {\\n // DayXX::run(\\"sample\\")\\n DayXX::main()\\n}\\n\\n// test_sample!(day_XX, DayXX, , );\\n```\\n\\n### Solution\\n\\nNot much to talk about, it is relatively easy to simulate.\\n\\n## [Day 10: Cathode-Ray Tube](https://adventofcode.com/2022/day/10)\\n\\n:::info tl;dr\\n\\nEmulating basic arithmetic operations on a CPU and drawing on CRT based on the\\nCPU\'s accumulator.\\n\\n:::\\n\\nIn this day I have discovered an issue with my design of the `Solution` trait.\\nAnd the issue is caused by different types of `Output` for the part 1 and part 2.\\n\\nProblem is relatively simple and consists of simulating a CPU, I have approached\\nit in a following way:\\n\\n```rust\\nfn evaluate_instructions(instructions: &[Instruction], mut out: Output) -> Output {\\n instructions\\n .iter()\\n .fold(State::new(), |state, instruction| {\\n state.execute(instruction, &mut out)\\n });\\n\\n out\\n}\\n```\\n\\nWe just take the instructions, we have some state of the CPU and we execute the\\ninstructions one-by-one. Perfect usage of the `fold` (or `reduce` as you may know\\nit from other languages).\\n\\nYou can also see that we have an `Output` type, so the question is how can we fix\\nthat problem. And the answer is very simple and _functional_. Rust allows you to\\nhave an `enumeration` that can _bear_ some other values apart from the type itself.\\n\\n:::tip\\n\\nWe could\'ve seen something like this with the `Result<T, E>` type that can be\\ndefined as\\n\\n```rust\\nenum Result<T, E> {\\n Ok(T),\\n Err(E)\\n}\\n```\\n\\n###### What does that mean though?\\n\\nWhen we have an `Ok` value, it has the result itself, and when we get an `Err`\\nvalue, it has the error. This also allows us to handle _results_ in a rather\\npretty way:\\n\\n```rust\\nmatch do_something(x) {\\n Ok(y) => {\\n println!(\\"SUCCESS: {}\\", y);\\n },\\n Err(y) => {\\n eprintln!(\\"ERROR: {}\\", y);\\n }\\n}\\n```\\n\\n:::\\n\\nMy solution has a following outline:\\n\\n```rust\\nfn execute(&self, i: &Instruction, output: &mut Output) -> State {\\n // execute the instruction\\n\\n // collect results if necessary\\n match output {\\n Output::Part1(x) => self.execute_part_1(y, x),\\n Output::Part2(x) => self.execute_part_2(y, x),\\n }\\n\\n // return the obtained state\\n new_state\\n}\\n```\\n\\nYou might think that it\'s a perfectly reasonable thing to do. Yes, **but** notice\\nthat the `match` statement doesn\'t _collect_ the changes in any way and also we\\npass `output` by `&mut`, so it is shared across each _iteration_ of the `fold`.\\n\\nThe dirty and ingenious thing is that `x`s are passed by `&mut` too and therefore\\nthey are directly modified by the helper functions. To sum it up and let it sit\\n\\n> We are **collecting** the result **into** an **enumeration** that is **shared**\\n> across **all** iterations of `fold`.\\n\\n### Solution\\n\\nSimilar to _Day 9_, but there are some technical details that can get you.\\n\\n## [Day 11: Monkey in the Middle](https://adventofcode.com/2022/day/11)\\n\\n:::info tl;dr\\n\\nSimulation of monkeys throwing stuff around and measuring your stress levels\\nwhile your stuff is being passed around.\\n\\n:::\\n\\nI think I decided to use regular expressions here for the first time, cause\\nparsing the input was a pain.\\n\\nAlso I didn\'t expect to implement Euclidean algorithm in Rust\u2026\\n\\n### Solution\\n\\nAgain, we\'re just running a simulation. Though I must admit it was very easy to\\nmake a small technical mistakes that could affect the final results very late.\\n\\n## [Day 12: Hill Climbing Algorithm](https://adventofcode.com/2022/day/12)\\n\\n:::info tl;dr\\n\\nFinding shortest path up the hill and also shortest path down to the ground while\\nalso rolling down the hill\u2026\\n\\n:::\\n\\nAs I have said in the _tl;dr_, we are looking for the shortest path, but the start\\nand goal differ for the part 1 and 2. So I have decided to refactor my solution\\nto a BFS algorithm that takes necessary parameters via functions:\\n\\n```rust\\nfn bfs<F, G>(\\n graph: &[Vec<char>], start: &Position, has_edge: F, is_target: G\\n) -> Option<usize>\\nwhere\\n F: Fn(&[Vec<char>], &Position, &Position) -> bool,\\n G: Fn(&[Vec<char>], &Position) -> bool\\n```\\n\\nWe pass the initial vertex from the caller and everything else is left to the BFS\\nalgorithm, based on the `has_edge` and `is_target` functions.\\n\\nThis was easy! And that is not very usual in Rust once you want to pass around\\nfunctions. :eyes:\\n\\n### Solution\\n\\nLooking for the shortest path\u2026 Must be Dijkstra, right? **Nope!** Half of the\\nReddit got jebaited though. In all fairness, nothing stops you from implementing\\nthe Dijkstra\'s algorithm for finding the shortest path, **but** if you know that\\nall connected vertices are in a unit (actually $d = 1$) distance from each other,\\nthen you know that running Dijkstra is equivalent to running BFS, only with worse\\ntime complexity, because of the priority heap instead of the queue.\\n\\n## [Day 13: Distress Signal](https://adventofcode.com/2022/day/13)\\n\\n:::info tl;dr\\n\\nProcessing packets with structured data from the distress signal.\\n\\n:::\\n\\nYou can implement a lot of traits if you want to. It is _imperative_ to implement\\nordering on the packets. I had a typo, so I also proceeded to implement a `Display`\\ntrait for debugging purposes:\\n\\n```rust\\nimpl Display for Packet {\\n fn fmt(&self, f: &mut std::fmt::Formatter<\'_>) -> std::fmt::Result {\\n match self {\\n Packet::Integer(x) => write!(f, \\"{x}\\"),\\n Packet::List(lst) => write!(f, \\"[{}]\\", lst.iter().map(|p| format!(\\"{p}\\")).join(\\",\\")),\\n }\\n }\\n}\\n```\\n\\n### Solution\\n\\nA lot of technical details\u2026 Parsing is nasty too\u2026\\n\\n## [Day 14: Regolith Reservoir](https://adventofcode.com/2022/day/14)\\n\\n:::info tl;dr\\n\\nLet\'s simulate falling sand grain-by-grain.\\n\\n:::\\n\\nAgain, both parts are relatively similar with minimal changes, so it is a good\\nidea to refactor it a bit. Similar approach to the [BFS above]. Also this is the\\nfirst day where I ran into efficiency issues and had to redo my solution to speed\\nit up just a bit.\\n\\n### Solution\\n\\nTedious.\\n\\n## Post Mortem\\n\\n### Indexing\\n\\nI was asked about the indexing after publishing the blog. And truly it is rather\\ncomplicated topic, especially after releasing `SliceIndex<I>` trait. I couldn\'t\\nleave it be, so I tried to implement the `Index` and `IndexMut` trait.\\n\\n:::note\\n\\nI have also mentioned that the `SliceIndex` trait is `unsafe`, but truth be told,\\nonly _unsafe_ part are the 2 methods that are named `*unchecked*`. Anyways, I will\\nbe implementing the `Index*` traits for now, rather than the `SliceIndex`.\\n\\n:::\\n\\nIt\'s relatively straightforward\u2026\\n\\n```rust\\nimpl<I, C> Index<Vector2D<I>> for [C]\\nwhere\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: Index<usize>,\\n{\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D<I>) -> &Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &self[y][x]\\n }\\n}\\n\\nimpl<I, C> IndexMut<Vector2D<I>> for [C]\\nwhere\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: IndexMut<usize>,\\n{\\n fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &mut self[y][x]\\n }\\n}\\n```\\n\\nWe can see a lot of similarities to the implementation of `index` and `index_mut`\\nfunctions. In the end, they are 1:1, just wrapped in the trait that provides a\\nsyntax sugar for `container[idx]`.\\n\\n:::note\\n\\nI have also switched from using the `TryFrom` to `TryInto` trait, since it better\\nmatches what we are using, the `.try_into` rather than `usize::try_from`.\\n\\nAlso implementing `TryFrom` automatically provides you with a `TryInto` trait,\\nsince it is relatively easy to implement. Just compare the following:\\n\\n```rust\\npub trait TryFrom<T>: Sized {\\n type Error;\\n\\n fn try_from(value: T) -> Result<Self, Self::Error>;\\n}\\n\\npub trait TryInto<T>: Sized {\\n type Error;\\n\\n fn try_into(self) -> Result<T, Self::Error>;\\n}\\n```\\n\\n:::\\n\\nOK, so we have our trait implemented, we should be able to use `container[index]`,\\nright? Yes\u2026 but actually no :frowning:\\n\\n```\\nerror[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`\\n --\x3e src/bin/day08.rs:26:18\\n |\\n26 | if trees[pos] > tallest {\\n | ^^^ slice indices are of type `usize` or ranges of `usize`\\n |\\n = help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`\\n = note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`\\n\\nerror[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`\\n --\x3e src/bin/day08.rs:30:28\\n |\\n30 | max(tallest, trees[pos])\\n | ^^^ slice indices are of type `usize` or ranges of `usize`\\n |\\n = help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`\\n = note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`\\n\\nerror[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<isize>`\\n --\x3e src/bin/day08.rs:52:28\\n |\\n52 | let max_height = trees[position];\\n | ^^^^^^^^ slice indices are of type `usize` or ranges of `usize`\\n |\\n = help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<isize>`\\n = note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<isize>>`\\n```\\n\\nWhy? We have it implemented for the slices (`[C]`), why doesn\'t it work? Well,\\nthe fun part consists of the fact that in other place, where we were using it,\\nwe were passing the `&[Vec<T>]`, but this is coming from a helper functions that\\ntake `&Vec<Vec<T>>` instead. And\u2026 we don\'t implement `Index` and `IndexMut` for\\nthose. Just for the slices. \ud83e\udd2f _What are we going to do about it?_\\n\\nWe can either start copy-pasting or be smarter about it\u2026 I choose to be smarter,\\nso let\'s implement a macro! The only difference across the implementations are\\nthe types of the outer containers. Implementation doesn\'t differ **at all**!\\n\\nImplementing the macro can be done in a following way:\\n\\n```rust\\nmacro_rules! generate_indices {\\n ($container:ty) => {\\n impl<I, C> Index<Vector2D<I>> for $container\\n where\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: Index<usize>,\\n {\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D<I>) -> &Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &self[y][x]\\n }\\n }\\n\\n impl<I, C> IndexMut<Vector2D<I>> for $container\\n where\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: IndexMut<usize>,\\n {\\n fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &mut self[y][x]\\n }\\n }\\n };\\n}\\n```\\n\\nAnd now we can simply do\\n\\n```rust\\ngenerate_indices!(VecDeque<C>);\\ngenerate_indices!([C]);\\ngenerate_indices!(Vec<C>);\\n// generate_indices!([C; N], const N: usize);\\n```\\n\\nThe last type (I took the inspiration from the implementations of the `Index` and\\n`IndexMut` traits) is a bit problematic, because of the `const N: usize` part,\\nwhich I haven\'t managed to be able to parse. And that\'s how I got rid of the error.\\n\\n:::note\\n\\nIf I were to use 2D-indexing over `[C; N]` slices, I\'d probably just go with the\\ncopy-paste, cause the cost of this \u201cmonstrosity\u201d outweighs the benefits of no DRY.\\n\\n:::\\n\\n#### Cause of the problem\\n\\nThis issue is relatively funny. If you don\'t use any type aliases, just the raw\\ntypes, you\'ll get suggested certain changes by the _clippy_. For example if you\\nconsider the following piece of code\\n\\n```rust\\nfn get_sum(nums: &Vec<i32>) -> i32 {\\n nums.iter().sum()\\n}\\n\\nfn main() {\\n let nums = vec![1, 2, 3];\\n println!(\\"Sum: {}\\", get_sum(&nums));\\n}\\n```\\n\\nand you run _clippy_ on it, you will get\\n\\n```\\nChecking playground v0.0.1 (/playground)\\nwarning: writing `&Vec` instead of `&[_]` involves a new object where a slice will do\\n --\x3e src/main.rs:1:18\\n |\\n1 | fn get_sum(nums: &Vec<i32>) -> i32 {\\n | ^^^^^^^^^ help: change this to: `&[i32]`\\n |\\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg\\n = note: `#[warn(clippy::ptr_arg)]` on by default\\n\\nwarning: `playground` (bin \\"playground\\") generated 1 warning\\n Finished dev [unoptimized + debuginfo] target(s) in 0.61s\\n```\\n\\nHowever, if you introduce a type alias, such as\\n\\n```rust\\ntype Numbers = Vec<i32>;\\n```\\n\\nThen _clippy_ won\'t say anything, cause there is literally nothing to suggest.\\nHowever the outcome is not the same\u2026\\n\\n[_advent of code_]: https://adventofcode.com\\n[bfs above]: #day-12-hill-climbing-algorithm"},{"id":"aoc-2022/1st-week","metadata":{"permalink":"/blog/aoc-2022/1st-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/01-week-1.md","source":"@site/blog/aoc-2022/01-week-1.md","title":"1st week of Advent of Code \'22 in Rust","description":"Surviving first week in Rust.","date":"2022-12-15T01:15:00.000Z","formattedDate":"December 15, 2022","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":12.4,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"1st week of Advent of Code \'22 in Rust","description":"Surviving first week in Rust.","date":"2022-12-15T01:15","slug":"aoc-2022/1st-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"2nd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/2nd-week"},"nextItem":{"title":"Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/intro"}},"content":"Let\'s go through the first week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n:::note\\n\\nIf you wish to have a look at the solutions, you can follow them on my [GitLab].\\nMore specifically in the [`/src/bin/`].\\n\\n:::\\n\\nI will try to summarize my experience with using Rust for the AoC. Trying it out\\nages ago, I believe it will be _pain and suffering_, but we will see. For each\\nday I will also try to give a tl;dr of the problem, so that you can better imagine\\nthe relation to my woes or :+1: moments.\\n\\n## [Day 1: Calorie Counting](https://adventofcode.com/2022/day/1)\\n\\n:::info tl;dr\\n\\nAs the name suggests, we get the calories of the food contained in the elves\\nbackpacks and we want to choose the elf that has the most food ;)\\n\\n:::\\n\\n> Wakey wakey!\\n\\nProgramming in Rust at 6am definitely hits. I\'ve also forgotten to mention how I\\nhandle samples. With each puzzle you usually get a sample input and expected\\noutput. You can use them to verify that your solution works, or usually doesn\'t.\\n\\nAt first I\'ve decided to put asserts into my `main`, something like\\n\\n```rust\\nassert_eq!(part_1(&sample), 24000);\\ninfo!(\\"Part 1: {}\\", part_1(&input));\\n\\nassert_eq!(part_2(&sample), 45000);\\ninfo!(\\"Part 2: {}\\", part_2(&input));\\n```\\n\\nHowever, once you get further, the sample input may take some time to run itself.\\nSo in the end, I have decided to turn them into unit tests:\\n\\n```rust\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n\\n #[test]\\n fn test_part_1() {\\n let sample = parse_input(\\"samples/day01.txt\\");\\n assert_eq!(part_1(&sample), 24000);\\n }\\n\\n #[test]\\n fn test_part_2() {\\n let sample = parse_input(\\"samples/day01.txt\\");\\n assert_eq!(part_2(&sample), 45000);\\n }\\n}\\n```\\n\\nAnd later on I have noticed, it\'s hard to tell the difference between the days,\\nso I further renamed the `mod` from generic `tests` to reflect the days.\\n\\nAlso after finishing the first day puzzle, I have installed an [`sccache`] to\\ncache the builds, so that the build time is lower, cause it was kinda unbearable.\\n\\n### Solution\\n\\nWell, it\'s a pretty simple problem. You just take the input, sum the calories and\\nfind the biggest one. However, if we try to generalize to more than the biggest\\none, the fun appears. We have few options:\\n\\n- keep all the calories, sort them, take what we need\\n- keep all the calories and use max heap\\n- use min heap and maintain at most N calories that we need\\n\\n## [Day 2: Rock Paper Scissors](https://adventofcode.com/2022/day/2)\\n\\n:::info tl;dr\\n\\nYou want to know what score did you achieve while playing _Rock Paper Scissors_.\\nAnd then you want to be strategic about it.\\n\\n:::\\n\\nApart from the technical details of the puzzle, it went relatively smooth.\\n\\n### Solution\\n\\nI took relatively na\xefve approach and then tried to simplify it.\\n\\n## [Day 3: Rucksack Reorganization](https://adventofcode.com/2022/day/3)\\n\\n:::info tl;dr\\n\\nLet\'s go reorganize elves\' backpacks! Each backpacks has 2 compartments and you\\nwant to find the common item among those compartments. Each of them has priority,\\nyou care only about the sum.\\n\\n:::\\n\\nThis is the day where I started to fight the compiler and neither of us decided\\nto give up. Let\'s dive into it \\\\o/\\n\\n:::tip Fun fact\\n\\nFighting the compiler took me 30 minutes.\\n\\n:::\\n\\nWe need to find a common item among 2 collections, that\'s an easy task, right?\\nWe can construct 2 sets and find an intersection:\\n\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3].iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5].iter().collect();\\n```\\n\\nNow, the first issue that we encounter is caused by the fact that we are using\\na slice (the `[\u2026]`), iterator of that returns **references** to the numbers.\\nAnd we get immediately yelled at by the compiler, because the numbers are discarded\\nafter running the `.collect`. To fix this, we can use `.into_iter`:\\n\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5].into_iter().collect();\\n```\\n\\nThis way the numbers will get copied instead of referenced. OK, let\'s find the\\nintersection of those 2 collections:\\n\\n```rust\\nprintln!(\\"Common elements: {:?}\\", top.intersection(&bottom));\\n```\\n\\n```\\nCommon elements: [3]\\n```\\n\\n:::warning[caution]\\n\\nNotice that we need to do `&bottom`. It explicitly specifies that `.intersection`\\n**borrows** the `bottom`, i.e. takes an immutable reference to it.\\n\\n:::\\n\\nThat\'s what we want, right? Looks like it! \\\\o/\\n\\nNext part wants us to find the common element among all of the backpacks. OK, so\\nthat should be fairly easy, we have an intersection and we want to find intersection\\nover all of them.\\n\\nLet\'s have a look at the type of the `.intersection`\\n\\n```rust\\npub fn intersection<\'a>(\\n\xa0\xa0\xa0\xa0&\'a self,\\n\xa0\xa0\xa0\xa0other: &\'a HashSet<T, S>\\n) -> Intersection<\'a, T, S>\\n```\\n\\nOK\u2026 Huh\u2026 But we have an example there!\\n\\n```rust\\nlet intersection: HashSet<_> = a.intersection(&b).collect();\\n```\\n\\nCool, that\'s all we need.\\n\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();\\n\\nlet intersection: HashSet<_> = top.intersection(&bottom).collect();\\nprintln!(\\"Intersection: {:?}\\", intersection);\\n```\\n\\n```\\nIntersection: {3, 4}\\n```\\n\\nCool, so let\'s do the intersection with the `top_2`:\\n\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();\\n\\nlet intersection: HashSet<_> = top.intersection(&bottom).collect();\\nlet intersection: HashSet<_> = intersection.intersection(&top_2).collect();\\nprintln!(\\"Intersection: {:?}\\", intersection);\\n```\\n\\nAnd we get yelled at by the compiler:\\n\\n```\\nerror[E0308]: mismatched types\\n --\x3e src/main.rs:10:58\\n |\\n10 | let intersection: HashSet<_> = intersection.intersection(&top_2).collect();\\n | ------------ ^^^^^^ expected `&i32`, found `i32`\\n | |\\n | arguments to this function are incorrect\\n |\\n = note: expected reference `&HashSet<&i32>`\\n found reference `&HashSet<i32>`\\n```\\n\\n/o\\\\ What the hell is going on here? Well, the funny thing is, that this operation\\ndoesn\'t return the elements themselves, but the references to them and when we pass\\nthe third set, it has just the values themselves, without any references.\\n\\n:::tip\\n\\nIt may seem as a very weird decision, but in fact it makes some sense\u2026 It allows\\nyou to do intersection of items that may not be possible to copy. Overall this is\\na \u201ctax\u201d for having a borrow checker ~~drilling your ass~~ having your back and\\nmaking sure you\'re not doing something naughty that may cause an **undefined**\\n**behavior**.\\n\\n:::\\n\\nTo resolve this we need to get an iterator that **clones** the elements:\\n\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();\\n\\nlet intersection: HashSet<_> = top.intersection(&bottom).cloned().collect();\\nlet intersection: HashSet<_> = intersection.intersection(&top_2).cloned().collect();\\nlet intersection: HashSet<_> = intersection.intersection(&bottom_2).cloned().collect();\\nprintln!(\\"Intersection: {:?}\\", intersection);\\n```\\n\\n```\\nIntersection: {4}\\n```\\n\\n### Solution\\n\\nThe approach is pretty simple, if you omit the _1on1 with the compiler_. You just\\nhave some fun with the set operations :)\\n\\n## [Day 4: Camp Cleanup](https://adventofcode.com/2022/day/4)\\n\\n:::info tl;dr\\n\\nElves are cleaning up the camp and they got overlapping sections to clean up.\\nFind how many overlap and can take the day off.\\n\\n:::\\n\\n[`RangeInclusive`] is your friend not an enemy :)\\n\\n### Solution\\n\\nRelatively easy, you just need to parse the input and know what you want. Rust\'s\\n`RangeInclusive` type helped a lot, cause it took care of all abstractions.\\n\\n## [Day 5: Supply Stacks](https://adventofcode.com/2022/day/5)\\n\\n:::info tl;dr\\n\\nLet\'s play with stacks of crates.\\n\\n:::\\n\\nVery easy problem with very annoying input. You can judge yourself:\\n\\n```\\n [D]\\n[N] [C]\\n[Z] [M] [P]\\n 1 2 3\\n\\nmove 1 from 2 to 1\\nmove 3 from 1 to 3\\nmove 2 from 2 to 1\\nmove 1 from 1 to 2\\n```\\n\\nGood luck transforming that into something reasonable :)\\n\\n:::tip Fun fact\\n\\nTook me 40 minutes to parse this reasonably, including fighting the compiler.\\n\\n:::\\n\\n### Solution\\n\\nFor the initial solution I went with a manual solution (as in _I have done all_\\n_the work_. Later on I have decided to explore the `std` and interface of the\\n`std::vec::Vec` and found [`split_off`] which takes an index and splits (duh)\\nthe vector:\\n\\n```rust\\nlet mut vec = vec![1, 2, 3];\\nlet vec2 = vec.split_off(1);\\nassert_eq!(vec, [1]);\\nassert_eq!(vec2, [2, 3]);\\n```\\n\\nThis helped me simplify my solution a lot and also get rid of some _edge cases_.\\n\\n## [Day 6: Tuning Trouble](https://adventofcode.com/2022/day/6)\\n\\n:::info tl;dr\\n\\nFinding start of the message in a very weird protocol. Start of the message is\\ndenoted by $N$ unique consecutive characters.\\n\\n:::\\n\\n### Solution\\n\\nA lot of different approaches, knowing that we are dealing with input consisting\\nsolely of ASCII letters, I bit the bullet and went with sliding window and\\nconstructing sets from that window, checking if the set is as big as the window.\\n\\nOne possible optimization could consist of keeping a bit-vector (i.e. `usize`\\nvariable) of encountered characters and updating it as we go. However this has\\na different issue and that is removal of the characters from the left side of the\\nwindow. We don\'t know if the same character is not included later on.\\n\\nOther option is to do similar thing, but keeping the frequencies of the letters,\\nand again knowing we have only ASCII letters we can optimize by having a vector\\nof 26 elements that keeps count for each lowercase letter.\\n\\n## [Day 7: No Space Left On Device](https://adventofcode.com/2022/day/7)\\n\\n:::info tl;dr\\n\\nLet\'s simulate [`du`] to get some stats about our file system and then pinpoint\\ndirectories that take a lot of space and should be deleted.\\n\\n:::\\n\\n> I was waiting for this moment, and yet it got me!\\n> _imagine me swearing for hours_\\n\\n### Solution\\n\\nWe need to \u201c_build_\u201d a file system from the input that is given in a following form:\\n\\n```\\n$ cd /\\n$ ls\\ndir a\\n14848514 b.txt\\n8504156 c.dat\\ndir d\\n$ cd a\\n$ ls\\ndir e\\n29116 f\\n2557 g\\n62596 h.lst\\n$ cd e\\n$ ls\\n584 i\\n$ cd ..\\n$ cd ..\\n$ cd d\\n$ ls\\n4060174 j\\n8033020 d.log\\n5626152 d.ext\\n7214296 k\\n```\\n\\nThere are few ways in which you can achieve this and also you can assume some\\npreconditions, but why would we do that, right? :)\\n\\nYou can \u201cslap\u201d this in either [`HashMap`] or [`BTreeMap`] and call it a day.\\nAnd that would be boring\u2026\\n\\n:::tip\\n\\n`BTreeMap` is quite fitting for this, don\'t you think?\\n\\n:::\\n\\nI always wanted to try allocation on heap in Rust, so I chose to implement a tree.\\nI fought with the `Box<T>` for some time and was losing\u2026\\n\\nThen I looked up some implementations of trees or linked lists and decided to try\\n`Rc<Cell<T>>`. And I got my _ass whopped_ by the compiler once again. /o\\\\\\n\\n:::tip\\n\\n`Box<T>` represents a dynamically allocated memory on heap. It is a single pointer,\\nyou can imagine this as `std::unique_ptr<T>` in C++.\\n\\n`Rc<T>` represents a dynamically allocated memory on heap. On top of that it is\\n_reference counted_ (that\'s what the `Rc` stands for). You can imagine this as\\n`std::shared_ptr<T>` in C++.\\n\\nNow the fun stuff. Neither of them lets you **mutate** the contents of the memory.\\n\\n`Cell<T>` allows you to mutate the memory. Can be used reasonably with types that\\ncan be copied, because the memory safety is guaranteed by copying the contents\\nwhen there is more than one **mutable** reference to the memory.\\n\\n`RefCell<T>` is similar to the `Cell<T>`, but the borrowing rules (how many mutable\\nreferences are present) are checked dynamically.\\n\\nSo in the end, if you want something like `std::shared_ptr<T>` in Rust, you want\\nto have `Rc<RefCell<T>>`.\\n\\n:::\\n\\nSo, how are we going to represent the file system then? We will use an enumeration,\\nhehe, which is an algebraic data type that can store some stuff in itself :weary:\\n\\n```rust\\ntype FileHandle = Rc<RefCell<AocFile>>;\\n\\n#[derive(Debug)]\\nenum AocFile {\\n File(usize),\\n Directory(BTreeMap<String, FileHandle>),\\n}\\n```\\n\\nLet\'s go over it! `FileHandle` represents dynamically allocated `AocFile`, not\\nmuch to discuss. What does the `#[derive(Debug)]` do though? It lets us to print\\nout the value of that enumeration, it\'s derived, so it\'s not as good as if we had\\nimplemented it ourselves, but it\'s good enough for debugging, hence the name.\\n\\nNow to the fun part! `AocFile` value can be represented in two ways:\\n\\n- `File(usize)`, e.g. `AocFile::File(123)` and we can pattern match it, if we\\n need to\\n- `Directory(BTreeMap<String, FileHandle>)` will represent the directory and will\\n contain map matching the name of the files (or directories) within to their\\n respective file handles\\n\\nI will omit the details about constructing this file system, cause there are a lot\\nof technicalities introduced by the nature of the input. However if you are\\ninterested, you can have a look at my solution.\\n\\nWe need to find small enough directories and also find the smallest directory that\\nwill free enough space. Now the question is, how could we do that. And there are\\nmultiple ways I will describe.\\n\\nI have chosen to implement [_tree catamorphism_] :weary:. It is basically a fold\\nover a tree data structure. We descent down into the leaves and propagate computed\\nresults all the way to the root. You can also notice that this approach is very\\nsimilar to _dynamic programming_, we find overlapping sections of the computation\\nand try to minimize the additional work (in this case: we need to know sizes of\\nour descendants, but we have already been there).\\n\\nAnother approach that has been suggested to me few days later is running DFS on\\nthe graph. And, funnily enough, we would still need to combine what we found in\\nthe branches where we descent. So in the end, it would work very similarly to my\\nsolution.\\n\\nOne of the more exotic options would be precomputing the required information at\\nthe same time as parsing. That could be done by adding additional fields to the\\nnodes which would allow storing such information and updating it as we construct\\nthe file system.\\n\\n## Post Mortem\\n\\nThings that have been brought up in the discussion later on.\\n\\n### `Rc<T>` vs `Rc<RefCell<T>>`\\n\\nIt has been brought up that I have a contradicting statement regarding the\\ndynamically allocated memory. Specifically:\\n\\n- You can imagine `Rc<T>` as an `std::shared_ptr<T>` (in C++)\\n- When you want an equivalent of `std::shared_ptr<T>`, you want to use\\n `Rc<RefCell<T>>`\\n\\nNow, in Rust it is a bit more complicated, because the type that represents the\\n\u201cshared pointer\u201d is `Rc<T>`. What `RefCell<T>` does is making sure that there is\\nonly one \u201cowner\u201d of a mutable reference at a time (and dynamically, as opposed\\nto the `Cell<T>`).\\n\\nTherefore to be precise and correct about the equivalents of `std::shared_ptr<T>`\\nin Rust, we can say that\\n\\n- `Rc<T>` is an equivalent of a `const std::shared_ptr<T>`,\\n- and `Rc<RefCell<T>>` is an equivalent of a `std::shared_ptr<T>`.\\n\\nYou can easily see that they only differ in the mutability. (And even that is not\\nas simple as it seems, because there is also `Cell<T>`)\\n\\n[_advent of code_]: https://adventofcode.com\\n[gitlab]: https://gitlab.com/mfocko/advent-of-code-2022\\n[`/src/bin/`]: https://gitlab.com/mfocko/advent-of-code-2022/-/tree/main/src/bin\\n[`sccache`]: https://github.com/mozilla/sccache\\n[`rangeinclusive`]: https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html\\n[`split_off`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split_off\\n[`du`]: https://www.man7.org/linux/man-pages/man1/du.1.html\\n[`hashmap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html\\n[`btreemap`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html\\n[_tree catamorphism_]: https://en.wikipedia.org/wiki/Catamorphism#Tree_fold"},{"id":"aoc-2022/intro","metadata":{"permalink":"/blog/aoc-2022/intro","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/00-intro.md","source":"@site/blog/aoc-2022/00-intro.md","title":"Advent of Code \'22 in Rust","description":"Preparing for Advent of Code \'22.","date":"2022-12-14T21:45:00.000Z","formattedDate":"December 14, 2022","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":8.665,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"Advent of Code \'22 in Rust","description":"Preparing for Advent of Code \'22.","date":"2022-12-14T21:45","slug":"aoc-2022/intro","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"1st week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/1st-week"}},"content":"Let\'s talk about the preparations for this year\'s [_Advent of Code_].\\n\\n\x3c!--truncate--\x3e\\n\\n## Choosing a language\\n\\nWhen choosing a language for AoC, you usually want a language that gives you a\\nquick feedback which allows you to iterate quickly to the solution of the puzzle.\\nOne of the most common choices is Python, many people also use JavaScript or Ruby.\\n\\nGiven the competitive nature of the AoC and popularity among competitive programming,\\nC++ might be also a very good choice. Only if you are familiar with it, I guess\u2026\\n\\nIf you want a challenge, you might also choose to rotate the languages each day.\\nThough I prefer to use only one language.\\n\\nFor this year I have been deciding between _Rust_, _C++_ and _Pascal_ or _Ada_.\\n\\nI have tried Rust last year and have survived with it for 3 days and then gave\\nup and switched to _Kotlin_, which was pretty good given it is \u201cJava undercover\u201d.\\nI pretty much like the ideas behind Rust, I am not sure about the whole cult and\\nimplementation of those ideas though. After some years with C/C++, I would say\\nthat Rust feels _too safe_ for my taste and tries to \u201c_punish me_\u201d even for the\\nmost trivial things.\\n\\nC++ is a very robust, but also comes with a wide variety of options providing you\\nthe ability to shoot yourself in the leg. I have tried to solve few days of previous\\nAdvent of Code events, it was _relatively easy_ to solve the problems in C++, given\\nthat I do not admit writing my own iterator for `enumerate`\u2026\\n\\nPascal or Ada were meme choices :) Ada is heavily inspired by Pascal and has a\\npretty nice standard library that offers enough to be able to quickly solve some\\nproblems in it. However the toolkit is questionable :/\\n\\n## Choosing libraries\\n\\n## Preparations for Rust\\n\\nAll of the sources, later on including solutions, can be found at my\\n[GitLab].\\n\\n### Toolkit\\n\\nSince we are using Rust, we are going to use a [Cargo] and more than likely VSCode\\nwith [`rust-analyzer`]. Because of my choice of libraries, we will also introduce\\na `.envrc` file that can be used by [`direnv`], which allows you to set specific\\nenvironment variables when you enter a directory. In our case, we will use\\n\\n```bash\\n# to show nice backtrace when using the color-eyre\\nexport RUST_BACKTRACE=1\\n\\n# to catch logs generated by tracing\\nexport RUST_LOG=trace\\n```\\n\\nAnd for the one of the most obnoxious things ever, we will use a script to download\\nthe inputs instead of \u201c_clicking, opening and copying to a file_\u201d[^1]. There is\\nno need to be _fancy_, so we will adjust Python script by Martin[^2].\\n\\n```py\\n#!/usr/bin/env python3\\n\\nimport datetime\\nimport yaml\\nimport requests\\nimport sys\\n\\n\\ndef load_config():\\n with open(\\"env.yaml\\", \\"r\\") as f:\\n js = yaml.load(f, Loader=yaml.Loader)\\n return js[\\"session\\"], js[\\"year\\"]\\n\\n\\ndef get_input(session, year, day):\\n return requests.get(\\n f\\"https://adventofcode.com/{year}/day/{day}/input\\",\\n cookies={\\"session\\": session},\\n headers={\\n \\"User-Agent\\": \\"{repo} by {mail}\\".format(\\n repo=\\"gitlab.com/mfocko/advent-of-code-2022\\",\\n mail=\\"me@mfocko.xyz\\",\\n )\\n },\\n ).content.decode(\\"utf-8\\")\\n\\n\\ndef main():\\n day = datetime.datetime.now().day\\n if len(sys.argv) == 2:\\n day = sys.argv[1]\\n\\n session, year = load_config()\\n problem_input = get_input(session, year, day)\\n\\n with open(f\\"./inputs/day{day:>02}.txt\\", \\"w\\") as f:\\n f.write(problem_input)\\n\\n\\nif __name__ == \\"__main__\\":\\n main()\\n```\\n\\nIf the script is called without any arguments, it will deduce the day from the\\nsystem, so we do not need to change the day every morning. It also requires a\\nconfiguration file:\\n\\n```yaml\\n# env.yaml\\nsession: \u2039your session cookie\u203a\\nyear: 2022\\n```\\n\\n### Libraries\\n\\nLooking at the list of the libraries, I have chosen \u201ca lot\u201d of them. Let\'s walk\\nthrough each of them.\\n\\n[`tracing`] and [`tracing-subscriber`] are the crates that can be used for tracing\\nand logging of your Rust programs, there are also other crates that can help you\\nwith providing backtrace to the Sentry in case you have deployed your application\\nsomewhere and you want to watch over it. In our use case we will just utilize the\\nmacros for debugging in the terminal.\\n\\n[`thiserror`], [`anyhow`] and [`color-eyre`] are used for error reporting.\\n`thiserror` is a very good choice for libraries, cause it extends the `Error`\\nfrom the `std` and allows you to create more convenient error types. Next is\\n`anyhow` which kinda builds on top of the `thiserror` and provides you with simpler\\nerror handling in binaries[^3]. And finally we have `color-eyre` which, as I found\\nout later, is a colorful (_wink wink_) extension of `eyre` which is fork of `anyhow`\\nwhile supporting customized reports.\\n\\nIn the end I have decided to remove `thiserror` and `anyhow`, since first one is\\nsuitable for libraries and the latter was basically fully replaced by `{color-,}eyre`.\\n\\n[`regex`] and [`lazy_static`] are a very good and also, I hope, self-explanatory\\ncombination. `lazy_static` allows you to have static variables that must be initialized\\nduring runtime.\\n\\n[`itertools`] provides some nice extensions to the iterators from the `std`.\\n\\n### My own \u201clibrary\u201d\\n\\nWhen creating the crate for this year\'s Advent of Code, I have chosen a library\\ntype. Even though standard library is huge, some things might not be included and\\nalso we can follow _KISS_. I have 2 modules that my \u201clibrary\u201d exports, one for\\nparsing and one for 2D vector (that gets used quite often during Advent of Code).\\n\\nKey part is, of course, processing the input and my library exports following\\nfunctions that get used a lot:\\n\\n```rust\\n/// Reads file to the string.\\npub fn file_to_string<P: AsRef<Path>>(pathname: P) -> String;\\n\\n/// Reads file and returns it as a vector of characters.\\npub fn file_to_chars<P: AsRef<Path>>(pathname: P) -> Vec<char>;\\n\\n/// Reads file and returns a vector of parsed structures. Expects each structure\\n/// on its own line in the file. And `T` needs to implement `FromStr` trait.\\npub fn file_to_structs<P: AsRef<Path>, T: FromStr>(pathname: P) -> Vec<T>\\nwhere\\n <T as FromStr>::Err: Debug;\\n\\n/// Converts iterator over strings to a vector of parsed structures. `T` needs\\n/// to implement `FromStr` trait and its error must derive `Debug` trait.\\npub fn strings_to_structs<T: FromStr, U>(\\n iter: impl Iterator<Item = U>\\n) -> Vec<T>\\nwhere\\n <T as std::str::FromStr>::Err: std::fmt::Debug,\\n U: Deref<Target = str>;\\n\\n/// Reads file and returns it as a vector of its lines.\\npub fn file_to_lines<P: AsRef<Path>>(pathname: P) -> Vec<String>;\\n```\\n\\nAs for the vector, I went with a rather simple implementation that allows only\\naddition of the vectors for now and accessing the elements via functions `x()`\\nand `y()`. Also the vector is generic, so we can use it with any numeric type we\\nneed.\\n\\n### Skeleton\\n\\nWe can also prepare a template to quickly bootstrap each of the days. We know\\nthat each puzzle has 2 parts, which means that we can start with 2 functions that\\nwill solve them.\\n\\n```rust\\nfn part1(input: &Input) -> Output {\\n todo!()\\n}\\n\\nfn part2(input: &Input) -> Output {\\n todo!()\\n}\\n```\\n\\nBoth functions take reference to the input and return some output (in majority\\nof puzzles, it is the same type). `todo!()` can be used as a nice placeholder,\\nit also causes a panic when reached and we could also provide some string with\\nan explanation, e.g. `todo!(\\"part 1\\")`. We have not given functions a specific\\ntype and to avoid as much copy-paste as possible, we will introduce type aliases.\\n\\n```rust\\ntype Input = String;\\ntype Output = i32;\\n```\\n\\n:::tip\\n\\nThis allows us to quickly adjust the types only in one place without the need to\\ndo _regex-replace_ or replace them manually.\\n\\n:::\\n\\nFor each day we get a personalized input that is provided as a text file. Almost\\nall the time, we would like to get some structured type out of that input, and\\ntherefore it makes sense to introduce a new function that will provide the parsing\\nof the input.\\n\\n```rust\\nfn parse_input(path: &str) -> Input {\\n todo!()\\n}\\n```\\n\\nThis \u201cparser\u201d will take a path to the file, just in case we would like to run the\\nsample instead of input.\\n\\nOK, so now we can write a `main` function that will take all of the pieces and\\nrun them.\\n\\n```rust\\nfn main() {\\n let input = parse_input(\\"inputs/dayXX.txt\\");\\n\\n println!(\\"Part 1: {}\\", part_1(&input));\\n println!(\\"Part 2: {}\\", part_2(&input));\\n}\\n```\\n\\nThis would definitely do :) But we have installed a few libraries and we want to\\nuse them. In this part we are going to utilize _[`tracing`]_ (for tracing, duh\u2026)\\nand _[`color-eyre`]_ (for better error reporting, e.g. from parsing).\\n\\n```rust\\nfn main() -> Result<()> {\\n tracing_subscriber::fmt()\\n .with_env_filter(EnvFilter::from_default_env())\\n .with_target(false)\\n .with_file(true)\\n .with_line_number(true)\\n .without_time()\\n .compact()\\n .init();\\n color_eyre::install()?;\\n\\n let input = parse_input(\\"inputs/dayXX.txt\\");\\n\\n info!(\\"Part 1: {}\\", part_1(&input));\\n info!(\\"Part 2: {}\\", part_2(&input));\\n\\n Ok(())\\n}\\n```\\n\\nThe first statement will set up tracing and configure it to print out the logs to\\nterminal, based on the environment variable. We also change the formatting a bit,\\nsince we do not need all the _fancy_ features of the logger. Pure initialization\\nwould get us logs like this:\\n\\n```\\n2022-12-11T19:53:19.975343Z INFO day01: Part 1: 0\\n```\\n\\nHowever after running that command, we will get the following:\\n\\n```\\n INFO src/bin/day01.rs:35: Part 1: 0\\n```\\n\\nAnd the `color_eyre::install()?` is quite straightforward. We just initialize the\\nerror reporting by _color eyre_.\\n\\n:::warning[caution]\\n\\nNotice that we had to add `Ok(())` to the end of the function and adjust the\\nreturn type of the `main` to `Result<()>`. It is caused by the _color eyre_ that\\ncan be installed only once and therefore it can fail, that is how we got the `?`\\nat the end of the `::install` which _unwraps_ the **\xbbresult\xab** of the installation.\\n\\n:::\\n\\nOverall we will get to a template like this:\\n\\n```rust\\nuse aoc_2022::*;\\n\\nuse color_eyre::eyre::Result;\\nuse tracing::info;\\nuse tracing_subscriber::EnvFilter;\\n\\ntype Input = String;\\ntype Output = i32;\\n\\nfn parse_input(path: &str) -> Input {\\n todo!()\\n}\\n\\nfn part1(input: &Input) -> Output {\\n todo!()\\n}\\n\\nfn part2(input: &Input) -> Output {\\n todo!()\\n}\\n\\nfn main() -> Result<()> {\\n tracing_subscriber::fmt()\\n .with_env_filter(EnvFilter::from_default_env())\\n .with_target(false)\\n .with_file(true)\\n .with_line_number(true)\\n .without_time()\\n .compact()\\n .init();\\n color_eyre::install()?;\\n\\n let input = parse_input(\\"inputs/dayXX.txt\\");\\n\\n info!(\\"Part 1: {}\\", part_1(&input));\\n info!(\\"Part 2: {}\\", part_2(&input));\\n\\n Ok(())\\n}\\n```\\n\\n[^1]:\\n Copy-pasting might be a relaxing thing to do, but you can also discover\\n nasty stuff about your PC. See [this Reddit post and the comment].\\n\\n[^2]: [GitHub profile](https://github.com/martinjonas)\\n[^3]:\\n Even though you can use it even for libraries, but handling errors from\\n libraries using `anyhow` is nasty\u2026 You will be the stinky one ;)\\n\\n[_advent of code_]: https://adventofcode.com\\n[gitlab]: https://gitlab.com/mfocko/advent-of-code-2022\\n[cargo]: https://doc.rust-lang.org/cargo/\\n[`rust-analyzer`]: https://rust-analyzer.github.io/\\n[`direnv`]: https://direnv.net/\\n[`tracing`]: https://crates.io/crates/tracing\\n[`tracing-subscriber`]: https://crates.io/crates/tracing-subscriber\\n[`thiserror`]: https://crates.io/crates/thiserror\\n[`anyhow`]: https://crates.io/crates/anyhow\\n[`color-eyre`]: https://crates.io/crates/color-eyre\\n[`regex`]: https://crates.io/crates/regex\\n[`lazy_static`]: https://crates.io/crates/lazy_static\\n[`itertools`]: https://crates.io/crates/itertools\\n[this reddit post and the comment]: https://www.reddit.com/r/adventofcode/comments/zb98pn/comment/iyq0ono"}]}')}}]);