fontations icon indicating copy to clipboard operation
fontations copied to clipboard

[kern] state-machine kerning state number is allowed to be negative

Open behdad opened this issue 4 months ago • 2 comments

https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html

has text:

Notice that this means that the offset can be either negative or positive, depending on the smallest glyph index in the table and the beginning of the table relative to the beginning of the state table.

this means that the state number can actually be negative. The code in fontations however does the math for the negative state numbers, but then casts and stores it as an unsigned:

        let new_state = (entry.new_state as i32) 
            .checked_sub(self.header.state_array_offset().to_u32() as i32) 
            .ok_or(ReadError::OutOfBounds)? 
            / n_classes as i32; 
        entry.new_state = new_state.try_into().map_err(|_| ReadError::OutOfBounds)?;

where:

/// Entry in an (extended) state table. 
#[derive(Clone, Debug)] 
pub struct StateEntry<T = NoPayload> { 
    /// Index of the next state. 
    pub new_state: u16, 
    /// Flag values are table specific. 
    pub flags: u16, 
    /// Payload is table specific. 
    pub payload: T, 
} 

behdad avatar Aug 29 '25 07:08 behdad

I’m admittedly a bit confused by this. I thought the piece of the spec you quoted referred to the action offset (which is packed into the flags or part of the payload) rather than the state number.

dfrg avatar Aug 29 '25 10:08 dfrg

Sorry, I quoted the wrong place. The relevant piece is in the kern table spec:

https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html

Because the stateTableOffset in the state table header is (strictly speaking) redundant, some 'kern' tables use it to record an initial state where that should not be StartOfText. To determine if this is done, calculate what the stateTableOffset should be. If it's different from the actual stateTableOffset, use it as the initial state.

behdad avatar Aug 29 '25 15:08 behdad