package encoder

import (
	
	
	

	
)

// The functions of marshaling of WithMarshalers of encoding/json/v2: a value of a type which a function takes is
// written by the function, before its method or its kind. The opcodes of a type depend on the functions, so they
// are compiled for the functions and cached with them, apart from the tables shared by every goroutine.

// MarshalFunc is a function of marshaling, for the values of the types castable to Type ( see runtime.CastableTo ).
type MarshalFunc struct {
	Type reflect.Type
	// Append appends the value at p, of the type from: ErrUseDefault if the function declined to write it, which
	// lets the next function, the method or the kind of the type write it.
	Append func(ctx *RuntimeContext, b []byte, p unsafe.Pointer, from reflect.Type) ([]byte, error)
}

// MarshalFuncs are the functions of marshaling of a call, in the order they are tried, with the opcodes compiled
// for them.
type MarshalFuncs struct {
	Funcs    []MarshalFunc
	codeSets sync.Map // map[modeKey]*OpcodeSet
	castable sync.Map // map[reflect.Type][]*MarshalFunc
	defaults sync.Map // map[defaultKey]*OpcodeSet: the default representations ( see appendDefault )
}

// codeSet returns the opcodes of the type for the functions, compiling them if the type is new.
func ( *MarshalFuncs) ( uintptr,  compileMode) (*OpcodeSet, error) {
	return codeSetIn(&.codeSets, , , )
}

// funcsOf returns the functions which take a value of the type, in their order.
func ( *MarshalFuncs) ( reflect.Type) []*MarshalFunc {
	if  == nil {
		return nil
	}
	if ,  := .castable.Load();  {
		return .([]*MarshalFunc)
	}
	var  []*MarshalFunc
	for  := range .Funcs {
		if runtime.CastableTo(, .Funcs[].Type) {
			 = append(, &.Funcs[])
		}
	}
	,  := .castable.LoadOrStore(, )
	return .([]*MarshalFunc)
}

// appendByFuncs appends the value at p, of typ, by the first of the functions which doesn't decline it, or
// returns ErrUseDefault if they all do.
func appendByFuncs( *RuntimeContext,  []byte,  unsafe.Pointer,  reflect.Type,  []*MarshalFunc) ([]byte, error) {
	for ,  := range  {
		,  := .Append(, , , )
		if  != ErrUseDefault {
			return , 
		}
	}
	return , ErrUseDefault
}

// v2FuncsCode returns the code of a value of typ, addressable or not, written by the functions of marshaling, and
// true, if a function takes it. A value which they all decline is written by its default representation ( see
// appendDefault ).
func ( *Compiler) ( reflect.Type,  bool) (Code, bool) {
	 := .funcs.funcsOf()
	if len() == 0 {
		return nil, false
	}
	return .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		,  := appendByFuncs(, , , , )
		if  == ErrUseDefault {
			return appendDefault(, , , , noMethod, )
		}
		return , 
	}), true
}