rust: The use of the Choice sort in Rust to pick out from a couple of values that would possibly now not exist

After you have the consumer’s enter, we wish to
determine a filename to put in writing the document out
as. We will both use the identify the consumer
handed in, or we will be able to attempt to use heuristics
to discover a identify from the markdown content material.

We will mix the consumer’s identify from the cli
arguments (an Choice) with the good judgment we
use as a heuristic for the markdown (additionally
an Choice).

// use `identify` if the consumer handed it in,
// differently attempt to discover a heading within the markdown
let document_title = identify.or_else(||  maybe_line.trim_start_matches("# ").to_string())

choice.or_else() returns the unique
choice if this can be a Some price, or executes
the serve as to go back a distinct Choice
if now not. So document_title is an
Choice<String> both approach and we have
coated all the conceivable situations:

  1. the consumer has handed in a identify
  2. the consumer has written content material with a heading
  3. the consumer has finished neither of those

Which leaves us to our markdown heuristic.

Markdown headings are required to have #
with no less than one area, so we will be able to flip
contents into an iterator and in finding the
first line that begins with # .

If we discover one, we wish to trim # off of
the heading to get simply the heading content material,
so we will be able to use map to function at the price
inside the Choice returned via in finding if
it exists.

contents .traces() .in finding(|v| v.starts_with("# ")) .map(|maybe_line| maybe_line.trim_start_matches("# ").to_string())

Now this code works wonderful, but it surely exposes a trojan horse
in our document dealing with.

If we write_all to the document, that strikes the
inner cursor to the top of that content material. So
after we run our code now, contents is
skipping the primary # bytes, which means that our
heuristic will simplest in finding the second one heading in
the document.

To mend this, we will be able to carry within the std::io::Search
trait, and search to the start of the document.

let mut contents = String::new(); started(0))?;
document.read_to_string(&mut contents)?;