<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>[wgml.pl]</title>
    <description>Random bits and pieces</description>
    <link>https://wgml.pl</link>
    <atom:link href="https://wgml.pl/feed.xml" rel="self" type="application/rss+xml" />
    
      <item>
        <title>The other missing pointer type -- `object_ptr&lt;T&gt;`</title>
        <description>&lt;p&gt;There are three smart pointers in &lt;code&gt;std&lt;/code&gt; already: &lt;code&gt;unique_ptr&lt;/code&gt;, &lt;code&gt;shared_ptr&lt;/code&gt; and &lt;code&gt;weak_ptr&lt;/code&gt;.
A couple of years ago article was published, presenting &lt;code&gt;value_ptr&lt;/code&gt; &lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;, aka. &lt;em&gt;the missing smart pointer&lt;/em&gt;. Here I would like discuss the other &lt;em&gt;(sort of still)&lt;/em&gt; missing &lt;em&gt;(not so)&lt;/em&gt; smart pointer – &lt;code&gt;observer_ptr&lt;/code&gt;.&lt;/p&gt;

&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#what-is-observer_ptrt&quot; id=&quot;markdown-toc-what-is-observer_ptrt&quot;&gt;What is &lt;code&gt;observer_ptr&amp;lt;T&amp;gt;&lt;/code&gt;?&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#a-new-hope&quot; id=&quot;markdown-toc-a-new-hope&quot;&gt;A new hope&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#when-to-use-it&quot; id=&quot;markdown-toc-when-to-use-it&quot;&gt;When to use it&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#limitations&quot; id=&quot;markdown-toc-limitations&quot;&gt;Limitations&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#valid_ptrt&quot; id=&quot;markdown-toc-valid_ptrt&quot;&gt;&lt;code&gt;valid_ptr&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#postlude&quot; id=&quot;markdown-toc-postlude&quot;&gt;Postlude&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;what-is-observer_ptrt&quot;&gt;What is &lt;code&gt;observer_ptr&amp;lt;T&amp;gt;&lt;/code&gt;?&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;observer_ptr&lt;/code&gt; is a recent addition to &lt;code&gt;c++&lt;/code&gt; ecosystem – it was appended into &lt;em&gt;Library Fundamentals TS&lt;/em&gt; in its second version. It means that if you would like to use it in your code, you are bound to the &lt;code&gt;std::experimental&lt;/code&gt; namespace for some time, until, or &lt;em&gt;if&lt;/em&gt;, it is going to be merged into the standard.&lt;/p&gt;

&lt;p&gt;The purpose of &lt;code&gt;observer_ptr&lt;/code&gt; is to provide:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;a near drop-in replacement for raw pointer types, with the advantage that, as a vocabulary type, it indicates its intended use without need for detailed analysis by code readers. &lt;sup id=&quot;fnref:2&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:2&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here is the thing – I think it is not really a drop-in replacement for raw pointers; and its vocabulary type is confusing and does not indicate its intend clearly. But we will get back to that.&lt;/p&gt;

&lt;p&gt;The idea behind &lt;code&gt;observer_ptr&lt;/code&gt; is to provide an interface that indicates the pointer that is being passed is considered read-only (pointer, not the object itself) and there will be no intention of extending the underlying object lifetime or stealing its ownership. If you use &lt;code&gt;std::shared_ptr&amp;lt;Something&amp;gt; const&amp;amp;&lt;/code&gt; in the function parameter list, you can use &lt;code&gt;observer_ptr&amp;lt;Something&amp;gt;&lt;/code&gt; instead.&lt;/p&gt;

&lt;p&gt;Why not simply use &lt;code&gt;Something*&lt;/code&gt; then? You &lt;em&gt;could&lt;/em&gt; but you probably shouldn’t. Raw pointers inject many quirks into the code – can be incremented and decremented, compared using &lt;code&gt;&amp;lt;&lt;/code&gt;, converted into &lt;code&gt;void*&lt;/code&gt;, casted. Additionally, those open up new questions, most importantly: &lt;em&gt;“who owns the object?”&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;When using &lt;code&gt;observer_ptr&lt;/code&gt;, you are safe from the quirks. You get type safety, no silly &lt;code&gt;ptr++&lt;/code&gt; and &lt;code&gt;(void*) ptr&lt;/code&gt;. Unless you do &lt;code&gt;ptr.get()&lt;/code&gt;, you should be good.&lt;/p&gt;

&lt;p&gt;However, &lt;code&gt;observer_ptr&lt;/code&gt; have some quirks on its own. Let’s try using it to show them all in context.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;experimental/memory&amp;gt;
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;memory&amp;gt;

struct Resource
{
  int value = 42;
};

std::unique_ptr&amp;lt;Resource&amp;gt; create_resource()
{
  return std::make_unique&amp;lt;Resource&amp;gt;();
}

void use_resource(std::unique_ptr&amp;lt;Resource&amp;gt; const&amp;amp; resource)
{
  std::cout &amp;lt;&amp;lt; &quot;value=&quot; &amp;lt;&amp;lt; resource-&amp;gt;value &amp;lt;&amp;lt; std::endl;
}

void observe_resource(std::experimental::observer_ptr&amp;lt;Resource&amp;gt; resource)
{
  std::cout &amp;lt;&amp;lt; &quot;value=&quot; &amp;lt;&amp;lt; resource-&amp;gt;value &amp;lt;&amp;lt; std::endl;
}

int main()
{
  auto res = create_resource();
  use_resource(res);
  observe_resource(std::experimental::make_observer(res.get()));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When I first learned about &lt;code&gt;observer_ptr&lt;/code&gt; and tried to use it, I ended up writing similar code and started thinking: &lt;em&gt;but… why would you do that…?&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;I &lt;em&gt;really&lt;/em&gt; don’t like &lt;code&gt;std::experimental::make_observer(resource.get())&lt;/code&gt; to create the wrapper for the pointer. It should be as easy as &lt;code&gt;make_observer(resource)&lt;/code&gt;, at worst. At best it should have implicit conversions from all smart pointers (I would consider a smart pointer as some type that provides &lt;code&gt;operator-&amp;gt;&lt;/code&gt;, &lt;code&gt;operator*&lt;/code&gt;, and possibly &lt;code&gt;get()&lt;/code&gt;.) and raw pointer of given type.
It shouldn’t have &lt;code&gt;release()&lt;/code&gt; member method, which, in smart pointer context, is related to releasing the ownership of the object. &lt;code&gt;observer_ptr&lt;/code&gt; does not own anything.&lt;/p&gt;

&lt;p&gt;On top of that, it requires a better name. &lt;code&gt;observer&lt;/code&gt; implies relation to the Observer pattern, while, in fact, has nothing to do with it.
I’m somewhere between &lt;code&gt;ptr_view&amp;lt;T&amp;gt;&lt;/code&gt; (&lt;em&gt;Just like the &lt;code&gt;string_view&lt;/code&gt;.&lt;/em&gt;) and &lt;code&gt;ptr&amp;lt;T&amp;gt;&lt;/code&gt; (&lt;em&gt;It’s just a pointer, man.&lt;/em&gt;) myself. But there are &lt;a href=&quot;https://www.reddit.com/r/cpp/comments/808c5z/bikeshedding_time_poll_for_a_new_name_for/&quot;&gt;more&lt;/a&gt; ideas. &lt;a href=&quot;https://github.com/tvaneerd/isocpp/blob/master/observer_ptr.md#a-list-of-names&quot;&gt;A lot more&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Different people have different concerns regarding the design of the type. For example, there is that one paper named &lt;a href=&quot;http://wg21.link/P1408&quot;&gt;&lt;em&gt;Abandon observer_ptr&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;a-new-hope&quot;&gt;A new hope&lt;/h2&gt;

&lt;p&gt;All in all, we can do better than that. Actually, we already do. There are 3rd-party implementations available, like &lt;a href=&quot;https://github.com/anthonywilliams/object_ptr/blob/master/object_ptr.hpp&quot;&gt;this one&lt;/a&gt; from Anthony Williams:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;named it &lt;code&gt;object_ptr&lt;/code&gt; instead of &lt;code&gt;observer_ptr&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;dropped the &lt;code&gt;release()&lt;/code&gt; member method&lt;/li&gt;
  &lt;li&gt;made it construct implicitly from other pointer types&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I like those changes in design; and it is just one header file so you can copy it into your code base and start using it now.
However, even though &lt;code&gt;object_ptr&lt;/code&gt; is a better name already, I still prefer to do:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;object_ptr.hpp&amp;gt;

namespace project::primary::ns {
template&amp;lt;typename T&amp;gt;
using ptr_view = jss::object_ptr&amp;lt;T&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I’ll stick to the &lt;code&gt;ptr_view&lt;/code&gt; for the rest of the post for clarity sake. With that, our example can become as simple as:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;void use_resource(ptr_view&amp;lt;Resource&amp;gt; resource)
{
  std::cout &amp;lt;&amp;lt; &quot;value=&quot; &amp;lt;&amp;lt; resource-&amp;gt;value &amp;lt;&amp;lt; std::endl;
}

int main()
{
  auto shared_res = std::make_shared&amp;lt;Resource&amp;gt;();

  use_resource(shared_res);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Constructs implicitly from the smart pointer, can be passed by value – just like the &lt;code&gt;string_view&lt;/code&gt;. You can play with the example &lt;a href=&quot;https://wandbox.org/permlink/DLdL62Ln3NfWgGkw&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I just complained about using &lt;code&gt;get()&lt;/code&gt; so let us dive into some use cases.&lt;/p&gt;

&lt;h2 id=&quot;when-to-use-it&quot;&gt;When to use it&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;ptr_view&lt;/code&gt; enables developers to build more readable and generic interfaces, no longer bound to specific pointer type.
Most of the time, it does not matter whether the &lt;code&gt;std::shared_ptr&amp;lt;T&amp;gt;&lt;/code&gt; or &lt;code&gt;T*&lt;/code&gt;, or &lt;code&gt;boost::shared_ptr&amp;lt;T&amp;gt;&lt;/code&gt;, or &lt;code&gt;my::better_ptr&amp;lt;T&amp;gt;&lt;/code&gt; is being provided by the caller. If all you require is access to the underlying object, dependency on the specific type can be removed.
Not only the function is going to end up being more generic but also a lot more readable.&lt;/p&gt;

&lt;p&gt;For &lt;code&gt;something(std::shared_ptr&amp;lt;T&amp;gt; const&amp;amp;, ...)&lt;/code&gt; –&amp;gt; &lt;code&gt;something(ptr_view&amp;lt;T&amp;gt;, ...)&lt;/code&gt; gets rid of the question &lt;em&gt;who owns the object now?&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;For &lt;code&gt;something_else(T* const, T* const, ...)&lt;/code&gt; –&amp;gt; &lt;code&gt;something_else(ptr_view&amp;lt;T&amp;gt;, ptr_view&amp;lt;T&amp;gt;, ...)&lt;/code&gt; you need not to worry if it is range or two objects.&lt;/p&gt;

&lt;p&gt;Same applies for &lt;code&gt;std::unique_ptr&lt;/code&gt; with custom deleter defined. By default, it is defined as &lt;code&gt;std::default_delete&amp;lt;T&amp;gt;&lt;/code&gt; and can be left out of
type declarations.  However, sometimes it might be necessary to provide dedicated deleter, e.g. for resources that does not follow RAII technique.
However, &lt;code&gt;ptr_view&lt;/code&gt; does not care about how the object have to be disposed on destruction, thus the deleter info is redundant, simplifying the code even more. Let’s consider following snippet:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;struct LoggingDeleter
{
  template&amp;lt;typename T&amp;gt;
  void operator()(T* p) const
  {
    std::clog &amp;lt;&amp;lt; &quot;freeing p=&quot; &amp;lt;&amp;lt; p &amp;lt;&amp;lt; std::endl;
    delete p;
  }
};

void use_resource(std::unique_ptr&amp;lt;Resource&amp;gt; const&amp;amp; resource)
{
  std::cout &amp;lt;&amp;lt; &quot;value=&quot; &amp;lt;&amp;lt; resource-&amp;gt;value &amp;lt;&amp;lt; std::endl;
}

void use_resource(std::unique_ptr&amp;lt;Resource, LoggingDeleter&amp;gt; const&amp;amp; resource)
{
  std::cout &amp;lt;&amp;lt; &quot;value=&quot; &amp;lt;&amp;lt; resource-&amp;gt;value &amp;lt;&amp;lt; std::endl;
}

int main()
{
  auto res = std::make_unique&amp;lt;Resource&amp;gt;();
  std::unique_ptr&amp;lt;Resource, LoggingDeleter&amp;gt; debug_resource{new Resource{}, LoggingDeleter{}};

  use_resource(res);
  use_resource(debug_resource);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As already mentioned, &lt;code&gt;ptr_view&lt;/code&gt; does not care about object destruction, so &lt;code&gt;void use_resource(ptr_view&amp;lt;Resource&amp;gt;)&lt;/code&gt; can handle all invocations, &lt;a href=&quot;https://wandbox.org/permlink/PDbASnnOl7EwGG9p&quot;&gt;like so&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ptr_view&lt;/code&gt; behaves also a bit like &lt;code&gt;std::weak_ptr&lt;/code&gt;’s &lt;em&gt;dumber&lt;/em&gt; friend - but in a good way. Often you can be bound to use &lt;code&gt;std::weak_ptr&amp;lt;T&amp;gt;&lt;/code&gt; as a mitigation for possible ownership cycles. However, assuming one of the objects is guaranteed to outlive the other one, it would be sufficient to store non-owning pointer to the longer-living one, like &lt;code&gt;T*&lt;/code&gt;. Or, you guessed it, &lt;code&gt;ptr_view&amp;lt;T&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;struct Task;
struct Executor
{
  void work_until_done();
  void notify_done(ptr_view&amp;lt;Task&amp;gt;);
  void queue(std::shared_ptr&amp;lt;Task&amp;gt;);

private:
  std::vector&amp;lt;std::shared_ptr&amp;lt;Task&amp;gt;&amp;gt; _tasks;
};

struct Task
{
  explicit Task(ptr_view&amp;lt;Executor&amp;gt; e) : _executor(e) {}

  void notify_done()
  {
    _executor-&amp;gt;notify_done(this);
  }

private:
  ptr_view&amp;lt;Executor&amp;gt; _executor;
};

int main()
{
  auto executor = std::make_unique&amp;lt;Executor&amp;gt;();
  for (std::size_t i = 0; i &amp;lt; 5; ++i)
    executor-&amp;gt;queue(std::make_shared&amp;lt;Task&amp;gt;(executor));
  executor-&amp;gt;work_until_done();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is no point in using &lt;code&gt;std::weak_ptr&lt;/code&gt; if you are guaranteed the &lt;code&gt;Executor&lt;/code&gt; will outlive all the &lt;code&gt;Task&lt;/code&gt; objects – and it is quite possible it will be the case in most of the implementations.&lt;/p&gt;

&lt;p&gt;Of course, we can get back to the discussion that we can just use &lt;code&gt;Executor*&lt;/code&gt; but it will be as less-safe, less-readable and less-explicit compared to vocabulary type like &lt;code&gt;ptr_view&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;limitations&quot;&gt;Limitations&lt;/h2&gt;

&lt;p&gt;For &lt;code&gt;ptr_view&lt;/code&gt; to be used in as much contexts as possible, the usage itself should be frictionless. Unfortunately, it is not the case yet.&lt;/p&gt;

&lt;p&gt;Let us consider some &lt;code&gt;check_resource&lt;/code&gt; function that takes pointer to arbitrary resource and verifies if the resource is accessible (&lt;code&gt;!= nullptr&lt;/code&gt;, for simplicity).&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;struct Filesystem
{...};

struct Network
{...};

template&amp;lt;typename Res&amp;gt;
bool check_resource(ptr_view&amp;lt;Res&amp;gt; resource)
{
  return resource != nullptr;
}

int main()
{
  auto fs = std::make_shared&amp;lt;Filesystem&amp;gt;();
  auto net = std::make_unique&amp;lt;Network&amp;gt;();

  check_resource(fs);
  check_resource(net);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Compilation attempt results in following error, plainly stating &lt;code&gt;object_ptr&lt;/code&gt; cannot be matched against some arbitrary smart pointers.&lt;/p&gt;

&lt;details open=&quot;open&quot;&gt;
    &lt;summary&gt;Output&lt;/summary&gt;
    &lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;prog.cc:24:3: error: no matching function for call to &amp;apos;check_resource&amp;apos;
  check_resource(fs);
  ^~~~~~~~~~~~~~
prog.cc:14:6: note: candidate template ignored: could not match &amp;apos;object_ptr&amp;apos; against &amp;apos;shared_ptr&amp;apos;
bool check_resource(ptr_view&amp;lt;Res&amp;gt; resource)
     ^
prog.cc:25:3: error: no matching function for call to &amp;apos;check_resource&amp;apos;
  check_resource(net);
  ^~~~~~~~~~~~~~
prog.cc:14:6: note: candidate template ignored: could not match &amp;apos;object_ptr&amp;apos; against &amp;apos;unique_ptr&amp;apos;
bool check_resource(ptr_view&amp;lt;Res&amp;gt; resource)
     ^
2 errors generated.&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;

&lt;p&gt;&lt;code&gt;CTAD&lt;/code&gt;&lt;sup id=&quot;fnref:3&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:3&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt; and user-defined deduction guides could help there but, well, those are for classes only. There was a &lt;a href=&quot;https://wg21.link/p1167&quot;&gt;paper&lt;/a&gt; to allow deduction guides for functions – I don’t know what feedback it received though.&lt;/p&gt;

&lt;p&gt;For now, we can avoid such issues with either specifying underlying &lt;code&gt;element_type&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;check_resource&amp;lt;Network&amp;gt;(net);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;or with intermediate function step, accepting &lt;em&gt;anything&lt;/em&gt; and forwarding only those types that are convertible to &lt;code&gt;ptr_view&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;template&amp;lt;typename ResPtr&amp;gt;
bool check_resource(ResPtr const&amp;amp; resource)
{
  return impl::check_resource&amp;lt;typename std::pointer_traits&amp;lt;ResPtr&amp;gt;::element_type&amp;gt;(resource);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While not perfect, both implementations manage to do the job and result in &lt;em&gt;sort-of-readable&lt;/em&gt; compiler errors when misused. Check out the full example &lt;a href=&quot;https://wandbox.org/permlink/C3WErlTmlbNn5HDh&quot;&gt;there&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;valid_ptrt&quot;&gt;&lt;code&gt;valid_ptr&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;One possible extension of the non-owning pointer could be a &lt;code&gt;valid_ptr&lt;/code&gt;, that is pointing to some existing object, and never to the &lt;code&gt;nullptr&lt;/code&gt;.
It is quite simple to implement on top of the &lt;code&gt;jss::object_ptr&lt;/code&gt; class, all that is required to add is some initial checks in the constructors.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;...
explicit valid_ptr(T* ptr) : _ptr(ptr)
{
  assert_valid();
}
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That immediately leads to a discussion what should be done in case &lt;code&gt;ptr == nullptr&lt;/code&gt;. &lt;code&gt;assert_valid()&lt;/code&gt; can throw exception on invalid pointer or truly &lt;code&gt;assert&lt;/code&gt; that condition and terminate on fail. That would be a question for a long and, probably, unsettlementable discussion.&lt;/p&gt;

&lt;p&gt;However, such design might lead to assumptions that the pointer is always valid, while, in fact, it is just as dumb as &lt;code&gt;ptr_view&lt;/code&gt;. It is impossible to guarantee validity without the ownership. And it is the caller role to do so.&lt;/p&gt;

&lt;p&gt;With that in mind, &lt;code&gt;valid_ptr&lt;/code&gt; becomes more of a implicit null-check of the argument provided. Maybe it is worth it but there might a better ideas how to solve the parameter nullability problem.&lt;/p&gt;

&lt;h2 id=&quot;postlude&quot;&gt;Postlude&lt;/h2&gt;
&lt;p&gt;As of today, I’m sort of in the &lt;em&gt;Almost Always &lt;code&gt;ptr_view&lt;/code&gt;&lt;/em&gt; team. It’s just more fit for the use case than &lt;code&gt;shared_ptr&amp;lt;T&amp;gt; const&amp;amp;&lt;/code&gt; and &lt;code&gt;T*&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I hope we get it merged into the standard someday; however, if I am to use it in most contexts, it &lt;em&gt;really&lt;/em&gt; should get a better (pronounced – shorter) name – I feel like 6-8 characters is the most I can invest to use it myself. Any more and the code readability will suffer.
&lt;code&gt;CTAD&lt;/code&gt; for functions would be fun, too.&lt;/p&gt;

&lt;p&gt;I’m sticking to 3rd-party implementation, for now.&lt;/p&gt;

&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;&lt;a href=&quot;https://hackernoon.com/value-ptr-the-missing-c-smart-pointer-1f515664153e&quot;&gt;value_ptr — The Missing C++ Smart-pointer&lt;/a&gt; &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:2&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;&lt;a href=&quot;https://en.cppreference.com/w/cpp/experimental/observer_ptr&quot;&gt;std::experimental::observer_ptr&lt;/a&gt; &lt;a href=&quot;#fnref:2&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:3&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;&lt;a href=&quot;https://en.cppreference.com/w/cpp/language/class_template_argument_deduction&quot;&gt;Class template argument deduction&lt;/a&gt; &lt;a href=&quot;#fnref:3&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Mon, 23 Sep 2019 00:00:00 +0000</pubDate>
        <link>https://wgml.pl//blog/object_ptr.html</link>
        <guid isPermaLink="true">https://wgml.pl//blog/object_ptr.html</guid>
      </item>
    
      <item>
        <title>Formatting user-defined types with {fmt} library</title>
        <description>&lt;p&gt;C++ has two standardized ways of printing formatted text out already: &lt;code&gt;printf&lt;/code&gt;-family functions inherited from C and I/O streams abstraction built on &lt;code&gt;operator&amp;lt;&amp;lt;&lt;/code&gt;. Streams are considered more modern, providing type-safety and extensibility functionalities. However, &lt;code&gt;printf&lt;/code&gt; have some notable advantages, too — at the cost of lost type-safety, user can use an interface that looks familiar to almost all developers, allowing for some ways of localization and more readable syntax.
And then, there is &lt;code&gt;{fmt}&lt;/code&gt; — yet another text formatting library, inspired by design already available in languages like &lt;a href=&quot;https://www.python.org/dev/peps/pep-3101/&quot;&gt;Python&lt;/a&gt; and &lt;a href=&quot;https://doc.rust-lang.org/std/fmt/index.html&quot;&gt;Rust&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Perhaps it’s just &lt;a href=&quot;https://xkcd.com/927/&quot;&gt;yet another standard to compete&lt;/a&gt; but, with an ambition to support most of the advantages of both mentioned methods, and with process of standardization being already &lt;a href=&quot;http://wg21.link/p0645&quot;&gt;in progress&lt;/a&gt;, it is worth looking into.&lt;/p&gt;

&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#quick-look-at-fmt&quot; id=&quot;markdown-toc-quick-look-at-fmt&quot;&gt;Quick look at &lt;code&gt;{fmt}&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#printing-out-a-custom-type&quot; id=&quot;markdown-toc-printing-out-a-custom-type&quot;&gt;Printing out a custom type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#specifying-formatting-for-user-defined-types&quot; id=&quot;markdown-toc-specifying-formatting-for-user-defined-types&quot;&gt;Specifying formatting for user-defined types&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#postlude&quot; id=&quot;markdown-toc-postlude&quot;&gt;Postlude&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;quick-look-at-fmt&quot;&gt;Quick look at &lt;code&gt;{fmt}&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;{fmt}&lt;/code&gt; library is available on &lt;a href=&quot;https://github.com/fmtlib/fmt&quot;&gt;Github&lt;/a&gt; for quite some time already. It provides API similar to &lt;code&gt;str.format()&lt;/code&gt; from Python 3, far closer to &lt;code&gt;printf(...)&lt;/code&gt; than &lt;code&gt;std::cout &amp;lt;&amp;lt; ...&lt;/code&gt; at the first glance. However, it also enforces type-safety and allows for extending to non-standard types, what makes it almost a silver bullet for text formatting in C++.&lt;/p&gt;

&lt;p&gt;Based on the mandatory &lt;em&gt;Hello world&lt;/em&gt; example, use of the library may look like so:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-Cpp&quot;&gt;fmt::print(&quot;Hello, {}!\n&quot;, name);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;{fmt}&lt;/code&gt; supports positional arguments, allowing user to manipulate the order in which arguments are used in the message:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-Cpp&quot;&gt;std::string message = fmt::format(&quot;{1} years ago, {0} was born.&quot;, name, age);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Formatting is also possible (well, that is the point, after all). If you want to print a number to the screen and align it to the right with the width of 7 characters, that is the syntax:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-Cpp&quot;&gt;fmt::print(&quot;The number is {:&amp;gt;7}!\n&quot;, number);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course, this can become far more &lt;em&gt;perl-y&lt;/em&gt; in style. This is a valid format:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-Cpp&quot;&gt;fmt::print(&quot;The number is {0:.&amp;gt;+#{1}.{2}G}\n&quot;, 42.123, 20, 10);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Translating it to human — the zeroth argument (&lt;code&gt;0:&lt;/code&gt;) will be aligned to the right (&lt;code&gt;&amp;gt;&lt;/code&gt;), with dots filling empty space (&lt;code&gt;.&lt;/code&gt;), the sign will be printed out (&lt;code&gt;+&lt;/code&gt;) no matter plus or minus, the number will be put in &lt;em&gt;general&lt;/em&gt; format (&lt;code&gt;G&lt;/code&gt;) unless it is too large, then it will be displayed using exponent notation. Trailing zeros will not be removed because of the alternate form (&lt;code&gt;#&lt;/code&gt;). Width and precision are configured by first (&lt;code&gt;{1}&lt;/code&gt;) and second (&lt;code&gt;{2}&lt;/code&gt;) argument.
Fortunately, you can look up the syntax in the &lt;a href=&quot;http://fmtlib.net/latest/syntax.html&quot;&gt;official docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;And the result?&lt;/p&gt;

&lt;details open=&quot;open&quot;&gt;
    &lt;summary&gt;Output&lt;/summary&gt;
    &lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;The number is ........+42.12300000&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;

&lt;p&gt;All in all, I suggest not to overcomplicate the syntax on your end unless you want your code to become write-only.&lt;/p&gt;

&lt;h2 id=&quot;printing-out-a-custom-type&quot;&gt;Printing out a custom type&lt;/h2&gt;

&lt;p&gt;One neat feature of &lt;code&gt;{fmt}&lt;/code&gt; is the possibility to extend it for user-defined types, similarly to the convention used when overloading &lt;code&gt;operator&amp;lt;&amp;lt;&lt;/code&gt; for such types.&lt;/p&gt;

&lt;p&gt;For example, given the simple &lt;code&gt;complex&lt;/code&gt; type, instead of defining the formatting in every place where the objects are printed out, one can specify formatter for the type and use it without any hassle.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;fmt/format.h&amp;gt;

struct complex
{
  double a;
  double b;
};

template&amp;lt;&amp;gt;
struct fmt::formatter&amp;lt;complex&amp;gt;
{
  template&amp;lt;typename ParseContext&amp;gt;
  constexpr auto parse(ParseContext&amp;amp; ctx);

  template&amp;lt;typename FormatContext&amp;gt;
  auto format(complex const&amp;amp; number, FormatContext&amp;amp; ctx);
};
};

int main()
{
  complex number{1, 2};
  fmt::print(&quot;The number is {0}+i{1}.\n&quot;, number.a, number.b);
  fmt::print(&quot;The number is {}.\n&quot;, number);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;User must specialize the &lt;code&gt;formatter&amp;lt;T&amp;gt;&lt;/code&gt; struct template in &lt;code&gt;fmt&lt;/code&gt; namespace with implementations of &lt;code&gt;parse&lt;/code&gt; and &lt;code&gt;format&lt;/code&gt; functions.
Provided the user wants to match the result of both lines, those two methods can be implemented as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;template&amp;lt;typename ParseContext&amp;gt;
constexpr auto fmt::formatter&amp;lt;complex&amp;gt;::parse(ParseContext&amp;amp; ctx)
{
  return ctx.begin();
}

template&amp;lt;typename FormatContext&amp;gt;
auto fmt::formatter&amp;lt;complex&amp;gt;::format(complex const&amp;amp; number, FormatContext&amp;amp; ctx)
{
  return fmt::format_to(ctx.out(), &quot;{0}+i{1}&quot;, number.a, number.b);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;parse&lt;/code&gt; assumes no formatting is specified for the type, and &lt;code&gt;format&lt;/code&gt; outputs the variable in hard-coded formatting.
In case of an error, exception will be thrown, with mostly unhelpful message, like “&lt;em&gt;unknown format specifier&lt;/em&gt;”.&lt;/p&gt;

&lt;h2 id=&quot;specifying-formatting-for-user-defined-types&quot;&gt;Specifying formatting for user-defined types&lt;/h2&gt;

&lt;p&gt;What if we want to allow the user to specify formatting for printed-out fields?&lt;/p&gt;

&lt;p&gt;Let’s look into another example. First of all, let me introduce the type.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;struct roman
{
  explicit roman(unsigned v) : value(v)
  {
    if (value == 0)
      throw std::runtime_error(&quot;0 cannot be represented&quot;);
    if (value &amp;gt; 3999)
      throw std::runtime_error(&quot;Roman value cannot exceed 3999&quot;);
  }

  unsigned const value;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It’s just a simple wrapper claiming to represent some Roman numeral. But how does it fit our use case?&lt;/p&gt;

&lt;p&gt;We might assume user would like to print out such numerals both in decimal form and in &lt;em&gt;string-like&lt;/em&gt; representation commonly associated with Roman numeric system. Then, we would like to be able to execute following program without errors:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;int main()
{
  for (unsigned i = 1; i &amp;lt; 4000; ++i)
    fmt::print(&quot;{0:d} = {0:r}\n&quot;, roman{i});
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Moreover, it would be useful to allow specifying underlying formatting for string and decimal representations — then, our testing program can take form as follows.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;int main()
{
  for (unsigned i = 1; i &amp;lt; 4000; ++i)
    fmt::print(&quot;{0:d&amp;gt;4} = {0:r.&amp;gt;16}\n&quot;, roman{i});
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first character after the &lt;code&gt;:&lt;/code&gt; defines representation that should be used and all that follows should be interpreted as underlying formatting. We will also assume &lt;code&gt;{0}&lt;/code&gt; defaults to Roman representation but without the possibility to specify the underlying formatting to make the code simpler.&lt;/p&gt;

&lt;p&gt;As previously, we have to specify specialization of &lt;code&gt;fmt::formatter&lt;/code&gt; class and implement two methods. This time, we will delegate &lt;code&gt;parse&lt;/code&gt; and &lt;code&gt;format&lt;/code&gt; calls to formatters of &lt;code&gt;std::string_view&lt;/code&gt; or &lt;code&gt;unsigned&lt;/code&gt;, depending on the formatting specified. The formatters will be members of the structure, and, because it is either one of them but never both nor none that is being used, we will utilize &lt;code&gt;std::variant&lt;/code&gt; for this.
Interface of the formatter can be now specified.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;template&amp;lt;&amp;gt;
struct fmt::formatter&amp;lt;roman&amp;gt;
{
  using unsigned_fmt = fmt::formatter&amp;lt;unsigned&amp;gt;;
  using string_view_fmt = fmt::formatter&amp;lt;std::string_view&amp;gt;;
  using underlying_formatter_type = std::variant&amp;lt;string_view_fmt, unsigned_fmt&amp;gt;;

  template&amp;lt;typename ParseContext&amp;gt;
  constexpr auto parse(ParseContext&amp;amp; ctx);

  template&amp;lt;typename FormatContext&amp;gt;
  auto format(roman const&amp;amp; number, FormatContext&amp;amp; ctx);

private:
  underlying_formatter_type underlying_formatter;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s look more closely at the &lt;code&gt;parse&lt;/code&gt; implementation first. All it needs to do is to determine which formatter should be used and forward the call to &lt;code&gt;parse&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;template&amp;lt;typename ParseContext&amp;gt;
constexpr auto parse(ParseContext&amp;amp; ctx)
{
  auto fmt_end = std::find(ctx.begin(), ctx.end(), &apos;}&apos;);
  if (fmt_end != ctx.begin())
  {
    char representation = *ctx.begin();
    if (representation == &apos;d&apos;)
      underlying_formatter = unsigned_fmt{};
    else if (representation != &apos;r&apos;)
      throw fmt::format_error(&quot;invalid roman representation&quot;);

    ctx.advance_to(std::next(ctx.begin()));
  }

  return std::visit([&amp;amp;](auto&amp;amp; fmt) { return fmt.parse(ctx); }, underlying_formatter);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s analyze the behavior with an example. Given we want to print a Roman number with &lt;code&gt;fmt::print(&quot;{0:r&amp;gt;16} is the number {0:d}&quot;, roman_number)&lt;/code&gt;, two &lt;code&gt;formatter&amp;lt;roman&amp;gt;&lt;/code&gt; instances will be created and &lt;code&gt;parse&lt;/code&gt; function will be called twice. First time, the input to the function will be a context with &lt;code&gt;begin&lt;/code&gt; pointing to the string of &lt;code&gt;r&amp;gt;16} is the number {0:d}&lt;/code&gt;. The second time — &lt;code&gt;d}&lt;/code&gt;. Part specifying the position is being consumed by the &lt;code&gt;fmt&lt;/code&gt; library itself. Then, user must parse the rest of the string and make sure the context is left in a valid state for any other formatters to use. In this example, in both cases we must make sure context is advanced to the &lt;code&gt;}&lt;/code&gt; character.&lt;/p&gt;

&lt;p&gt;However, all the function is doing is to determine if user asked for roman or numeric representation and call &lt;code&gt;ctx.advance_to&lt;/code&gt; pointing to the second character. We will consume only the first char, leaving the rest intact. Finally, we forward the context to &lt;code&gt;parse&lt;/code&gt; of the underlying formatter, taking care of the rest of format string.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;std::variant&lt;/code&gt; constructs with the first type specified by default so all the &lt;code&gt;parse&lt;/code&gt; is required to do is to overwrite the value in case decimal representation is specified or throw an exception when erroneous formatting is found.&lt;/p&gt;

&lt;p&gt;Next, &lt;code&gt;format&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;template&amp;lt;typename FormatContext&amp;gt;
auto format(roman const&amp;amp; number, FormatContext&amp;amp; ctx)
{
  return std::visit(formatting_visitor&amp;lt;FormatContext&amp;gt;{number, ctx}, underlying_formatter);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We just forward the call to visitor:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;namespace romans {
struct numeral
{
  char repr[3];
  unsigned value;
};

constexpr std::array&amp;lt;numeral, 13&amp;gt; numerals = {{
    {&quot;M&quot;, 1000}, {&quot;CM&quot;, 900}, {&quot;D&quot;, 500}, {&quot;CD&quot;, 400},
    {&quot;C&quot;, 100}, {&quot;XC&quot;, 90}, {&quot;L&quot;, 50}, {&quot;XL&quot;, 40},
    {&quot;X&quot;, 10}, {&quot;IX&quot;, 9}, {&quot;V&quot;, 5}, {&quot;IV&quot;, 4}, {&quot;I&quot;, 1}
  }};
}  // namespace romans

template&amp;lt;typename FormatContext&amp;gt;
struct formatting_visitor
{
  formatting_visitor(roman const&amp;amp; number, FormatContext&amp;amp; ctx) : number(number), ctx(ctx)
  {}

  void operator()(string_view_fmt&amp;amp; f) const
  {
    unsigned value = number.value;
    std::string buffer;

    buffer.reserve(16);  // romans are no longer that 15 chars
    for (auto const&amp;amp; [repr, v] : romans::numerals)
    {
      while (value &amp;gt;= v)
      {
        buffer.append(repr);
        value -= v;
      }
    }

    ctx.advance_to(f.format(buffer, ctx));
  }

  void operator()(unsigned_fmt&amp;amp; f) const
  {
    ctx.advance_to(f.format(number.value, ctx));
  }

private:
  roman const&amp;amp; number;
  FormatContext&amp;amp; ctx;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In both possible cases, the function calls underlying &lt;code&gt;format&lt;/code&gt; with value to be printed out and context as arguments. Then, the output iterator must be adjusted, so &lt;code&gt;advance_to&lt;/code&gt; is called with the result. Similarly, our &lt;code&gt;format&lt;/code&gt; returns &lt;code&gt;ctx.out()&lt;/code&gt;.
In case of decimal representation, we can simply extract the value from number; for Roman representation, we execute conversion algorithm and that’s why we even need the struct instead of simpler lambda.&lt;/p&gt;

&lt;p&gt;Finally, we can check the results.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;   1 = ...............I
   2 = ..............II
...
3998 = .....MMMCMXCVIII
3999 = .......MMMCMXCIX
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It seems everything worked as expected. If you are interested in the full source code of the example, you can find it and play with it on the &lt;a href=&quot;https://wandbox.org/permlink/gxTuRDykK1aUrDER&quot;&gt;Wandbox&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;postlude&quot;&gt;Postlude&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;{fmt}&lt;/code&gt; is a neat library, easy to use from user perspective, and providing syntax that is new for C++ but already established in other programming languages. Perhaps it is a bit more demanding when formatting for custom type is to be specified but it should be a rare case to build complex formatting outside of the standard library.&lt;/p&gt;

&lt;p&gt;It has a lot more to offer than was described in this post. It &lt;a href=&quot;https://github.com/fmtlib/fmt#benchmarks&quot;&gt;claims&lt;/a&gt; to be faster than alternatives both in compile and run times, without bloating application code, too.&lt;/p&gt;

&lt;p&gt;It also supports formatting time and date, &lt;code&gt;std::chrono&lt;/code&gt; types (it is &lt;a href=&quot;https://wg21.link/p1361&quot;&gt;already proposed&lt;/a&gt; for merge into the standard), and more. Check out &lt;a href=&quot;http://fmtlib.net/latest/index.html&quot;&gt;the official documentation&lt;/a&gt; for details. Even though not everything is going to be merged into the standard, I’m still happy to see &lt;code&gt;std::format&lt;/code&gt; in the next edition of C++, probably even in &lt;code&gt;c++20&lt;/code&gt;.&lt;/p&gt;
</description>
        <pubDate>Fri, 01 Mar 2019 00:00:00 +0000</pubDate>
        <link>https://wgml.pl//blog/formatting-user-defined-types-fmt.html</link>
        <guid isPermaLink="true">https://wgml.pl//blog/formatting-user-defined-types-fmt.html</guid>
      </item>
    
      <item>
        <title>Getting started with VPS</title>
        <description>&lt;p&gt;Recently, I decided to organize how I host and manage this website.
Until now, I was using tangled net of services hidden behind the idea of simplicity. I used Github Pages for hosting but wanted to keep my own domain. Easily done, unless you want to also have HTTPS – I had to use Cloudflare for DNS and tunneling traffic via theirs server for SSL. My domain provider didn’t support managing mail communication with custom DNS addresses, so I configured &lt;a href=&quot;https://www.mailgun.com/&quot;&gt;mailgun&lt;/a&gt; to do it instead. On top of that, I maintained &lt;em&gt;development&lt;/em&gt; box with its own subdomain but without tunneling the traffic via Cloudflare. It was a mess. The time has come to sort things out.&lt;/p&gt;

&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#basics&quot; id=&quot;markdown-toc-basics&quot;&gt;Basics&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#blog&quot; id=&quot;markdown-toc-blog&quot;&gt;Blog&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#deploying-content-changes-automatically&quot; id=&quot;markdown-toc-deploying-content-changes-automatically&quot;&gt;Deploying content changes automatically&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#lets-encrypt&quot; id=&quot;markdown-toc-lets-encrypt&quot;&gt;Let’s Encrypt&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#summary&quot; id=&quot;markdown-toc-summary&quot;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;basics&quot;&gt;Basics&lt;/h2&gt;

&lt;p&gt;I am using &lt;a href=&quot;https://jekyllrb.com/&quot;&gt;Jekyll&lt;/a&gt; to generate static website from Markdown and HTML snippets. It is &lt;em&gt;really&lt;/em&gt; great. Those are still being hosted by &lt;a href=&quot;https://github.com/wgml/wgml.github.io&quot;&gt;Github repository&lt;/a&gt; but I no longer care for Github Pages – it’s only reason for existence is to redirect to mine domain. And one more thing but let’s not get ahead of ourselves.&lt;/p&gt;

&lt;p&gt;I host the content on Vultr $5/mo VPS. 1 GB of RAM + 25 GB of SSD storage is more than enough to support such endeavour and allow me to play with side projects on the same machine. Theirs $2.5/mo would be probably sufficient, too. Decided to use Ubuntu just for the library of guides already available on Vultr and DigitalOcean for that distribution.&lt;/p&gt;

&lt;h2 id=&quot;blog&quot;&gt;Blog&lt;/h2&gt;
&lt;p&gt;I installed nginx, configured it, normal stuff. The configuration was dead-simple.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-nginx&quot;&gt;server {
    root /var/www/wgml.pl/html;
    index index.html;
    error_page 404 /404.html;

    server_name wgml.pl www.wgml.pl;

    location / {
        try_files $uri $uri/ =404;
    }

    listen 80;
    listen [::]:80;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I also installed a few necessary packages, like git, vim, jekyll. Built blog with &lt;code&gt;jekyll build --destination /var/www/wgml.pl&lt;/code&gt; and, voilà, I could see my website under &lt;code&gt;http://wgml.pl&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Yeah, at least two issues with that setup:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;I do not want to manually deploy the site every time I commit to repository&lt;/li&gt;
  &lt;li&gt;Where is that HTTPS lock icon?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Fortunately, we will solve both of them in a minute.&lt;/p&gt;

&lt;h2 id=&quot;deploying-content-changes-automatically&quot;&gt;Deploying content changes automatically&lt;/h2&gt;

&lt;p&gt;I googled a bit for ideas on how to automate website deployment. It seems there are at least two interesting solutions. Jekyll docs &lt;a href=&quot;https://jekyllrb.com/docs/deployment/automated/&quot;&gt;describe&lt;/a&gt; how to use bare git repository and post-receive hooks to regenerate website on every push. You can also use Github webhooks to notify something like &lt;a href=&quot;https://github.com/developmentseed/jekyll-hook/&quot;&gt;jekyll-hook&lt;/a&gt; about changes. Both solutions work fine, I went with the second one because who would like to write two &lt;code&gt;git push&lt;/code&gt; commands every time when one is sufficient?&lt;/p&gt;

&lt;p&gt;Within a couple of minutes I prepared a bit overly complicated shell script to handle deployments.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;#/bin/bash

set -e

REPO_URL=&quot;https://github.com/wgml/wgml.github.io.git&quot;
SITE_DIR=&quot;/var/www/wgml.pl&quot;
SITE_PUBLIC_DIR=&quot;$SITE_DIR/html&quot;

cd $(mktemp -d)
git clone $REPO_URL --depth=1 --branch=master --single-branch .

HEAD=$(git rev-parse HEAD)
SITE_REV_DIR=&quot;$SITE_DIR/html-$HEAD&quot;

if [ -d &quot;$SITE_REV_DIR&quot; ];
then
  ln -sfn &quot;$SITE_REV_DIR&quot; &quot;$SITE_PUBLIC_DIR&quot;
  exit 0
else
  mkdir &quot;$SITE_REV_DIR&quot;
fi

jekyll build --destination &quot;$SITE_REV_DIR&quot; &amp;amp;&amp;amp; ln -sfn &quot;$SITE_REV_DIR&quot; &quot;$SITE_PUBLIC_DIR&quot; || rm -rf &quot;$SITE_REV_DIR&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I modified nginx configuration to expose &lt;code&gt;/update&lt;/code&gt; endpoint and forward all requests to the hook listener.&lt;/p&gt;

&lt;pre class=&quot;line-numbers&quot; data-line=&quot;7-10&quot;&gt;&lt;code class=&quot;language-nginx&quot;&gt;server {
    ...
    location / {
        try_files $uri $uri/ =404;
    }

    location /update {
        rewrite ^/update(.*) /$1 break;
        proxy_pass http://127.0.0.1:12345;
    }

    listen 80;
    listen [::]:80;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, when I do &lt;code&gt;git push&lt;/code&gt; on my local machine, changes will appear on website in a matter of seconds. Finally, I have dynamic-static website.&lt;/p&gt;

&lt;h2 id=&quot;lets-encrypt&quot;&gt;Let’s Encrypt&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://letsencrypt.org/&quot;&gt;Let’s encrypt&lt;/a&gt; is a go-to service for everyone in need of free TLS certificates and I highly recommend it.
For configuration, I  mostly followed DO &lt;a href=&quot;https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04&quot;&gt;How To Secure Nginx with Let’s Encrypt&lt;/a&gt; guide.&lt;/p&gt;

&lt;p&gt;To sum up, install LE Certbot, configure firewall, obtain your SSL certificate with something similar to:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;sudo certbot --nginx -d wgml.pl -d www.wgml.pl
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;certbot&lt;/code&gt; will attempt to renew any near-expiring certificates but make sure it will work by running&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;sudo certbot renew --dry-run
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Make sure you entered your email address while requesting certificate as Let’s Encrypt will mail you if renewal fails. 
&lt;code&gt;certbot&lt;/code&gt; modified nginx configuration on itself, &lt;code&gt;https://wgml.pl&lt;/code&gt; was available when I restarted nginx. Yay!&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;
&lt;p&gt;I managed to migrate from Github Pages into personal VPS in a matter of couple of hours. I didn’t lose ability to dynamically regenerate content on changes and SSL support. And, in addition to &lt;code&gt;DIY&lt;/code&gt; factor, hosting your own website means you no longer need to care about limitations of Github Pages.&lt;/p&gt;
</description>
        <pubDate>Fri, 15 Feb 2019 00:00:00 +0000</pubDate>
        <link>https://wgml.pl//blog/getting-started-vps.html</link>
        <guid isPermaLink="true">https://wgml.pl//blog/getting-started-vps.html</guid>
      </item>
    
  </channel>
</rss>
