Skip to content

Instantly share code, notes, and snippets.

@okkero
Created February 6, 2018 20:56
Show Gist options
  • Save okkero/037c62920c7ac72fa94046e3360240fd to your computer and use it in GitHub Desktop.
Save okkero/037c62920c7ac72fa94046e3360240fd to your computer and use it in GitHub Desktop.
#![feature(slice_patterns)]
type PhonebookError = String;
#[derive(Debug)]
struct PhonebookEntry
{
name: String,
phone_numbers: Vec<u32>
}
fn parse_name(unparsed_name: &str) -> Result<String, PhonebookError>
{
for c in unparsed_name.chars()
{
if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != ' '
{
return Err(format!("Invalid character {}!", c));
}
}
Ok(unparsed_name.to_string())
}
fn parse_phone_number(phone_number: &str) -> Result<u32, PhonebookError>
{
let mut result = 0;
for c in phone_number.chars()
{
let n = c as u32 - '0' as u32;
if n > 9
{
return Err(format!("Invalid character {}!", c));
}
if result == 0 && n == 0
{
return Err(String::from("Phone numbers cannot begin with zero!"));
}
result = 10 * result + n;
}
Ok(result)
}
fn parse_phone_numbers(phone_numbers: &str) -> Result<Vec<u32>, PhonebookError>
{
let split_phone_numbers = phone_numbers.split(' ');
let mut result = Vec::with_capacity(10);
for number in split_phone_numbers
{
let parsed_number = parse_phone_number(number)?;
result.push(parsed_number);
}
Ok(result)
}
fn parse_arguments(arguments: &[&str]) -> Result<PhonebookEntry, PhonebookError>
{
if let &[name, phone_numbers] = arguments
{
let parsed_name = parse_name(name)?;
let parsed_phone_numbers = parse_phone_numbers(phone_numbers)?;
Ok(PhonebookEntry
{
name: parsed_name,
phone_numbers: parsed_phone_numbers
})
}
else
{
Err(format!("Expected 2 arguments, got {}!", arguments.len()))
}
}
fn parse_line(line: &str) -> Result<PhonebookEntry, PhonebookError>
{
let arguments: Vec<&str> = line.split(": ").collect();
parse_arguments(&arguments[..])
}
fn print_result(result: &Result<PhonebookEntry, PhonebookError>)
{
match result
{
&Ok(ref entry) => println!("{:?}", entry),
&Err(ref error) => println!("Error: {}", error)
}
}
fn main()
{
print_result(&parse_line("John Doe: 1337 69 420"));
print_result(&parse_line("This is a malformed phonebook entry"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment