go-vise

Constrained Size Output Virtual Machine
Info | Log | Files | Refs | README | LICENSE

dump.go (846B)


      1 package db
      2 
      3 import (
      4 	"context"
      5 )
      6 
      7 type DumperFunc func(ctx context.Context) ([]byte, []byte)
      8 type CloseFunc func() error
      9 
     10 type Dumper struct {
     11 	fn     DumperFunc
     12 	cfn    CloseFunc
     13 	k      []byte
     14 	v      []byte
     15 	nexted bool
     16 }
     17 
     18 func NewDumper(fn DumperFunc) *Dumper {
     19 	return &Dumper{
     20 		fn: fn,
     21 	}
     22 }
     23 
     24 func (d *Dumper) WithFirst(k []byte, v []byte) *Dumper {
     25 	if d.nexted {
     26 		panic("already started")
     27 	}
     28 	d.k = k
     29 	d.v = v
     30 	d.nexted = true
     31 	return d
     32 }
     33 
     34 func (d *Dumper) WithClose(fn func() error) *Dumper {
     35 	d.cfn = fn
     36 	return d
     37 }
     38 
     39 func (d *Dumper) Next(ctx context.Context) ([]byte, []byte) {
     40 	d.nexted = true
     41 	k := d.k
     42 	v := d.v
     43 	if k == nil {
     44 		return nil, nil
     45 	}
     46 	d.k, d.v = d.fn(ctx)
     47 	logg.TraceCtxf(ctx, "next value is", "k", d.k, "v", d.v)
     48 	return k, v
     49 }
     50 
     51 func (d *Dumper) Close() error {
     52 	if d.cfn != nil {
     53 		return d.cfn()
     54 	}
     55 	return nil
     56 }