Module: Fontisan::Utilities::Padding

Defined in:
lib/fontisan/utilities/padding.rb

Overview

Stateless helpers for SFNT byte-alignment padding.

OpenType and WOFF/WOFF2 require table data and certain directory blocks to be aligned to 4-byte boundaries with trailing null bytes. The same (N - (size % N)) % N arithmetic was duplicated across nine call sites before extraction; this module is the single source of truth.

All public methods take an Integer size. Callers with a String compute .bytesize first.

Examples:

Get padding length

Padding.boundary(13)              # => 3
Padding.boundary(13, boundary: 4) # => 3
Padding.boundary(16, boundary: 4) # => 0

Get padded bytes

Padding.pad("abc")               # => "abc\x00"
Padding.pad("abcd")              # => "abcd"

Class Method Summary collapse

Class Method Details

.aligned_size(size, boundary: Constants::TABLE_ALIGNMENT) ⇒ Integer

Aligned size of size after padding to boundary.

Parameters:

  • size (Integer)

    Original size in bytes.

  • boundary (Integer) (defaults to: Constants::TABLE_ALIGNMENT)

    Alignment boundary in bytes.

Returns:

  • (Integer)

    Size after alignment (multiple of boundary).



56
57
58
# File 'lib/fontisan/utilities/padding.rb', line 56

def self.aligned_size(size, boundary: Constants::TABLE_ALIGNMENT)
  size + boundary(size, boundary:)
end

.boundary(size, boundary: Constants::TABLE_ALIGNMENT) ⇒ Integer

Count of trailing pad bytes needed to align size to boundary.

Parameters:

  • size (Integer)

    Size in bytes (callers with a String compute .bytesize first).

  • boundary (Integer) (defaults to: Constants::TABLE_ALIGNMENT)

    Alignment boundary in bytes (default Constants::TABLE_ALIGNMENT).

Returns:

  • (Integer)

    Number of pad bytes in 0...boundary-1



32
33
34
# File 'lib/fontisan/utilities/padding.rb', line 32

def self.boundary(size, boundary: Constants::TABLE_ALIGNMENT)
  (boundary - (size % boundary)) % boundary
end

.pad(bytes, boundary: Constants::TABLE_ALIGNMENT) ⇒ String

Return bytes followed by null padding to the requested boundary.

Parameters:

  • bytes (String)

    Binary string to pad.

  • boundary (Integer) (defaults to: Constants::TABLE_ALIGNMENT)

    Alignment boundary in bytes.

Returns:

  • (String)

    The original string if already aligned, else a new binary string with trailing nulls.



42
43
44
45
46
47
48
49
# File 'lib/fontisan/utilities/padding.rb', line 42

def self.pad(bytes, boundary: Constants::TABLE_ALIGNMENT)
  pad_count = boundary(bytes.bytesize, boundary:)
  return bytes if pad_count.zero?

  out = bytes.dup.force_encoding(Encoding::BINARY)
  out << ("\x00" * pad_count)
  out
end