github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/types/sexp/sexp.go (about)

     1  package sexp
     2  
     3  import (
     4  	"github.com/abesto/sexp"
     5  	"github.com/lmorg/murex/lang"
     6  	"github.com/lmorg/murex/lang/stdio"
     7  )
     8  
     9  const (
    10  	sexpr = "sexp"
    11  	csexp = "csexp"
    12  )
    13  
    14  func init() {
    15  	stdio.RegisterReadArray(sexpr, readArrayS)
    16  	stdio.RegisterReadArrayWithType(sexpr, readArrayWithTypeS)
    17  	stdio.RegisterReadMap(sexpr, readMapS)
    18  	stdio.RegisterWriteArray(sexpr, newArrayWriterS)
    19  	lang.ReadIndexes[sexpr] = readIndexS
    20  	lang.ReadNotIndexes[sexpr] = readIndexS
    21  	lang.Marshallers[sexpr] = marshalS
    22  	lang.Unmarshallers[sexpr] = unmarshal
    23  
    24  	stdio.RegisterReadArray(csexp, readArrayC)
    25  	stdio.RegisterReadArrayWithType(csexp, readArrayWithTypeC)
    26  	stdio.RegisterReadMap(csexp, readMapC)
    27  	stdio.RegisterWriteArray(csexp, newArrayWriterC)
    28  	lang.ReadIndexes[csexp] = readIndexC
    29  	lang.ReadNotIndexes[csexp] = readIndexC
    30  	lang.Marshallers[csexp] = marshalC
    31  	lang.Unmarshallers[csexp] = unmarshal
    32  
    33  	// These are just guessed at as I couldn't find any formally named MIMEs
    34  	lang.SetMime(sexpr,
    35  		"application/sexp",
    36  		"application/x-sexp",
    37  		"text/sexp",
    38  		"text/x-sexp",
    39  	)
    40  
    41  	lang.SetFileExtensions(sexpr, "sexp")
    42  }
    43  
    44  func readIndexC(p *lang.Process, params []string) error { return readIndex(p, params, true) }
    45  func readIndexS(p *lang.Process, params []string) error { return readIndex(p, params, false) }
    46  
    47  func readIndex(p *lang.Process, params []string, canonical bool) (err error) {
    48  	var se interface{}
    49  
    50  	b, err := p.Stdin.ReadAll()
    51  	if err != nil {
    52  		return err
    53  	}
    54  
    55  	se, err = sexp.Unmarshal(b)
    56  	if err != nil {
    57  		return err
    58  	}
    59  
    60  	marshaller := func(iface interface{}) ([]byte, error) {
    61  		return sexp.Marshal(iface, canonical)
    62  	}
    63  
    64  	return lang.IndexTemplateObject(p, params, &se, marshaller)
    65  }
    66  
    67  func marshalC(_ *lang.Process, v interface{}) ([]byte, error) { return sexp.Marshal(v, true) }
    68  func marshalS(_ *lang.Process, v interface{}) ([]byte, error) { return sexp.Marshal(v, false) }
    69  
    70  func unmarshal(p *lang.Process) (v interface{}, err error) {
    71  	b, err := p.Stdin.ReadAll()
    72  	if err != nil {
    73  		return
    74  	}
    75  
    76  	v, err = sexp.Unmarshal(b)
    77  	return
    78  }