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

package tables

import (
	"encoding/binary"
	"fmt"
)

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

func (item *ColorRecord) mustParse(src []byte) {
	_ = src[3] // early bound checking
	item.Blue = src[0]
	item.Green = src[1]
	item.Red = src[2]
	item.Alpha = src[3]
}

func ParseCPAL(src []byte) (CPAL, int, error) {
	var item CPAL
	n := 0
	if L := len(src); L < 12 {
		return item, 0, fmt.Errorf("reading CPAL: "+"EOF: expected length: 12, got %d", L)
	}
	_ = src[11] // early bound checking
	item.Version = binary.BigEndian.Uint16(src[0:])
	item.NumPaletteEntries = binary.BigEndian.Uint16(src[2:])
	item.numPalettes = binary.BigEndian.Uint16(src[4:])
	item.numColorRecords = binary.BigEndian.Uint16(src[6:])
	offsetColorRecordsArray := int(binary.BigEndian.Uint32(src[8:]))
	n += 12

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

			arrayLength := int(item.numColorRecords)

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

			item.ColorRecordsArray = make([]ColorRecord, arrayLength) // allocation guarded by the previous check
			for i := range item.ColorRecordsArray {
				item.ColorRecordsArray[i].mustParse(src[offsetColorRecordsArray+i*4:])
			}
			offsetColorRecordsArray += arrayLength * 4
		}
	}
	{
		arrayLength := int(item.numPalettes)

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

		item.ColorRecordIndices = make([]uint16, arrayLength) // allocation guarded by the previous check
		for i := range item.ColorRecordIndices {
			item.ColorRecordIndices[i] = binary.BigEndian.Uint16(src[12+i*2:])
		}
		n += arrayLength * 2
	}
	return item, n, nil
}
