Class: Fontisan::Optimizers::SubroutineBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/fontisan/optimizers/subroutine_builder.rb

Overview

Builds CFF subroutines from analyzed patterns. Converts pattern byte sequences into valid CFF CharStrings with return operators, calculates bias values, and generates callsubr operators for pattern replacement.

Examples:

Basic usage

patterns = analyzer.analyze(charstrings)
builder = SubroutineBuilder.new(patterns, type: :local)
subroutines = builder.build
bias = builder.bias
call = builder.create_call(0)  # Call first subroutine

See Also:

  • docs/SUBROUTINE_ARCHITECTUREdocs/SUBROUTINE_ARCHITECTURE.md

Constant Summary collapse

RETURN_OPERATOR =

CFF return operator

"\x0b"
CALLSUBR_OPERATOR =

CFF callsubr operator

"\x0a"

Instance Method Summary collapse

Constructor Details

#initialize(patterns, type: :local) ⇒ SubroutineBuilder

Initialize subroutine builder

Parameters:

  • patterns (Array<Pattern>)

    patterns to convert to subroutines

  • type (Symbol) (defaults to: :local)

    subroutine type (:local or :global)



27
28
29
30
31
# File 'lib/fontisan/optimizers/subroutine_builder.rb', line 27

def initialize(patterns, type: :local)
  @patterns = patterns
  @type = type
  @subroutines = []
end

Instance Method Details

#biasInteger

Calculate CFF bias for current subroutine count Bias values defined by CFF specification:

  • 107 for count < 1240

  • 1131 for count < 33900

  • 32768 for count >= 33900

Returns:

  • (Integer)

    bias value



52
53
54
# File 'lib/fontisan/optimizers/subroutine_builder.rb', line 52

def bias
  calculate_bias(@subroutines.length)
end

#buildArray<String>

Build subroutines from patterns Each subroutine consists of the pattern bytes followed by a return operator. The order matches the pattern array order.

Returns:

  • (Array<String>)

    subroutine CharStrings



38
39
40
41
42
43
# File 'lib/fontisan/optimizers/subroutine_builder.rb', line 38

def build
  @subroutines = @patterns.map do |pattern|
    build_subroutine_charstring(pattern)
  end
  @subroutines
end

#create_call(subroutine_id) ⇒ String

Create callsubr operator for a subroutine Encodes the biased subroutine ID as a CFF integer followed by the callsubr operator.

Parameters:

  • subroutine_id (Integer)

    zero-based subroutine index

Returns:

  • (String)

    encoded callsubr operator



62
63
64
65
# File 'lib/fontisan/optimizers/subroutine_builder.rb', line 62

def create_call(subroutine_id)
  biased_id = subroutine_id - bias
  encode_integer(biased_id) + CALLSUBR_OPERATOR
end