Class: Fontisan::Woff2::GlyfTransformer

Inherits:
Object
  • Object
show all
Defined in:
lib/fontisan/woff2/glyf_transformer.rb

Overview

Reconstructs glyf and loca tables from WOFF2 transformed format

WOFF2 glyf table transformation splits glyph data into separate streams for better compression. This transformer reconstructs the standard glyf and loca table formats from the transformed data.

Transformation format (Section 5 of WOFF2 spec):

  • Separate streams for nContour, nPoints, flags, x-coords, y-coords
  • Variable-length integer encoding (255UInt16)
  • Composite glyph components stored separately

See: https://www.w3.org/TR/WOFF2/#glyf_table_format

Examples:

Reconstructing tables

result = GlyfTransformer.reconstruct(transformed_data, num_glyphs)
glyf_data = result[:glyf]
loca_data = result[:loca]

Constant Summary collapse

ON_CURVE_POINT =

Glyph flags

0x01
X_SHORT_VECTOR =
0x02
Y_SHORT_VECTOR =
0x04
REPEAT_FLAG =
0x08
X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR =
0x10
Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR =
0x20
ARG_1_AND_2_ARE_WORDS =

Composite glyph flags

0x0001
ARGS_ARE_XY_VALUES =
0x0002
ROUND_XY_TO_GRID =
0x0004
WE_HAVE_A_SCALE =
0x0008
MORE_COMPONENTS =
0x0020
WE_HAVE_AN_X_AND_Y_SCALE =
0x0040
WE_HAVE_A_TWO_BY_TWO =
0x0080
WE_HAVE_INSTRUCTIONS =
0x0100
USE_MY_METRICS =
0x0200
OVERLAP_COMPOUND =
0x0400
HAVE_VARIATIONS =

Variable font variation data follows

0x1000

Class Method Summary collapse

Class Method Details

.build_simple_glyph_data(num_contours, x_min, y_min, x_max, y_max, end_pts, instructions, flags, x_coords, y_coords) ⇒ String

Build simple glyph data in standard format

Returns:

  • (String)

    Glyph data



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 610

def self.build_simple_glyph_data(num_contours, x_min, y_min, x_max, y_max,
                                 end_pts, instructions, flags, x_coords, y_coords)
  data = +""
  data << [num_contours].pack("n")
  data << [x_min, y_min, x_max, y_max].pack("n4")

  end_pts.each { |pt| data << [pt].pack("n") }

  data << [instructions.bytesize].pack("n")
  data << instructions

  flags.each { |flag| data << [flag].pack("C") }

  # Write x-coordinates
  prev_x = 0
  x_coords.each do |x|
    delta = x - prev_x
    prev_x = x

    data << if delta.abs <= 255
              [delta.abs].pack("C")
            else
              [delta].pack("n")
            end
  end

  # Write y-coordinates
  prev_y = 0
  y_coords.each do |y|
    delta = y - prev_y
    prev_y = y

    data << if delta.abs <= 255
              [delta.abs].pack("C")
            else
              [delta].pack("n")
            end
  end

  data
end

.build_tables(glyphs, index_format) ⇒ Hash

Build glyf and loca tables

Parameters:

  • glyphs (Array<String>)

    Glyph data

  • index_format (Integer)

    Loca format (0 = short, 1 = long)

Returns:

  • (Hash)

    { glyf: String, loca: String }



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 657

def self.build_tables(glyphs, index_format)
  glyf_data = +""
  loca_offsets = [0]

  glyphs.each do |glyph|
    glyf_data << glyph

    # Add padding to 4-byte boundary
    padding = (4 - (glyph.bytesize % 4)) % 4
    glyf_data << ("\x00" * padding)

    loca_offsets << glyf_data.bytesize
  end

  # Build loca table
  loca_data = +""
  if index_format.zero?
    # Short format (divide offsets by 2)
    loca_offsets.each do |offset|
      loca_data << [offset / 2].pack("n")
    end
  else
    # Long format
    loca_offsets.each do |offset|
      loca_data << [offset].pack("N")
    end
  end

  { glyf: glyf_data, loca: loca_data }
end

.parse_n_contour_stream(io, num_glyphs) ⇒ Array<Integer>

Parse nContour stream

Parameters:

  • io (StringIO)

    Input stream

  • num_glyphs (Integer)

    Number of glyphs

Returns:

  • (Array<Integer>)

    Number of contours per glyph (-1 for composite)



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 199

def self.parse_n_contour_stream(io, num_glyphs)
  n_contours = []
  num_glyphs.times do
    # For variable fonts, stream may be incomplete
    break if io.eof? || (io.size - io.pos) < 2

    value = read_int16(io)
    n_contours << value
  end

  # Pad with zeros if we have fewer contours than glyphs
  while n_contours.size < num_glyphs
    n_contours << 0
  end

  n_contours
end

.read_255_uint16(io) ⇒ Integer

Read variable-length 255UInt16 integer

Format from WOFF2 spec:

  • value < 253: one byte
  • value == 253: 253 + next uint16
  • value == 254: 253 * 2 + next uint16
  • value == 255: 253 * 3 + next uint16

Parameters:

  • io (StringIO)

    Input stream

Returns:

  • (Integer)

    Decoded value, or 0 if not enough data



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 159

def self.read_255_uint16(io)
  return 0 if io.eof? || (io.size - io.pos) < 1

  code_byte = io.read(1)
  return 0 unless code_byte && code_byte.bytesize == 1

  code = code_byte.unpack1("C")

  case code
  when 255
    return 0 if io.eof? || (io.size - io.pos) < 2

    value_bytes = io.read(2)
    return 0 unless value_bytes && value_bytes.bytesize == 2

    759 + value_bytes.unpack1("n")  # 253 * 3 + value
  when 254
    return 0 if io.eof? || (io.size - io.pos) < 2

    value_bytes = io.read(2)
    return 0 unless value_bytes && value_bytes.bytesize == 2

    506 + value_bytes.unpack1("n")  # 253 * 2 + value
  when 253
    return 0 if io.eof? || (io.size - io.pos) < 2

    value_bytes = io.read(2)
    return 0 unless value_bytes && value_bytes.bytesize == 2

    253 + value_bytes.unpack1("n")
  else
    code
  end
end

.read_coordinates(io, flags, short_flag, same_or_positive_flag) ⇒ Array<Integer>

Read coordinates

Parameters:

  • io (StringIO)

    Glyph stream

  • flags (Array<Integer>)

    Flag values

  • short_flag (Integer)

    Flag bit for short vector

  • same_or_positive_flag (Integer)

    Flag bit for same/positive

Returns:

  • (Array<Integer>)

    Coordinate values



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 572

def self.read_coordinates(io, flags, short_flag, same_or_positive_flag)
  coords = []
  value = 0

  flags.each do |flag|
    # EOF protection
    if (flag & short_flag) != 0
      break if io.eof? || (io.size - io.pos) < 1

      # Short vector (one byte)
      delta = read_uint8(io)
      delta = -delta if (flag & same_or_positive_flag).zero?
    elsif (flag & same_or_positive_flag) != 0
      # Same as previous (delta = 0)
      delta = 0
    else
      break if io.eof? || (io.size - io.pos) < 2

      # Long vector (two bytes, signed)
      delta = read_int16(io)
    end

    value += delta
    coords << value
  end

  # Pad with last value if needed
  last_val = coords.last || 0
  while coords.size < flags.size
    coords << last_val
  end

  coords
end

.read_f2dot14(io) ⇒ Object



711
712
713
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 711

def self.read_f2dot14(io)
  read_uint16(io)
end

.read_flags(io, count) ⇒ Array<Integer>

Read flags with repeat handling

Parameters:

  • io (StringIO)

    Flag stream

  • count (Integer)

    Number of flags to read

Returns:

  • (Array<Integer>)

    Flag values



533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 533

def self.read_flags(io, count)
  flags = []

  while flags.size < count
    # Safety check to prevent infinite loops with corrupted streams
    if flags.size > 200000
      # Stream appears corrupted, pad with zeros
      while flags.size < count
        flags << 0
      end
      break
    end

    # EOF protection for variable fonts
    break if io.eof? || (io.size - io.pos) < 1

    flag = read_uint8(io)
    flags << flag

    if (flag & REPEAT_FLAG) != 0
      break if io.eof? || (io.size - io.pos) < 1

      repeat_count = read_uint8(io)
      # Safety check on repeat count
      repeat_count = [repeat_count, 100].min
      repeat_count.times { flags << flag }
    end
  end

  flags
end

.read_int16(io) ⇒ Object



702
703
704
705
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 702

def self.read_int16(io)
  value = read_uint16(io)
  value > 0x7FFF ? value - 0x10000 : value
end

.read_int8(io) ⇒ Object



694
695
696
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 694

def self.read_int8(io)
  io.read(1)&.unpack1("c") || raise(EOFError, "Unexpected end of stream")
end

.read_stream_safely(io, _stream_name, variable_font: false) ⇒ String

Safely read a stream with bounds checking

Parameters:

  • io (StringIO)

    Input stream

  • stream_name (String)

    Name of stream for error messages

  • variable_font (Boolean) (defaults to: false)

    Whether this is a variable font (allows incomplete streams)

Returns:

  • (String)

    Stream data (empty if not available)



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 124

def self.read_stream_safely(io, _stream_name, variable_font: false)
  remaining = io.size - io.pos
  if remaining < 4
    # Not enough data for stream size - return empty stream
    return ""
  end

  # Read stream size safely
  size_bytes = io.read(4)
  return "" unless size_bytes && size_bytes.bytesize == 4

  stream_size = size_bytes.unpack1("N")
  remaining = io.size - io.pos

  if remaining < stream_size
    # Stream size extends beyond available data
    # Read what we can
    io.read(remaining) || ""
    # For variable fonts, we may have incomplete streams - just return what we have

  else
    io.read(stream_size) || ""
  end
end

.read_uint16(io) ⇒ Object



698
699
700
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 698

def self.read_uint16(io)
  io.read(2)&.unpack1("n") || raise(EOFError, "Unexpected end of stream")
end

.read_uint32(io) ⇒ Object



707
708
709
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 707

def self.read_uint32(io)
  io.read(4)&.unpack1("N") || raise(EOFError, "Unexpected end of stream")
end

.read_uint8(io) ⇒ Object

Helper methods for reading binary data



690
691
692
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 690

def self.read_uint8(io)
  io.read(1)&.unpack1("C") || raise(EOFError, "Unexpected end of stream")
end

.reconstruct(transformed_data, num_glyphs, variable_font: false) ⇒ Hash

Reconstruct glyf and loca tables from transformed data

Parameters:

  • transformed_data (String)

    The transformed glyf table data

  • num_glyphs (Integer)

    Number of glyphs from maxp table

  • variable_font (Boolean) (defaults to: false)

    Whether this is a variable font with variation data

Returns:

  • (Hash)

    { glyf: String, loca: String }

Raises:



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 53

def self.reconstruct(transformed_data, num_glyphs, variable_font: false)
  io = StringIO.new(transformed_data)

  # Check minimum size for header
  if io.size < 8
    raise InvalidFontError,
          "Transformed glyf data too small: #{io.size} bytes"
  end

  # Read header
  read_uint32(io)
  num_glyphs_in_data = read_uint16(io)
  index_format = read_uint16(io)

  if num_glyphs_in_data != num_glyphs
    raise InvalidFontError,
          "Glyph count mismatch: expected #{num_glyphs}, got #{num_glyphs_in_data}"
  end

  # Read nContour stream
  n_contour_data = read_stream_safely(io, "nContour",
                                      variable_font: variable_font)

  # Read nPoints stream
  n_points_data = read_stream_safely(io, "nPoints",
                                     variable_font: variable_font)

  # Read flag stream
  flag_data = read_stream_safely(io, "flag", variable_font: variable_font)

  # Read glyph stream (coordinates, instructions, composite data)
  glyph_data = read_stream_safely(io, "glyph",
                                  variable_font: variable_font)

  # Read composite stream
  composite_data = read_stream_safely(io, "composite",
                                      variable_font: variable_font)

  # Read bbox stream
  bbox_data = read_stream_safely(io, "bbox", variable_font: variable_font)

  # Read instruction stream
  instruction_data = read_stream_safely(io, "instruction",
                                        variable_font: variable_font)

  # Parse streams
  n_contours = parse_n_contour_stream(StringIO.new(n_contour_data),
                                      num_glyphs)

  # Reconstruct glyphs
  glyphs = reconstruct_glyphs(
    n_contours,
    StringIO.new(n_points_data),
    StringIO.new(flag_data),
    StringIO.new(glyph_data),
    StringIO.new(composite_data),
    StringIO.new(bbox_data),
    StringIO.new(instruction_data),
    variable_font: variable_font,
  )

  # Build glyf and loca tables
  build_tables(glyphs, index_format)
end

.reconstruct_composite_glyph(composite_io, bbox_io, instruction_io, variable_font: false) ⇒ String

Reconstruct a composite glyph

Parameters:

  • composite_io (StringIO)

    Composite stream

  • bbox_io (StringIO)

    Bounding box stream

  • instruction_io (StringIO)

    Instruction stream

  • variable_font (Boolean) (defaults to: false)

    Whether this is a variable font

Returns:

  • (String)

    Glyph data in standard format



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 358

def self.reconstruct_composite_glyph(composite_io, bbox_io,
instruction_io, variable_font: false)
  # Track available bytes to prevent EOF errors
  composite_size = composite_io.size - composite_io.pos

  # Validate minimum size (at least flags + glyph_index + args)
  return "" if composite_size < 8

  # Read bounding box safely
  bbox_remaining = bbox_io.size - bbox_io.pos
  if bbox_remaining < 8
    # Not enough data for bounding box, return empty glyph
    return ""
  end

  bbox_bytes = bbox_io.read(8)
  unless bbox_bytes && bbox_bytes.bytesize == 8
    return ""
  end

  x_min, y_min, x_max, y_max = bbox_bytes.unpack("n4")
  # Convert to signed
  x_min = x_min > 0x7FFF ? x_min - 0x10000 : x_min
  y_min = y_min > 0x7FFF ? y_min - 0x10000 : y_min
  x_max = x_max > 0x7FFF ? x_max - 0x10000 : x_max
  y_max = y_max > 0x7FFF ? y_max - 0x10000 : y_max

  # Read composite data
  composite_data = +""
  has_instructions = false
  has_variations = false

  loop do
    # Check if we have enough bytes for flags and glyph_index
    remaining = composite_io.size - composite_io.pos
    break if composite_io.eof? || remaining < 4

    # Read flags and glyph_index safely
    component_header = composite_io.read(4)
    break unless component_header && component_header.bytesize == 4

    flags, glyph_index = component_header.unpack("n2")

    # Write flags and index
    composite_data << [flags].pack("n")
    composite_data << [glyph_index].pack("n")

    # Read arguments (depend on flags)
    remaining = composite_io.size - composite_io.pos
    if (flags & ARG_1_AND_2_ARE_WORDS).zero?
      break if composite_io.eof? || remaining < 2

      arg_bytes = composite_io.read(2)
      break unless arg_bytes && arg_bytes.bytesize == 2

      arg1, arg2 = arg_bytes.unpack("c2")
      composite_data << [arg1, arg2].pack("c2")
    else
      break if composite_io.eof? || remaining < 4

      arg_bytes = composite_io.read(4)
      break unless arg_bytes && arg_bytes.bytesize == 4

      arg1, arg2 = arg_bytes.unpack("n2")
      # Convert to signed
      arg1 = arg1 > 0x7FFF ? arg1 - 0x10000 : arg1
      arg2 = arg2 > 0x7FFF ? arg2 - 0x10000 : arg2
      composite_data << [arg1, arg2].pack("n2")
    end

    # Read transformation matrix (depends on flags) with bounds checking
    if (flags & WE_HAVE_A_SCALE) != 0
      remaining = composite_io.size - composite_io.pos
      break if composite_io.eof? || remaining < 2

      scale_bytes = composite_io.read(2)
      break unless scale_bytes && scale_bytes.bytesize == 2

      scale = scale_bytes.unpack1("n")
      composite_data << [scale].pack("n")
    elsif (flags & WE_HAVE_AN_X_AND_Y_SCALE) != 0
      remaining = composite_io.size - composite_io.pos
      break if composite_io.eof? || remaining < 4

      scale_bytes = composite_io.read(4)
      break unless scale_bytes && scale_bytes.bytesize == 4

      x_scale, y_scale = scale_bytes.unpack("n2")
      composite_data << [x_scale, y_scale].pack("n2")
    elsif (flags & WE_HAVE_A_TWO_BY_TWO) != 0
      remaining = composite_io.size - composite_io.pos
      break if composite_io.eof? || remaining < 8

      matrix_bytes = composite_io.read(8)
      break unless matrix_bytes && matrix_bytes.bytesize == 8

      x_scale, scale01, scale10, y_scale = matrix_bytes.unpack("n4")
      composite_data << [x_scale, scale01, scale10, y_scale].pack("n4")
    end

    # Check for variable font variation data
    # Only parse if this is a variable font and the flag is set
    if variable_font && (flags & HAVE_VARIATIONS) != 0
      has_variations = true
      # Read tuple variation count and data
      remaining = composite_io.size - composite_io.pos
      if !composite_io.eof? && remaining >= 2
        # Read tuple count safely
        tuple_bytes = composite_io.read(2)
        if tuple_bytes && tuple_bytes.bytesize == 2
          tuple_count = tuple_bytes.unpack1("n")
          composite_data << [tuple_count].pack("n")

          # Each tuple has variation data - read and preserve it
          tuple_count.times do
            remaining = composite_io.size - composite_io.pos
            break if composite_io.eof? || remaining < 4

            # Read variation data (2 int16 values per tuple)
            var_bytes = composite_io.read(4)
            break unless var_bytes && var_bytes.bytesize == 4

            var1, var2 = var_bytes.unpack("n2")
            # Convert to signed if needed
            var1 = var1 > 0x7FFF ? var1 - 0x10000 : var1
            var2 = var2 > 0x7FFF ? var2 - 0x10000 : var2
            composite_data << [var1, var2].pack("n2")
          end
        end
      end
    end

    has_instructions = (flags & WE_HAVE_INSTRUCTIONS) != 0

    break if (flags & MORE_COMPONENTS).zero?
  end

  # Add instructions if present
  instructions = +""
  if has_instructions
    # Read instruction length safely
    remaining = instruction_io.size - instruction_io.pos
    if !instruction_io.eof? && remaining >= 2
      length_bytes = instruction_io.read(2)
      if length_bytes && length_bytes.bytesize == 2
        instruction_length = length_bytes.unpack1("n")
        if instruction_length.positive?
          remaining = instruction_io.size - instruction_io.pos
          instructions = if remaining >= instruction_length
                           instruction_io.read(instruction_length) || ""
                         else
                           # Read what we can
                           instruction_io.read(remaining) || ""
                         end
        end
      end
    end
  end

  # Build composite glyph data
  data = +""
  data << [-1].pack("n") # numberOfContours = -1
  data << [x_min, y_min, x_max, y_max].pack("n4")
  data << composite_data
  data << [instructions.bytesize].pack("n") if has_instructions
  data << instructions if has_instructions

  data
end

.reconstruct_glyphs(n_contours, n_points_io, flag_io, glyph_io, composite_io, bbox_io, instruction_io, variable_font: false) ⇒ Array<String>

Reconstruct all glyphs

Parameters:

  • n_contours (Array<Integer>)

    Contour counts

  • n_points_io (StringIO)

    Points stream

  • flag_io (StringIO)

    Flag stream

  • glyph_io (StringIO)

    Glyph data stream

  • composite_io (StringIO)

    Composite glyph stream

  • bbox_io (StringIO)

    Bounding box stream

  • instruction_io (StringIO)

    Instruction stream

  • variable_font (Boolean) (defaults to: false)

    Whether this is a variable font

Returns:

  • (Array<String>)

    Reconstructed glyph data



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 228

def self.reconstruct_glyphs(n_contours, n_points_io, flag_io, glyph_io,
                             composite_io, bbox_io, instruction_io, variable_font: false)
  glyphs = []

  n_contours.each do |num_contours|
    if num_contours.zero?
      # Empty glyph
      glyphs << ""
    elsif num_contours.positive?
      # Simple glyph
      glyphs << reconstruct_simple_glyph(
        num_contours, n_points_io, flag_io,
        glyph_io, bbox_io, instruction_io
      )
    elsif num_contours == -1
      # Composite glyph
      glyphs << reconstruct_composite_glyph(
        composite_io, bbox_io, instruction_io, variable_font: variable_font
      )
    else
      raise InvalidFontError, "Invalid nContours value: #{num_contours}"
    end
  end

  glyphs
end

.reconstruct_simple_glyph(num_contours, n_points_io, flag_io, glyph_io, bbox_io, instruction_io) ⇒ String

Reconstruct a simple glyph

Parameters:

  • num_contours (Integer)

    Number of contours

  • n_points_io (StringIO)

    Points stream

  • flag_io (StringIO)

    Flag stream

  • glyph_io (StringIO)

    Glyph data stream

  • bbox_io (StringIO)

    Bounding box stream

  • instruction_io (StringIO)

    Instruction stream

Returns:

  • (String)

    Glyph data in standard format



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/fontisan/woff2/glyf_transformer.rb', line 264

def self.reconstruct_simple_glyph(num_contours, n_points_io, flag_io,
                                  glyph_io, bbox_io, instruction_io)
  # Read end points of contours
  end_pts_of_contours = []
  max_points_per_glyph = 100000 # Sanity limit

  num_contours.times do
    if end_pts_of_contours.empty?
      val = read_255_uint16(n_points_io)
      end_pts_of_contours << val
    else
      delta = read_255_uint16(n_points_io)
      next_end_pt = end_pts_of_contours.last + delta + 1

      # Sanity check to prevent explosion from corrupted data
      if delta > 10000 || next_end_pt > max_points_per_glyph
        # Data appears corrupted, stop reading
        break
      end

      end_pts_of_contours << next_end_pt
    end
  end

  # Handle case where stream was corrupted
  if end_pts_of_contours.empty?
    # Return minimal empty glyph
    return ["\x00\x00"].pack("n") * 5 # Empty glyph: num_contours=0, bbox=0
  end

  total_points = [end_pts_of_contours.last + 1, max_points_per_glyph].min

  # Read flags
  flags = read_flags(flag_io, total_points)

  # Read coordinates
  x_coordinates = read_coordinates(glyph_io, flags, X_SHORT_VECTOR,
                                   X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR)
  y_coordinates = read_coordinates(glyph_io, flags, Y_SHORT_VECTOR,
                                   Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR)

  # Read bounding box safely
  bbox_remaining = bbox_io.size - bbox_io.pos
  if bbox_remaining < 8
    # Not enough data, use default bounding box
    x_min = y_min = x_max = y_max = 0
  else
    bbox_bytes = bbox_io.read(8)
    if bbox_bytes && bbox_bytes.bytesize == 8
      x_min, y_min, x_max, y_max = bbox_bytes.unpack("n4")
      # Convert to signed
      x_min = x_min > 0x7FFF ? x_min - 0x10000 : x_min
      y_min = y_min > 0x7FFF ? y_min - 0x10000 : y_min
      x_max = x_max > 0x7FFF ? x_max - 0x10000 : x_max
      y_max = y_max > 0x7FFF ? y_max - 0x10000 : y_max
    else
      x_min = y_min = x_max = y_max = 0
    end
  end

  # Read instructions safely
  instruction_length = 0
  instructions = ""

  inst_remaining = instruction_io.size - instruction_io.pos
  if inst_remaining >= 2
    inst_length_data = read_255_uint16(instruction_io)
    if inst_length_data
      instruction_length = inst_length_data
      if instruction_length.positive?
        inst_remaining = instruction_io.size - instruction_io.pos
        instructions = if inst_remaining >= instruction_length
                         instruction_io.read(instruction_length) || ""
                       else
                         # Read what we can
                         instruction_io.read(inst_remaining) || ""
                       end
      end
    end
  end

  # Build glyph data in standard format
  build_simple_glyph_data(num_contours, x_min, y_min, x_max, y_max,
                          end_pts_of_contours, instructions, flags,
                          x_coordinates, y_coordinates)
end