github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/fbp/example/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/egonelbre/exp/fbp"
     8  )
     9  
    10  type Comm struct{ In, Out chan string }
    11  
    12  func main() {
    13  	comm := &Comm{}
    14  	graph := fbp.New(comm)
    15  
    16  	graph.Registry = fbp.Registry{
    17  		"Split": NewSplit,
    18  		"Lower": NewLower,
    19  		"Upper": NewUpper,
    20  	}
    21  
    22  	graph.Setup(`
    23  		: s Split
    24  		: l Lower
    25  		: u Upper
    26  
    27  		$.In    -> s.In
    28  		s.Left  -> l.In
    29  		s.Right -> u.In
    30  
    31  		l.Out -> $.Out
    32  		u.Out -> $.Out
    33  	`)
    34  
    35  	graph.Start()
    36  
    37  	for i := range []int{1, 2, 3, 4, 5} {
    38  		comm.In <- fmt.Sprintf("Hello %v", i)
    39  	}
    40  	close(comm.In)
    41  
    42  	for v := range comm.Out {
    43  		fmt.Printf("%v\n", v)
    44  	}
    45  }
    46  
    47  type Split struct{ In, Left, Right chan string }
    48  
    49  func NewSplit() fbp.Node { return &Split{} }
    50  func (node *Split) Run() error {
    51  	defer close(node.Left)
    52  	defer close(node.Right)
    53  	for v := range node.In {
    54  		m := len(v) / 2
    55  		node.Left <- v[:m]
    56  		node.Right <- v[m:]
    57  	}
    58  	return nil
    59  }
    60  
    61  type Lower struct{ In, Out chan string }
    62  
    63  func NewLower() fbp.Node { return &Lower{} }
    64  func (node *Lower) Run() error {
    65  	defer close(node.Out)
    66  	for v := range node.In {
    67  		node.Out <- strings.ToLower(v)
    68  	}
    69  	return nil
    70  }
    71  
    72  type Upper struct{ In, Out chan string }
    73  
    74  func NewUpper() fbp.Node { return &Upper{} }
    75  func (node *Upper) Run() error {
    76  	defer close(node.Out)
    77  	for v := range node.In {
    78  		node.Out <- strings.ToUpper(v)
    79  	}
    80  	return nil
    81  }