Skip to main content

Fields

Struct Fields 

Source
pub struct Fields(/* private fields */);
Expand description

What a form was filled in with.

Every answer arrives as text, because that is what a control on a page produces: a number box hands back the digits that were typed, and an empty box hands back nothing at all. So a field is read through the reader that suits it, and a field holding something that field cannot be is a 400 naming it rather than a panic or a silent zero.

Implementations§

Source§

impl Fields

Source

pub fn get(&self, key: &str) -> Option<&str>

The answer as it was typed, or nothing where the form did not carry the field at all.

Source

pub fn text(&self, key: &str) -> &str

The answer as text, trimmed. A field nobody filled in is empty rather than absent, since a form that was saved answered every field it had.

Examples found in repository?
examples/library/main.rs (line 945)
943    fn lend(fields: &Fields, args: &ViewArgs, ctx: &Context) -> Result<String, ApiError> {
944        let title = args.get_or("title", "");
945        let borrower = fields.text("borrower");
946        let days = fields.integer("days")?;
947        let from = fields.date("from")?;
948        let condition = fields.text("condition").to_lowercase();
949
950        if borrower.is_empty() {
951            return Err(ApiError::bad_request("a loan needs a borrower"));
952        }
953        if days < 1 {
954            return Err(ApiError::bad_request("a loan is at least one day long"));
955        }
956        let start = days_from_civil(from).ok_or_else(|| {
957            ApiError::bad_request(format!("{from} is not a date in the calendar"))
958        })?;
959        let due = civil_from_days(start + days);
960
961        let mut books: Vec<Book> = ctx.rows(BOOKS_FILE)?;
962        let book = books
963            .iter_mut()
964            .find(|b| b.title == title)
965            .ok_or_else(|| ApiError::bad_request(format!("no book is called \"{title}\"")))?;
966        if book.lent.unwrap_or(false) {
967            return Err(ApiError::bad_request(format!("\"{title}\" is already out")));
968        }
969        book.lent = Some(true);
970        book.due = due.clone();
971        book.notes = format!("Lent to {borrower} on {from}, {condition}.");
972
973        let problems = Books.validate(&books, ctx)?;
974        if let Some(first) = problems.first() {
975            return Err(ApiError::bad_request(format!(
976                "the loan would leave row {} in a state the table refuses: {}",
977                first.line, first.message
978            )));
979        }
980
981        let text = Books
982            .serialize(&books)
983            .map_err(|e| ApiError::server(format!("could not serialize {BOOKS_FILE}: {e}")))?;
984        ctx.write(BOOKS_FILE, &text)?;
985
986        Ok(format!("\"{title}\" is out to {borrower} until {due}."))
987    }
Source

pub fn integer(&self, key: &str) -> Result<i64, ApiError>

The answer as a whole number.

Examples found in repository?
examples/library/main.rs (line 946)
943    fn lend(fields: &Fields, args: &ViewArgs, ctx: &Context) -> Result<String, ApiError> {
944        let title = args.get_or("title", "");
945        let borrower = fields.text("borrower");
946        let days = fields.integer("days")?;
947        let from = fields.date("from")?;
948        let condition = fields.text("condition").to_lowercase();
949
950        if borrower.is_empty() {
951            return Err(ApiError::bad_request("a loan needs a borrower"));
952        }
953        if days < 1 {
954            return Err(ApiError::bad_request("a loan is at least one day long"));
955        }
956        let start = days_from_civil(from).ok_or_else(|| {
957            ApiError::bad_request(format!("{from} is not a date in the calendar"))
958        })?;
959        let due = civil_from_days(start + days);
960
961        let mut books: Vec<Book> = ctx.rows(BOOKS_FILE)?;
962        let book = books
963            .iter_mut()
964            .find(|b| b.title == title)
965            .ok_or_else(|| ApiError::bad_request(format!("no book is called \"{title}\"")))?;
966        if book.lent.unwrap_or(false) {
967            return Err(ApiError::bad_request(format!("\"{title}\" is already out")));
968        }
969        book.lent = Some(true);
970        book.due = due.clone();
971        book.notes = format!("Lent to {borrower} on {from}, {condition}.");
972
973        let problems = Books.validate(&books, ctx)?;
974        if let Some(first) = problems.first() {
975            return Err(ApiError::bad_request(format!(
976                "the loan would leave row {} in a state the table refuses: {}",
977                first.line, first.message
978            )));
979        }
980
981        let text = Books
982            .serialize(&books)
983            .map_err(|e| ApiError::server(format!("could not serialize {BOOKS_FILE}: {e}")))?;
984        ctx.write(BOOKS_FILE, &text)?;
985
986        Ok(format!("\"{title}\" is out to {borrower} until {due}."))
987    }
Source

pub fn number(&self, key: &str) -> Result<f64, ApiError>

The answer as a number, whole or not.

inf and NaN parse as floats and are refused with the rest: a row holding one serialises to null, which would put a wrong value in a file rather than say the answer was no good.

Source

pub fn date(&self, key: &str) -> Result<&str, ApiError>

The answer as a YYYY-MM-DD date.

The shape is checked and the ranges with it, so nothing beyond a real month and a plausible day gets through; which days a month actually has is a calendar question, and the repository writing the date is what holds a calendar.

Examples found in repository?
examples/library/main.rs (line 947)
943    fn lend(fields: &Fields, args: &ViewArgs, ctx: &Context) -> Result<String, ApiError> {
944        let title = args.get_or("title", "");
945        let borrower = fields.text("borrower");
946        let days = fields.integer("days")?;
947        let from = fields.date("from")?;
948        let condition = fields.text("condition").to_lowercase();
949
950        if borrower.is_empty() {
951            return Err(ApiError::bad_request("a loan needs a borrower"));
952        }
953        if days < 1 {
954            return Err(ApiError::bad_request("a loan is at least one day long"));
955        }
956        let start = days_from_civil(from).ok_or_else(|| {
957            ApiError::bad_request(format!("{from} is not a date in the calendar"))
958        })?;
959        let due = civil_from_days(start + days);
960
961        let mut books: Vec<Book> = ctx.rows(BOOKS_FILE)?;
962        let book = books
963            .iter_mut()
964            .find(|b| b.title == title)
965            .ok_or_else(|| ApiError::bad_request(format!("no book is called \"{title}\"")))?;
966        if book.lent.unwrap_or(false) {
967            return Err(ApiError::bad_request(format!("\"{title}\" is already out")));
968        }
969        book.lent = Some(true);
970        book.due = due.clone();
971        book.notes = format!("Lent to {borrower} on {from}, {condition}.");
972
973        let problems = Books.validate(&books, ctx)?;
974        if let Some(first) = problems.first() {
975            return Err(ApiError::bad_request(format!(
976                "the loan would leave row {} in a state the table refuses: {}",
977                first.line, first.message
978            )));
979        }
980
981        let text = Books
982            .serialize(&books)
983            .map_err(|e| ApiError::server(format!("could not serialize {BOOKS_FILE}: {e}")))?;
984        ctx.write(BOOKS_FILE, &text)?;
985
986        Ok(format!("\"{title}\" is out to {borrower} until {due}."))
987    }
Source

pub fn iter(&self) -> impl Iterator<Item = (&str, &str)>

Every key and answer, in order.

Trait Implementations§

Source§

impl Clone for Fields

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Fields

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Fields

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.