// See http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set
// TODO: This function can be optimized by using bit arithmetic when the first argument is
// a constant string and the second is a column of type SET.
420852
func builtinFindInSet(args []types.Datum, _ context.Context) (d types.Datum, err error) {
	// args[0] -> Str
	// args[1] -> StrList
	if args[0].IsNull() || args[1].IsNull() {
		return
	}

	str, err := args[0].ToString()
	if err != nil {
		return d, errors.Trace(err)
	}
	strlst, err := args[1].ToString()
	if err != nil {
		return d, errors.Trace(err)
	}

	d.SetInt64(0)
	if len(strlst) == 0 {
		return
	}
	for i, s := range strings.Split(strlst, ",") {
		if s == str {
			d.SetInt64(int64(i + 1))
			return
		}
	}
	return
}
912253
func (set StringSet) Intersect(other StringSet) StringSet {
	intersection := NewStringSet()
	// loop over smaller set
	if set.Cardinality() < other.Cardinality() {
		for elem := range set {
			if other.Contains(elem) {
				intersection.Add(elem)
			}
		}
	} else {
		for elem := range other {
			if set.Contains(elem) {
				intersection.Add(elem)
			}
		}
	}
	return intersection
}
117332
func (s Set) ContainsFunc(f func(string) bool) bool {
	for k := range s {
		if f(k) {
			return true
		}
	}
	return false
}
837625
func (s *set) Contains(v interface{}) bool {
	_, ok := s.values[v]
	return ok
}
1105430
func FindInMap(mapName, topLevelKey, secondLevelKey interface{}) string {
	return encode(fmt.Sprintf(`{ "Fn::FindInMap" : [ "%v", "%v", "%v" ] }`, mapName, topLevelKey, secondLevelKey))
}
580483
func expandIntSet(s string) ([]string, error) {
	// Fast path for strings that do not have sets at all.
	if !strings.ContainsAny(s, "{}") {
		return []string{s}, nil
	}

	// States for the parser state machine.
	const (
		BEFORE_LB = iota // scanning to find '{'
		AFTER_RB         // after {...} block is read, scanning for end

		// In comments below '|' denotes the position of the state machine.

		RANGE_START   // '{|1..4,5}' or '{|1,2}', expecting to read a number or '}'
		COMMA_OR_DOTS // '{1|..4,5}' or '{1|,2}, expecting either ',' or '..', or '}'
		RANGE_END     // '{1..|4,5}', expecting to read a number
		COMMA         // '{1..4|,5}', expecting ',' or '}'
	)

	// Represents e.g. "10..20", or just "10" if l == r
	type rnge struct {
		l, r uint64
		fmt  string // either %d or e.g. %03d
	}

	var ranges []rnge     // all read ranges
	var total int         // total number of output strings to expect
	var rangeStart string // for currently constructed range

	// addRange parses strings into ints and verifies ranges are in the increasing
	// order. 'r' is empty for single-element terms e.g. "{2}".
	addRange := func(l, r string) error {
		li, err := strconv.ParseUint(l, 10, 64)
		if err != nil {
			return fmt.Errorf("integer %q is too large", l)
		}

		var ri uint64
		if r != "" {
			if ri, err = strconv.ParseUint(r, 10, 64); err != nil {
				return fmt.Errorf("integer %q is too large", r)
			}
			// E.g. "5..2" is a bad range, should be "2..5". Same for "2..2".
			if li >= ri {
				return fmt.Errorf("bad range - %d is not larger than %d", ri, li)
			}
		} else {
			// For e.g. "{2}".
			ri = li
			r = l
		}

		// E.g. "10,9" is bad, should be "9,10". Same for "9,9".
		if len(ranges) > 0 {
			if min := ranges[len(ranges)-1].r; min >= li {
				return fmt.Errorf("the set is not in increasing order - %d is not larger than %d", li, min)
			}
		}

		// If both strings have the same length, use it as padding for the output.
		format := "%d"
		if len(l) == len(r) {
			format = fmt.Sprintf("%%0%dd", len(l))
		}

		ranges = append(ranges, rnge{li, ri, format})
		total += int(ri-li) + 1
		return nil
	}

	pfx := "" // everything before '{'
	sfx := "" // everything after '}'

	state := BEFORE_LB

	for _, tok := range tokenize(s) {
		switch state {
		case BEFORE_LB:
			switch tok.typ {
			case TOK_LB:
				state = RANGE_START
			case TOK_RB:
				return nil, fmt.Errorf(`bad expression - "}" must appear after "{"`)
			default:
				pfx += tok.val
			}

		case AFTER_RB:
			switch tok.typ {
			case TOK_LB, TOK_RB:
				return nil, fmt.Errorf(`bad expression - only one "{...}" section is allowed`)
			default:
				sfx += tok.val
			}

		case RANGE_START:
			switch tok.typ {
			case TOK_NUM:
				rangeStart = tok.val
				state = COMMA_OR_DOTS
			case TOK_RB:
				state = AFTER_RB
			default:
				return nil, fmt.Errorf(`bad expression - expecting a number or "}", got %q`, tok.val)
			}

		case COMMA_OR_DOTS:
			switch tok.typ {
			case TOK_COMMA:
				if err := addRange(rangeStart, ""); err != nil {
					return nil, err
				}
				state = RANGE_START
			case TOK_RB:
				if err := addRange(rangeStart, ""); err != nil {
					return nil, err
				}
				state = AFTER_RB
			case TOK_DOTS:
				state = RANGE_END
			default:
				return nil, fmt.Errorf(`bad expression - expecting ",", ".." or "}", got %q`, tok.val)
			}

		case RANGE_END:
			switch tok.typ {
			case TOK_NUM:
				if err := addRange(rangeStart, tok.val); err != nil {
					return nil, err
				}
				state = COMMA
			default:
				return nil, fmt.Errorf(`bad expression - expecting a number, got %q`, tok.val)
			}

		case COMMA:
			switch tok.typ {
			case TOK_COMMA:
				state = RANGE_START
			case TOK_RB:
				state = AFTER_RB
			default:
				return nil, fmt.Errorf(`bad expression - expecting "," or "}", got %q`, tok.val)
			}

		default:
			panic("impossible")
		}
	}

	if len(ranges) == 0 {
		return []string{pfx + sfx}, nil
	}

	out := make([]string, 0, total)
	for _, rng := range ranges {
		for i := rng.l; i <= rng.r; i++ {
			out = append(out, fmt.Sprintf("%s"+rng.fmt+"%s", pfx, i, sfx))
		}
	}
	return out, nil
}
1291376
func (db *RedisDB) stringSet(k, v string) {
	db.del(k, false)
	db.keys[k] = "string"
	db.stringKeys[k] = v
	db.keyVersion[k]++
}
7759
func (me *PositiveInteger) Set(s string) {
	v, _ := strconv.ParseUint(s, 0, 64)
	*me = PositiveInteger(v)
}
1123353
func (f *StringSlice) Set(value string) error {
	*f = append(*f, value)
	return nil
}
73475
func altSet(db *sql.DB, key, value string) error {
	r, err := db.Query("SELECT replaceinto($1, $2)", key, value)
	if err != nil {
		return err
	}
	return r.Close()
}
1204574
func (m *MySQLStore) Find(token string) ([]byte, bool, error) {
	var b []byte
	var stmt string

	if compareVersion("5.6.4", m.version) >= 0 {
		stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP(6) < expiry"
	} else {
		stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP < expiry"
	}

	row := m.DB.QueryRow(stmt, token)
	err := row.Scan(&b)
	if err == sql.ErrNoRows {
		return nil, false, nil
	} else if err != nil {
		return nil, false, err
	}
	return b, true, nil
}
1333542
func (set StringSet) Difference(other StringSet) StringSet {
	differencedSet := NewStringSet()
	for elem := range set {
		if !other.Contains(elem) {
			differencedSet.Add(elem)
		}
	}
	return differencedSet
}
1301381
func (set StringSet) ContainsAll(i ...string) bool {
	allSet := NewStringSetFromSlice(i)
	if allSet.IsSubset(set) {
		return true
	}
	return false
}
975831
func FindInt(s []int, cb func(s int) bool) (int, bool) {
	for _, i := range s {
		result := cb(i)

		if result {
			return i, true
		}
	}

	return 0, false
}
28614
func (set Mysql56GTIDSet) Contains(other GTIDSet) bool {
	other56, ok := other.(Mysql56GTIDSet)
	if !ok {
		return false
	}

	// Check each SID in the other set.
	for sid, otherIntervals := range other56 {
		i := 0
		intervals := set[sid]
		count := len(intervals)

		// Check each interval for this SID in the other set.
		for _, iv := range otherIntervals {
			// Check that interval against each of our intervals.
			// Intervals are monotonically increasing,
			// so we don't need to reset the index each time.
			for {
				if i >= count {
					// We ran out of intervals to check against.
					return false
				}
				if intervals[i].contains(iv) {
					// Yes it's covered. Go on to the next one.
					break
				}
				i++
			}
		}
	}

	// No uncovered intervals were found.
	return true
}
45572
func stringSetDiff(a, b stringset.Set) []string {
	diff := a.Difference(b).ToSlice()
	sort.Strings(diff)
	return diff
}
812701
func (k *Key) In(defaultVal string, candidates []string) string {
	val := k.String()
	for _, cand := range candidates {
		if val == cand {
			return val
		}
	}
	return defaultVal
}