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.

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, #bytesize)

    Original size or bytes-like.

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

    Alignment boundary in bytes.

Returns:

  • (Integer)

    Size after alignment (multiple of boundary).



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

def self.aligned_size(size, boundary: Constants::TABLE_ALIGNMENT)
  length = size.respond_to?(:bytesize) ? size.bytesize : size
  length + boundary(length, boundary:)
end

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

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

Parameters:

  • size (Integer, #bytesize)

    Either an Integer size, or any object responding to #bytesize (e.g. a String).

  • 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



29
30
31
32
# File 'lib/fontisan/utilities/padding.rb', line 29

def self.boundary(size, boundary: Constants::TABLE_ALIGNMENT)
  length = size.respond_to?(:bytesize) ? size.bytesize : size
  (boundary - (length % 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.



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

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

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