File: mutate.go

package info (click to toggle)
golang-github-kshedden-dstream 0.0~git20190512.c4c4106-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 596 kB
  • sloc: makefile: 30
file content (60 lines) | stat: -rw-r--r-- 1,051 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package dstream

import "fmt"

// MutateFunc is a function that can be used to change the values of a variable in-place.
type MutateFunc func(interface{})

type mutated struct {
	xform

	// The name of the variable to be mutated
	vname string

	// The position of the variable to be mutated
	vpos int

	// The function that performs the mutation
	f MutateFunc
}

// Mutate returns a Dstream in which the variable with the given name
// is transformed using the given function.
func Mutate(ds Dstream, name string, f MutateFunc) Dstream {

	// Find the variable's position
	vpos := -1
	for j, n := range ds.Names() {
		if n == name {
			vpos = j
			break
		}
	}
	if vpos == -1 {
		msg := fmt.Sprintf("Mutate: variable '%s' not found", name)
		panic(msg)
	}

	m := &mutated{
		xform: xform{
			source: ds,
		},
		vname: name,
		vpos:  vpos,
		f:     f,
	}

	return m
}

func (m *mutated) Next() bool {
	if !m.source.Next() {
		return false
	}

	// Call the mutating function on the variable to be
	// transformed.
	m.f(m.GetPos(m.vpos))

	return true
}