f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The one reader of the numbers and percentages of WordprocessingML: a decimal number (`ST_DecimalNumber`), a hex number (`ST_ShortHexNumber`,
//! `ST_LongHexNumber`), a text scale (`ST_TextScale`) and the percent of a preferred width
//! (`ST_MeasurementOrPercent` with `w:type="pct"`). Each reader takes the forms that Word for
//! Windows reads, and the place gives the range of its values. A [`PartReader`] reads them: a
//! value that does not read, or that lies outside its place's range, counts as missing, with a
//! warning.

use std::ops::RangeInclusive;

use f_office_units::scale::FIFTIETHS_PER_PERCENT;
use f_office_xml::NodeId;

use crate::params::{HEX_RADIX, MAX_CHARACTER_SCALE};
use crate::reader::PartReader;

/// Every whole number: the range of a place that takes any value of its type.
pub(crate) const ANY: RangeInclusive<i64> = i64::MIN..=i64::MAX;

/// The whole numbers from 0: the range of a count, an index or a share.
pub(crate) const NOT_NEGATIVE: RangeInclusive<i64> = 0..=i64::MAX;

/// The numbers of one octet, `ST_UcharHexNumber`, such as the tint and shade of a theme
/// color, which Word reads also when written with more digits, such as `0000BF`.
pub(crate) const UCHAR_HEX: RangeInclusive<i64> = 0..=u8::MAX as i64;

/// The numbers of two octets, `ST_ShortHexNumber`, such as `w:val` of `w:tblLook` and `w:char`
/// of `w:sym`.
pub(crate) const SHORT_HEX: RangeInclusive<i64> = 0..=u16::MAX as i64;

/// The numbers of four octets, `ST_LongHexNumber`, such as the revision IDs of a run.
pub(crate) const LONG_HEX: RangeInclusive<i64> = 0..=u32::MAX as i64;

/// The text scales, in percent, that F-Office draws. The schema also takes 0, which no
/// rendering measured.
const TEXT_SCALES: RangeInclusive<i64> = 1..=MAX_CHARACTER_SCALE;

impl PartReader<'_> {
    /// The number of the attribute `name` of `node`, as [`decimal`] reads it, when it lies in
    /// `range` and fits in `T`. A value that does not read, or that lies outside them, counts
    /// as missing, with a warning.
    pub(crate) fn number<T: TryFrom<i64>>(
        &mut self,
        node: NodeId,
        name: &str,
        range: RangeInclusive<i64>,
    ) -> Option<T> {
        self.or_missing(node, name, |value| within(decimal(value)?, &range))
    }

    /// The hex number of the attribute `name` of `node`, as [`hex`] reads it, when it lies in
    /// `range` and fits in `T`. A value that does not read, or that lies outside them, counts
    /// as missing, with a warning.
    pub(crate) fn hex<T: TryFrom<i64>>(
        &mut self,
        node: NodeId,
        name: &str,
        range: RangeInclusive<i64>,
    ) -> Option<T> {
        self.or_missing(node, name, |value| within(hex(value)?, &range))
    }

    /// The text scale of the attribute `name` of `node` (`w:w` of a run), in percent, as
    /// [`text_scale`] reads it. A value that does not read counts as missing, 100 percent, with
    /// a warning.
    pub(crate) fn text_scale(&mut self, node: NodeId, name: &str) -> Option<i64> {
        self.or_missing(node, name, text_scale)
    }

    /// The percent of the preferred width of the attribute `name` of `node`, in fiftieths of a
    /// percent, as [`fiftieths`] reads it. A value that does not read counts as missing, with a
    /// warning.
    pub(crate) fn fiftieths(&mut self, node: NodeId, name: &str) -> Option<i64> {
        self.or_missing(node, name, fiftieths)
    }
}

/// Reads a decimal number (`ST_DecimalNumber`, `xsd:integer`): an optional sign, `+` or `-`,
/// and decimal digits, with a fraction that is dropped, as Word for Windows drops it: `2.7` is
/// 2. A space around the number, text and a number followed by text do not read.
pub(crate) fn decimal(value: &str) -> Option<i64> {
    let (whole, fraction) = value.split_once('.').unwrap_or((value, ""));
    if !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    whole.parse().ok()
}

/// Reads a hex number (`ST_ShortHexNumber`, `ST_LongHexNumber`): hex digits in either case,
/// with an optional sign and leading zeros, as Word for Windows reads `0a20`, `+0420` and
/// `00420`. The place's range keeps the number to the octets of its type.
pub(crate) fn hex(value: &str) -> Option<i64> {
    i64::from_str_radix(value, HEX_RADIX).ok()
}

/// Reads a text scale (`ST_TextScale`) in percent: a decimal number, as [`decimal`] reads it,
/// with an optional `%`, from 1 to 600. Word for Windows reads every other value, a negative
/// number and a number above 600 among them, as a missing scale.
pub(crate) fn text_scale(value: &str) -> Option<i64> {
    within(
        decimal(value.strip_suffix('%').unwrap_or(value))?,
        &TEXT_SCALES,
    )
}

/// Reads the percent of a preferred width in fiftieths of a percent: a decimal number, as
/// [`decimal`] reads it, counts fiftieths, and one followed by `%` counts percent, so that
/// `2500` and `50%` are both half. Word for Windows drops the fraction of either, and reads a
/// negative number as a missing width.
pub(crate) fn fiftieths(value: &str) -> Option<i64> {
    let fiftieths = match value.strip_suffix('%') {
        Some(percent) => decimal(percent)?.checked_mul(FIFTIETHS_PER_PERCENT)?,
        None => decimal(value)?,
    };
    within(fiftieths, &NOT_NEGATIVE)
}

/// The indices of `count` things, from 0 to `count - 1`: the range of an index, such as a list
/// level.
pub(crate) fn indices(count: usize) -> RangeInclusive<i64> {
    0..=i64::try_from(count).map_or(i64::MAX, |count| count - 1)
}

/// `number` in `T`, when it lies in `range` and fits in `T`.
fn within<T: TryFrom<i64>>(number: i64, range: &RangeInclusive<i64>) -> Option<T> {
    if range.contains(&number) {
        T::try_from(number).ok()
    } else {
        None
    }
}

#[cfg(test)]
mod tests;