@@ -67,14 +67,7 @@ func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser)
6767 link .input .Close ()
6868 }()
6969 for i , toxic := range link .toxics .chain [link .direction ] {
70- if stateful , ok := toxic .Toxic .(toxics.StatefulToxic ); ok {
71- if toxic .PairedToxic == nil || link .pairedLink .stubs [toxic .PairedToxic .Index ].State == nil {
72- link .stubs [i ].State = stateful .NewState ()
73- } else {
74- link .stubs [i ].State = link .pairedLink .stubs [toxic .PairedToxic .Index ].State
75- link .stubs [i ].Toxicity = link .pairedLink .stubs [toxic .PairedToxic .Index ].Toxicity
76- }
77- }
70+ link .InitPairState (toxic )
7871
7972 go link .stubs [i ].Run (toxic )
8073 }
@@ -93,6 +86,22 @@ func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser)
9386 }()
9487}
9588
89+ func (link * ToxicLink ) InitPairState (toxic * toxics.ToxicWrapper ) {
90+ // If the toxic is stateful, create a state object or copy it from the paired link.
91+ if stateful , ok := toxic .Toxic .(toxics.StatefulToxic ); ok {
92+ if toxic .PairedToxic == nil || link .pairedLink .stubs [toxic .PairedToxic .Index ].State == nil {
93+ link .stubs [toxic .Index ].State = stateful .NewState ()
94+ } else {
95+ link .stubs [toxic .Index ].State = link .pairedLink .stubs [toxic .PairedToxic .Index ].State
96+ }
97+ }
98+
99+ // If the toxic is paired, synchronize the toxicity so they are always in the same state.
100+ if toxic .PairedToxic != nil {
101+ link .stubs [toxic .Index ].Toxicity = link .pairedLink .stubs [toxic .PairedToxic .Index ].Toxicity
102+ }
103+ }
104+
96105// Add a toxic to the end of the chain.
97106func (link * ToxicLink ) AddToxic (toxic * toxics.ToxicWrapper ) {
98107 i := len (link .stubs )
@@ -104,14 +113,7 @@ func (link *ToxicLink) AddToxic(toxic *toxics.ToxicWrapper) {
104113 if link .stubs [i - 1 ].InterruptToxic () {
105114 link .stubs [i - 1 ].Output = newin
106115
107- if stateful , ok := toxic .Toxic .(toxics.StatefulToxic ); ok {
108- if toxic .PairedToxic == nil || link .pairedLink .stubs [toxic .PairedToxic .Index ].State == nil {
109- link .stubs [i ].State = stateful .NewState ()
110- } else {
111- link .stubs [i ].State = link .pairedLink .stubs [toxic .PairedToxic .Index ].State
112- link .stubs [i ].Toxicity = link .pairedLink .stubs [toxic .PairedToxic .Index ].Toxicity
113- }
114- }
116+ link .InitPairState (toxic )
115117
116118 go link .stubs [i ].Run (toxic )
117119 go link .stubs [i - 1 ].Run (link .toxics .chain [link .direction ][i - 1 ])
0 commit comments