github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/starlib/starlarkio/io.go (about)

     1  // Copyright 2022 Edward McFarlane. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package starlarkio implements readers and writers.
     6  package starlarkio
     7  
     8  import (
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"sort"
    13  
    14  	"github.com/emcfarlane/larking/starlib/starext"
    15  	"go.starlark.net/starlark"
    16  )
    17  
    18  type Reader struct {
    19  	io.Reader
    20  	frozen bool
    21  }
    22  
    23  func (v *Reader) String() string        { return "<reader>" }
    24  func (v *Reader) Type() string          { return "io.reader" }
    25  func (v *Reader) Freeze()               { v.frozen = true }
    26  func (v *Reader) Truth() starlark.Bool  { return starlark.Bool(v.Reader != nil) }
    27  func (v *Reader) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: %s", v.Type()) }
    28  
    29  type readerAttr func(e *Reader) starlark.Value
    30  
    31  // TODO: optional methods io.Closer, etc.
    32  var readerAttrs = map[string]readerAttr{
    33  	"read_all": func(r *Reader) starlark.Value { return starext.MakeMethod(r, "read_all", r.readAll) },
    34  }
    35  
    36  func (v *Reader) Attr(name string) (starlark.Value, error) {
    37  	if a := readerAttrs[name]; a != nil {
    38  		return a(v), nil
    39  	}
    40  	return nil, nil
    41  }
    42  func (v *Reader) AttrNames() []string {
    43  	names := make([]string, 0, len(readerAttrs))
    44  	for name := range readerAttrs {
    45  		names = append(names, name)
    46  	}
    47  	sort.Strings(names)
    48  	return names
    49  }
    50  
    51  // TODO: check args/kwargs length
    52  func (v *Reader) readAll(_ *starlark.Thread, _ string, _ starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) {
    53  	x, err := ioutil.ReadAll(v.Reader)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	return starlark.Bytes(x), nil
    58  }