@@ -14,6 +14,9 @@ type Result struct {
1414 Language string
1515 // Confidence of the Result. Scale from 1 to 100. The bigger, the more confident.
1616 Confidence int
17+
18+ // used for sorting internally
19+ order int
1720}
1821
1922// Detector implements charset detection.
@@ -87,13 +90,13 @@ var (
8790func (d * Detector ) DetectBest (b []byte ) (r * Result , err error ) {
8891 input := newRecognizerInput (b , d .stripTag )
8992 outputChan := make (chan recognizerOutput )
90- for _ , r := range d .recognizers {
91- go matchHelper (r , input , outputChan )
93+ for i , r := range d .recognizers {
94+ go matchHelper (r , input , outputChan , i )
9295 }
9396 var output Result
9497 for i := 0 ; i < len (d .recognizers ); i ++ {
9598 o := <- outputChan
96- if output .Confidence < o .Confidence {
99+ if output .Confidence < o .Confidence || ( output . Confidence == o . Confidence && output . order < o . order ) {
97100 output = Result (o )
98101 }
99102 }
@@ -107,8 +110,8 @@ func (d *Detector) DetectBest(b []byte) (r *Result, err error) {
107110func (d * Detector ) DetectAll (b []byte ) ([]Result , error ) {
108111 input := newRecognizerInput (b , d .stripTag )
109112 outputChan := make (chan recognizerOutput )
110- for _ , r := range d .recognizers {
111- go matchHelper (r , input , outputChan )
113+ for i , r := range d .recognizers {
114+ go matchHelper (r , input , outputChan , i )
112115 }
113116 outputs := make (recognizerOutputs , 0 , len (d .recognizers ))
114117 for i := 0 ; i < len (d .recognizers ); i ++ {
@@ -136,12 +139,14 @@ func (d *Detector) DetectAll(b []byte) ([]Result, error) {
136139 return dedupOutputs , nil
137140}
138141
139- func matchHelper (r recognizer , input * recognizerInput , outputChan chan <- recognizerOutput ) {
140- outputChan <- r .Match (input )
142+ func matchHelper (r recognizer , input * recognizerInput , outputChan chan <- recognizerOutput , order int ) {
143+ outputChan <- r .Match (input , order )
141144}
142145
143146type recognizerOutputs []recognizerOutput
144147
145- func (r recognizerOutputs ) Len () int { return len (r ) }
146- func (r recognizerOutputs ) Less (i , j int ) bool { return r [i ].Confidence > r [j ].Confidence }
147- func (r recognizerOutputs ) Swap (i , j int ) { r [i ], r [j ] = r [j ], r [i ] }
148+ func (r recognizerOutputs ) Len () int { return len (r ) }
149+ func (r recognizerOutputs ) Less (i , j int ) bool {
150+ return r [i ].Confidence > r [j ].Confidence || (r [i ].Confidence == r [j ].Confidence && r [i ].order < r [j ].order )
151+ }
152+ func (r recognizerOutputs ) Swap (i , j int ) { r [i ], r [j ] = r [j ], r [i ] }
0 commit comments