// SPDX-License-Identifier: Unlicense OR BSD-3-Clause

package tables

import (
	"encoding/binary"
	"fmt"
)

// Code generated by binarygen from glyphs_sbix_src.go. DO NOT EDIT

func ParseBitmapGlyphData(src []byte) (BitmapGlyphData, int, error) {
	var item BitmapGlyphData
	n := 0
	if L := len(src); L < 8 {
		return item, 0, fmt.Errorf("reading BitmapGlyphData: "+"EOF: expected length: 8, got %d", L)
	}
	_ = src[7] // early bound checking
	item.OriginOffsetX = int16(binary.BigEndian.Uint16(src[0:]))
	item.OriginOffsetY = int16(binary.BigEndian.Uint16(src[2:]))
	item.GraphicType = Tag(binary.BigEndian.Uint32(src[4:]))
	n += 8

	{

		item.Data = src[8:]
		n = len(src)
	}
	return item, n, nil
}

func ParseSbix(src []byte, numGlyphs int) (Sbix, int, error) {
	var item Sbix
	n := 0
	if L := len(src); L < 8 {
		return item, 0, fmt.Errorf("reading Sbix: "+"EOF: expected length: 8, got %d", L)
	}
	_ = src[7] // early bound checking
	item.version = binary.BigEndian.Uint16(src[0:])
	item.Flags = binary.BigEndian.Uint16(src[2:])
	arrayLengthStrikes := int(binary.BigEndian.Uint32(src[4:]))
	n += 8

	{

		if L := len(src); L < 8+arrayLengthStrikes*4 {
			return item, 0, fmt.Errorf("reading Sbix: "+"EOF: expected length: %d, got %d", 8+arrayLengthStrikes*4, L)
		}

		item.Strikes = make([]Strike, arrayLengthStrikes) // allocation guarded by the previous check
		for i := range item.Strikes {
			offset := int(binary.BigEndian.Uint32(src[8+i*4:]))
			// ignore null offsets
			if offset == 0 {
				continue
			}

			if L := len(src); L < offset {
				return item, 0, fmt.Errorf("reading Sbix: "+"EOF: expected length: %d, got %d", offset, L)
			}

			var err error
			item.Strikes[i], _, err = ParseStrike(src[offset:], numGlyphs)
			if err != nil {
				return item, 0, fmt.Errorf("reading Sbix: %s", err)
			}
		}
		n += arrayLengthStrikes * 4
	}
	return item, n, nil
}

func ParseStrike(src []byte, numGlyphs int) (Strike, int, error) {
	var item Strike
	n := 0
	if L := len(src); L < 4 {
		return item, 0, fmt.Errorf("reading Strike: "+"EOF: expected length: 4, got %d", L)
	}
	_ = src[3] // early bound checking
	item.Ppem = binary.BigEndian.Uint16(src[0:])
	item.Ppi = binary.BigEndian.Uint16(src[2:])
	n += 4

	{

		err := item.parseGlyphDatas(src[:], numGlyphs)
		if err != nil {
			return item, 0, fmt.Errorf("reading Strike: %s", err)
		}
	}
	return item, n, nil
}
