<commit_before>package strutils

import (
	"fmt"
	"math"
	"reflect"
	"regexp"
	"strconv"
)

type stringUtils struct{}

var numericPattern = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$`)

// init.
func NewStringUtils() stringUtils {
	return stringUtils{}
}

// quote string with slashes
func (s *stringUtils) AddSlashes(str string) string {

	l := len(str)

	buf := make([]byte, 0, l*2) //prealloca

	for i := 0; i < l; i++ {

		buf = append(buf, byte(str[i]))

		switch str[i] {

		case 92: //Dec : /

			if l >= i+1 {
				buf = append(buf, 92)

				if l > i+1 && str[i+1] == 92 {
					i++
				}
			}
		}
	}

	return string(buf)
}

// Un-quotes a quoted string
func (s *stringUtils) StripSlashes(str string) string {

	l := len(str)
	buf := make([]byte, 0, l) //prealloca

	for i := 0; i < l; i++ {

		buf = append(buf, byte(str[i]))
		if l > i+1 && str[i+1] == 92 {
			i++
		}
	}

	return string(buf)

}

// breakstr inserted before looks like space (CRLF , LFCR, SPACE, NL)
// BenchmarkNl2Br-8                   	10000000	      3398 ns/op
// BenchmarkNl2BrUseStringReplace-8   	10000000	      4535 ns/op
func (s *stringUtils) Nl2Br(str string) string {

	brtag := []byte("
")
	l := len(str)
	buf := make([]byte, 0, l) //prealloca

	for i := 0; i < l; i++ {

		switch str[i] {

		case 10, 13: //NL or CR

			for _, v := range brtag {
				buf = append(buf, v)
			}

			if l >= i+1 {
				if l > i+1 && (str[i+1] == 10 || str[i+1] == 13) { //NL+CR or CR+NL
					i++
				}
			}
		default:
			buf = append(buf, str[i])
		}
	}

	return string(buf)
}

// Wraps a string to a given number of characters using break characters (TAB, SPACE)
func (s *stringUtils) WordWrapSimple(str string, wd int, breakstr string) string {

	if wd < 1 {
		return str
	}

	strl := len(str)
	breakstrl := len(breakstr)

	buf := make([]byte, 0, (strl+breakstrl)*2)
	bufstr := []byte(str)

	brpos := 0
	for _, v := range bufstr {

		if (v == 9 || v == 32) && brpos >= wd {
			for _, vbk := range []byte(breakstr) {
				buf = append(buf, vbk)
			}
			brpos = -1

		} else {
			buf = append(buf, v)
		}
		brpos++
	}

	return string(buf)
}

// Wraps a string to a given number of characters using break characters (TAB, SPACE)
func (s *stringUtils) WordWrapAround(str string, wd int, breakstr string) string {

	if wd < 1 {
		return str
	}

	strl := len(str)
	breakstrl := len(breakstr)

	buf := make([]byte, 0, (strl+breakstrl)*2)
	bufstr := []byte(str)

	lastspc := make([]int, 0, strl)
	strpos := 0

	//looking for space or tab
	for _, v := range bufstr {

		if v == 9 || v == 32 {
			lastspc = append(lastspc, strpos)
		}
		strpos++
	}

	inject := make([]int, 0, strl)

	//looking for break point
	beforeBp := 0
	width := wd

	for _, v := range lastspc {

		if beforeBp != v {
			beforeBp = v
		}

		// DEBUG: fmt.Printf("V(%v) (%d <= %d || %d <= %d || %d <= %d) && %d <= %d : ", v, width, beforeBp, width, beforeBp+1, width, beforeBp-1, width, v)
		if (width <= beforeBp || width <= beforeBp+1 || width <= beforeBp-1) && width <= v {
			inject = append(inject, beforeBp)
			width += wd
			//fmt.Print("OK")
		} else if width < v && len(lastspc) == 1 {
			inject = append(inject, v)
		}
		//fmt.Println()
	}

	//injection
	breakno := 0
	loopcnt := 0
	injectcnt := len(inject)
	for _, v := range bufstr {

		//fmt.Printf("(%v) %d > %d && %d <= %d\n", v, injectcnt, breakno, inject[breakno], loopcnt)
		if injectcnt > breakno && inject[breakno] == loopcnt {
			for _, vbk := range []byte(breakstr) {
				buf = append(buf, vbk)
			}

			if injectcnt > breakno+1 {
				breakno++
			}
		} else {
			buf = append(buf, v)
		}

		loopcnt++
	}

	return string(buf)
}

// format a number with english notation grouped thousands
// TODO : improve bytebuffer efficiently
func (s *stringUtils) NumberFmt(obj interface{}) (string, error) {

	var strNum string

	switch obj.(type) {

	case string:
		strNum = obj.(string)
		if numericPattern.MatchString(strNum) == false {
			return "", fmt.Errorf("not support obj.(%v) := %v ", reflect.TypeOf(obj), strNum)
		}
	case int:
		strNum = strconv.FormatInt(int64(obj.(int)), 10)
	case int8:
		strNum = strconv.FormatInt(int64(obj.(int8)), 10)
	case int16:
		strNum = strconv.FormatInt(int64(obj.(int16)), 10)
	case int32:
		strNum = strconv.FormatInt(int64(obj.(int32)), 10)
	case int64:
		strNum = strconv.FormatInt(int64(obj.(int64)), 10)
	case uint:
		strNum = strconv.FormatUint(uint64(obj.(uint)), 10)
	case uint8:
		strNum = strconv.FormatUint(uint64(obj.(uint8)), 10)
	case uint16:
		strNum = strconv.FormatUint(uint64(obj.(uint16)), 10)
	case uint32:
		strNum = strconv.FormatUint(uint64(obj.(uint32)), 10)
	case uint64:
		strNum = strconv.FormatUint(uint64(obj.(uint64)), 10)
	case float32:
		strNum = fmt.Sprintf("%g", obj.(float32))
	case float64:
		strNum = fmt.Sprintf("%g", obj.(float64))
	default:
		return "", fmt.Errorf("not support obj.(%v)", reflect.TypeOf(obj))
	}

	bufbyteStr := []byte(strNum)
	bufbyteStr_len := len(bufbyteStr)

	//subffix after dot
	bufbyteTail := make([]byte, bufbyteStr_len-1)

	//init.
	foundDot := 0
	foundPos := 0
	dotcnt := 0
	bufbyteSize := 0

	//looking for dot
	for i := bufbyteStr_len - 1; i >= 0; i-- {
		if bufbyteStr[i] == 46 {
			copy(bufbyteTail, bufbyteStr[i:])
			foundDot = i
			foundPos = i
			break
		}
	}

	//make bufbyte size
	if foundDot == 0 { //numeric without dot
		bufbyteSize = int(math.Ceil(float64(bufbyteStr_len) + (float64(bufbyteStr_len) / 3)))
		foundDot = bufbyteStr_len
		foundPos = bufbyteSize - 2

		bufbyteSize -= 1

	} else { //with dot

		var cal_foundDot int

		if bufbyteStr[0] == 45 { //if startwith "-"(45)
			cal_foundDot = foundDot - 1
		} else {
			cal_foundDot = foundDot
		}

		bufbyteSize = int(math.Ceil(float64(cal_foundDot) + (float64(cal_foundDot) / 3) + float64(bufbyteStr_len-cal_foundDot) - 1))
	}

	//make a buffer byte
	bufbyte := make([]byte, bufbyteSize)

	//skip : need to dot injection
	if 4 > foundDot {
		return strNum, nil
	}

	//injection
	intoPos := foundPos
	for i := foundDot - 1; i >= 0; i-- {
		if dotcnt >= 3 && ((bufbyteStr[i] >= 48 && bufbyteStr[i] <= 57) || bufbyteStr[i] == 69 || bufbyteStr[i] == 101 || bufbyteStr[i] == 43) {
			bufbyte[intoPos] = 44
			intoPos--
			dotcnt = 0
		}
		bufbyte[intoPos] = bufbyteStr[i]
		intoPos--
		dotcnt++
	}

	//into dot to tail
	intoPos = foundPos + 1
	if foundDot != bufbyteStr_len {
		for _, v := range bufbyteTail {
			if v == 0 { //NULL
				break
			}

			bufbyte[intoPos] = v
			intoPos++
		}
	}

	return string(bufbyte), nil
}

// padding contol const
const (
	PAD_LEFT  = 0 //left padding
	PAD_RIGHT = 1 //right padding
	PAD_BOTH  = 2 //both padding
)

// pad a string to a certain length with another string
func (s *stringUtils) PaddingBoth(str string, fill string, mx int) string {
	return s.padding(str, fill, PAD_BOTH, mx)
}

// pad a string to a certain length with another string
func (s *stringUtils) PaddingLeft(str string, fill string, mx int) string {
	return s.padding(str, fill, PAD_LEFT, mx)
}

// pad a string to a certain length with another string
func (s *stringUtils) PaddingRight(str string, fill string, mx int) string {
	return s.padding(str, fill, PAD_RIGHT, mx)
}

// BenchmarkPadding-8                   10000000	       271 ns/op
// BenchmarkPaddingUseStringRepeat-8   	 3000000	       418 ns/op
func (s *stringUtils) padding(str string, fill string, m int, mx int) string {

	byteStr := []byte(str)
	byteStr_len := len(byteStr)
	if byteStr_len >= mx || mx < 1 {
		return str
	}

	var leftsize int
	var rightsize int

	switch m {
	case PAD_BOTH:
		rlsize := float64(mx-byteStr_len) / 2
		leftsize = int(rlsize)
		rightsize = int(rlsize + math.Copysign(0.5, rlsize))

	case PAD_LEFT:
		leftsize = mx - byteStr_len

	case PAD_RIGHT:
		rightsize = mx - byteStr_len

	}

	buf := make([]byte, 0, mx)

	if m == PAD_LEFT || m == PAD_BOTH {
		for i := 0; i < leftsize; {
			for _, v := range []byte(fill) {
				buf = append(buf, v)
				if i >= leftsize-1 {
					i = leftsize
					break
				} else {
					i++
				}
			}
		}
	}

	for _, v := range byteStr {
		buf = append(buf, v)
	}

	if m == PAD_RIGHT || m == PAD_BOTH {
		for i := 0; i < rightsize; {
			for _, v := range []byte(fill) {
				buf = append(buf, v)
				if i >= rightsize-1 {
					i = rightsize
					break
				} else {
					i++
				}
			}
		}
	}

	return string(buf)
}

// Lowercase the first character of each word in a string
// TOKEN : \t(9)\r(13)\n(10)\f(12)\v(11)\s(32)
func (s *stringUtils) LowerCaseFirstWords(str string) string {

	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		if upper == 1 && v >= 65 && v <= 90 {
			v = v + 32
		}

		upper = 0

		if (v >= 9 && v <= 13) || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}

// Uppercase the first character of each word in a string
// TOKEN : \t(9)\r(13)\n(10)\f(12)\v(11)\s(32)
func (s *stringUtils) UpperCaseFirstWords(str string) string {

	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		if upper == 1 && v >= 97 && v <= 122 {
			v = v - 32
		}

		upper = 0

		if (v >= 9 && v <= 13) || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}

// Switch the first character case of each word in a string
func (s *stringUtils) SwapCaseFirstWords(str string) string {

	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		switch {
		case upper == 1 && v >= 65 && v <= 90:
			v = v + 32

		case upper == 1 && v >= 97 && v <= 122:
			v = v - 32
		}

		upper = 0

		if (v >= 9 && v <= 13) || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}
<commit_msg>fixed warrning on golint, according to golint guide-lines<commit_after>package strutils

import (
	"fmt"
	"math"
	"reflect"
	"regexp"
	"strconv"
)

type stringUtils struct{}

var numericPattern = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$`)

// init string processing utility
func NewStringUtils() stringUtils {
	return stringUtils{}
}

// quote string with slashes
func (s *stringUtils) AddSlashes(str string) string {

	l := len(str)

	buf := make([]byte, 0, l*2) //prealloca

	for i := 0; i < l; i++ {

		buf = append(buf, byte(str[i]))

		switch str[i] {

		case 92: //Dec : /

			if l >= i+1 {
				buf = append(buf, 92)

				if l > i+1 && str[i+1] == 92 {
					i++
				}
			}
		}
	}

	return string(buf)
}

// Un-quotes a quoted string
func (s *stringUtils) StripSlashes(str string) string {

	l := len(str)
	buf := make([]byte, 0, l) //prealloca

	for i := 0; i < l; i++ {

		buf = append(buf, byte(str[i]))
		if l > i+1 && str[i+1] == 92 {
			i++
		}
	}

	return string(buf)

}

// breakstr inserted before looks like space (CRLF , LFCR, SPACE, NL)
// BenchmarkNl2Br-8                   	10000000	      3398 ns/op
// BenchmarkNl2BrUseStringReplace-8   	10000000	      4535 ns/op
func (s *stringUtils) Nl2Br(str string) string {

	brtag := []byte("
")
	l := len(str)
	buf := make([]byte, 0, l) //prealloca

	for i := 0; i < l; i++ {

		switch str[i] {

		case 10, 13: //NL or CR

			for _, v := range brtag {
				buf = append(buf, v)
			}

			if l >= i+1 {
				if l > i+1 && (str[i+1] == 10 || str[i+1] == 13) { //NL+CR or CR+NL
					i++
				}
			}
		default:
			buf = append(buf, str[i])
		}
	}

	return string(buf)
}

// Wraps a string to a given number of characters using break characters (TAB, SPACE)
func (s *stringUtils) WordWrapSimple(str string, wd int, breakstr string) string {

	if wd < 1 {
		return str
	}

	strl := len(str)
	breakstrl := len(breakstr)

	buf := make([]byte, 0, (strl+breakstrl)*2)
	bufstr := []byte(str)

	brpos := 0
	for _, v := range bufstr {

		if (v == 9 || v == 32) && brpos >= wd {
			for _, vbk := range []byte(breakstr) {
				buf = append(buf, vbk)
			}
			brpos = -1

		} else {
			buf = append(buf, v)
		}
		brpos++
	}

	return string(buf)
}

// Wraps a string to a given number of characters using break characters (TAB, SPACE)
func (s *stringUtils) WordWrapAround(str string, wd int, breakstr string) string {

	if wd < 1 {
		return str
	}

	strl := len(str)
	breakstrl := len(breakstr)

	buf := make([]byte, 0, (strl+breakstrl)*2)
	bufstr := []byte(str)

	lastspc := make([]int, 0, strl)
	strpos := 0

	//looking for space or tab
	for _, v := range bufstr {

		if v == 9 || v == 32 {
			lastspc = append(lastspc, strpos)
		}
		strpos++
	}

	inject := make([]int, 0, strl)

	//looking for break point
	beforeBp := 0
	width := wd

	for _, v := range lastspc {

		if beforeBp != v {
			beforeBp = v
		}

		// DEBUG: fmt.Printf("V(%v) (%d <= %d || %d <= %d || %d <= %d) && %d <= %d : ", v, width, beforeBp, width, beforeBp+1, width, beforeBp-1, width, v)
		if (width <= beforeBp || width <= beforeBp+1 || width <= beforeBp-1) && width <= v {
			inject = append(inject, beforeBp)
			width += wd
			//fmt.Print("OK")
		} else if width < v && len(lastspc) == 1 {
			inject = append(inject, v)
		}
		//fmt.Println()
	}

	//injection
	breakno := 0
	loopcnt := 0
	injectcnt := len(inject)
	for _, v := range bufstr {

		//fmt.Printf("(%v) %d > %d && %d <= %d\n", v, injectcnt, breakno, inject[breakno], loopcnt)
		if injectcnt > breakno && inject[breakno] == loopcnt {
			for _, vbk := range []byte(breakstr) {
				buf = append(buf, vbk)
			}

			if injectcnt > breakno+1 {
				breakno++
			}
		} else {
			buf = append(buf, v)
		}

		loopcnt++
	}

	return string(buf)
}

// format a number with english notation grouped thousands
// TODO : improve bytebuffer efficiently
func (s *stringUtils) NumberFmt(obj interface{}) (string, error) {

	var strNum string

	switch obj.(type) {

	case string:
		strNum = obj.(string)
		if numericPattern.MatchString(strNum) == false {
			return "", fmt.Errorf("not support obj.(%v) := %v ", reflect.TypeOf(obj), strNum)
		}
	case int:
		strNum = strconv.FormatInt(int64(obj.(int)), 10)
	case int8:
		strNum = strconv.FormatInt(int64(obj.(int8)), 10)
	case int16:
		strNum = strconv.FormatInt(int64(obj.(int16)), 10)
	case int32:
		strNum = strconv.FormatInt(int64(obj.(int32)), 10)
	case int64:
		strNum = strconv.FormatInt(int64(obj.(int64)), 10)
	case uint:
		strNum = strconv.FormatUint(uint64(obj.(uint)), 10)
	case uint8:
		strNum = strconv.FormatUint(uint64(obj.(uint8)), 10)
	case uint16:
		strNum = strconv.FormatUint(uint64(obj.(uint16)), 10)
	case uint32:
		strNum = strconv.FormatUint(uint64(obj.(uint32)), 10)
	case uint64:
		strNum = strconv.FormatUint(uint64(obj.(uint64)), 10)
	case float32:
		strNum = fmt.Sprintf("%g", obj.(float32))
	case float64:
		strNum = fmt.Sprintf("%g", obj.(float64))
	default:
		return "", fmt.Errorf("not support obj.(%v)", reflect.TypeOf(obj))
	}

	bufbyteStr := []byte(strNum)
	bufbyteStrLen := len(bufbyteStr)

	//subffix after dot
	bufbyteTail := make([]byte, bufbyteStrLen-1)

	//init.
	foundDot := 0
	foundPos := 0
	dotcnt := 0
	bufbyteSize := 0

	//looking for dot
	for i := bufbyteStrLen - 1; i >= 0; i-- {
		if bufbyteStr[i] == 46 {
			copy(bufbyteTail, bufbyteStr[i:])
			foundDot = i
			foundPos = i
			break
		}
	}

	//make bufbyte size
	if foundDot == 0 { //numeric without dot
		bufbyteSize = int(math.Ceil(float64(bufbyteStrLen) + (float64(bufbyteStrLen) / 3)))
		foundDot = bufbyteStrLen
		foundPos = bufbyteSize - 2

		bufbyteSize -= 1

	} else { //with dot

		var calFoundDot int

		if bufbyteStr[0] == 45 { //if startwith "-"(45)
			calFoundDot = foundDot - 1
		} else {
			calFoundDot = foundDot
		}

		bufbyteSize = int(math.Ceil(float64(calFoundDot) + (float64(calFoundDot) / 3) + float64(bufbyteStrLen-calFoundDot) - 1))
	}

	//make a buffer byte
	bufbyte := make([]byte, bufbyteSize)

	//skip : need to dot injection
	if 4 > foundDot {
		return strNum, nil
	}

	//injection
	intoPos := foundPos
	for i := foundDot - 1; i >= 0; i-- {
		if dotcnt >= 3 && ((bufbyteStr[i] >= 48 && bufbyteStr[i] <= 57) || bufbyteStr[i] == 69 || bufbyteStr[i] == 101 || bufbyteStr[i] == 43) {
			bufbyte[intoPos] = 44
			intoPos--
			dotcnt = 0
		}
		bufbyte[intoPos] = bufbyteStr[i]
		intoPos--
		dotcnt++
	}

	//into dot to tail
	intoPos = foundPos + 1
	if foundDot != bufbyteStrLen {
		for _, v := range bufbyteTail {
			if v == 0 { //NULL
				break
			}

			bufbyte[intoPos] = v
			intoPos++
		}
	}

	return string(bufbyte), nil
}

// padding contol const
const (
	PAD_LEFT  = 0 //left padding
	PAD_RIGHT = 1 //right padding
	PAD_BOTH  = 2 //both padding
)

// pad a string to a certain length with another string
func (s *stringUtils) PaddingBoth(str string, fill string, mx int) string {
	return s.padding(str, fill, PAD_BOTH, mx)
}

// pad a string to a certain length with another string
func (s *stringUtils) PaddingLeft(str string, fill string, mx int) string {
	return s.padding(str, fill, PAD_LEFT, mx)
}

// pad a string to a certain length with another string
func (s *stringUtils) PaddingRight(str string, fill string, mx int) string {
	return s.padding(str, fill, PAD_RIGHT, mx)
}

// BenchmarkPadding-8                   10000000	       271 ns/op
// BenchmarkPaddingUseStringRepeat-8   	 3000000	       418 ns/op
func (s *stringUtils) padding(str string, fill string, m int, mx int) string {

	byteStr := []byte(str)
	byteStrLen := len(byteStr)
	if byteStrLen >= mx || mx < 1 {
		return str
	}

	var leftsize int
	var rightsize int

	switch m {
	case PAD_BOTH:
		rlsize := float64(mx-byteStrLen) / 2
		leftsize = int(rlsize)
		rightsize = int(rlsize + math.Copysign(0.5, rlsize))

	case PAD_LEFT:
		leftsize = mx - byteStrLen

	case PAD_RIGHT:
		rightsize = mx - byteStrLen

	}

	buf := make([]byte, 0, mx)

	if m == PAD_LEFT || m == PAD_BOTH {
		for i := 0; i < leftsize; {
			for _, v := range []byte(fill) {
				buf = append(buf, v)
				if i >= leftsize-1 {
					i = leftsize
					break
				} else {
					i++
				}
			}
		}
	}

	for _, v := range byteStr {
		buf = append(buf, v)
	}

	if m == PAD_RIGHT || m == PAD_BOTH {
		for i := 0; i < rightsize; {
			for _, v := range []byte(fill) {
				buf = append(buf, v)
				if i >= rightsize-1 {
					i = rightsize
					break
				} else {
					i++
				}
			}
		}
	}

	return string(buf)
}

// Lowercase the first character of each word in a string
// TOKEN : \t(9)\r(13)\n(10)\f(12)\v(11)\s(32)
func (s *stringUtils) LowerCaseFirstWords(str string) string {

	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		if upper == 1 && v >= 65 && v <= 90 {
			v = v + 32
		}

		upper = 0

		if (v >= 9 && v <= 13) || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}

// Uppercase the first character of each word in a string
// TOKEN : \t(9)\r(13)\n(10)\f(12)\v(11)\s(32)
func (s *stringUtils) UpperCaseFirstWords(str string) string {

	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		if upper == 1 && v >= 97 && v <= 122 {
			v = v - 32
		}

		upper = 0

		if (v >= 9 && v <= 13) || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}

// Switch the first character case of each word in a string
func (s *stringUtils) SwapCaseFirstWords(str string) string {

	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		switch {
		case upper == 1 && v >= 65 && v <= 90:
			v = v + 32

		case upper == 1 && v >= 97 && v <= 122:
			v = v - 32
		}

		upper = 0

		if (v >= 9 && v <= 13) || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}
<|endoftext|>


<commit_before>package mpmailq

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestGetNthLine(t *testing.T) {
	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "0000" {
			t.Errorf("0-th line is expected to be 0000")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "" {
			t.Errorf("0-th line is expected to be empty")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "0000" {
			t.Errorf("0-th line is expected to be 0000")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "" {
			t.Errorf("0-th line is expected to be empty")
		}
	}

	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "" {
			t.Errorf("1-st line is expected to be empty")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "" {
			t.Errorf("1-st line is expected to be empty")
		}
	}

	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "0000" {
			t.Errorf("-1-st line is expected to be 0000")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "" {
			t.Errorf("-1-st line is expected to be empty")
		}
	}

	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "" {
			t.Errorf("-2-nd line is expected to be empty")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "" {
			t.Errorf("-2-nd line is expected to be empty")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "0000" {
			t.Errorf("-2-nd line is expected to be 0000")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "" {
			t.Errorf("-2-nd line is expected to be empty")
		}
	}
}

func TestParseMailqPostfix(t *testing.T) {
	mailq := mailqFormats["postfix"]

	{
		output := `-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------
DD0C740001C      274 Thu Mar  3 23:52:37  foobar@example.com
          (connect to mail.invalid[192.0.2.100]:25: Connection timed out)
                                         nyao@mail.invalid

-- 15 Kbytes in 42 Requests.
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 42 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}

	{
		output := `Mail queue is empty
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 0 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}
}

func TestParseMailqQmain(t *testing.T) {
	mailq := mailqFormats["qmail"]

	{
		output := `messages in queue: 42
messages in queue but not yet preprocessed: 3
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 42 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}
}

func TestParseMailqExim(t *testing.T) {
	mailq := mailqFormats["exim"]

	{
		output := `42
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 42 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}
}

func TestGraphDefinition(t *testing.T) {
	plugin := plugin{
		mailq:       mailqFormats["postfix"],
		keyPrefix:   "mailq",
		labelPrefix: "Mailq",
	}

	{
		graphs := plugin.GraphDefinition()
		graphMailq, ok := graphs["mailq"]
		if !ok {
			t.Errorf("No graph definition for mailq")
		}

		if graphMailq.Unit != "integer" {
			t.Errorf("Mailq is expected to be an integral graph")
		}

		if graphMailq.Label == "" {
			t.Errorf("Mailq is expected to have a label")
		}

		if len(graphMailq.Metrics) != 1 {
			t.Errorf("Mailq is expected to have one definition of metrics")
		}

		if graphMailq.Metrics[0].Name != "count" {
			t.Errorf("Mailq is expected to have count metric")
		}

		if graphMailq.Metrics[0].Type != "uint64" {
			t.Errorf("Mailq is expected to have type uint64")
		}
	}
}

func TestFetchMetricsPostfix(t *testing.T) {
	cwd, _ := os.Getwd()

	plugin := plugin{
		mailq:       mailqFormats["postfix"],
		path:        filepath.Join(cwd, "/fixtures/postqueue"),
		keyPrefix:   "mailq",
		labelPrefix: "Mailq",
	}

	{
		os.Setenv("TEST_MAILQ_COUNT", "42")
		defer os.Unsetenv("TEST_MAILQ_COUNT")

		metrics, err := plugin.FetchMetrics()
		if err != nil {
			t.Errorf("Error %s", err.Error())
		}
		if metrics["count"].(uint64) != 42 {
			t.Errorf("Incorrect value: %d", metrics["count"].(uint64))
		}
	}
}

func TestFetchMetricsQmail(t *testing.T) {
	cwd, _ := os.Getwd()

	plugin := plugin{
		mailq:       mailqFormats["qmail"],
		path:        filepath.Join(cwd, "/fixtures/qmail/qmail-qstat"),
		keyPrefix:   "mailq",
		labelPrefix: "Mailq",
	}

	origPath := os.Getenv("PATH")
	os.Setenv("PATH", "/bin:/usr/bin")
	defer os.Setenv("PATH", origPath)

	{
		os.Setenv("TEST_MAILQ_COUNT", "42")
		defer os.Unsetenv("TEST_MAILQ_COUNT")

		metrics, err := plugin.FetchMetrics()
		if err != nil {
			t.Errorf("Error %s", err.Error())
		}
		if metrics["count"].(uint64) != 42 {
			t.Errorf("Incorrect value: %d", metrics["count"].(uint64))
		}
	}
}
<commit_msg>remove prefix "/"<commit_after>package mpmailq

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestGetNthLine(t *testing.T) {
	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "0000" {
			t.Errorf("0-th line is expected to be 0000")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "" {
			t.Errorf("0-th line is expected to be empty")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "0000" {
			t.Errorf("0-th line is expected to be 0000")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), 0)
		if l != "" {
			t.Errorf("0-th line is expected to be empty")
		}
	}

	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "" {
			t.Errorf("1-st line is expected to be empty")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), 1)
		if l != "" {
			t.Errorf("1-st line is expected to be empty")
		}
	}

	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "0000" {
			t.Errorf("-1-st line is expected to be 0000")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "1111" {
			t.Errorf("1-st line is expected to be 1111")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), -1)
		if l != "" {
			t.Errorf("-1-st line is expected to be empty")
		}
	}

	{
		s := `0000`
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "" {
			t.Errorf("-2-nd line is expected to be empty")
		}
	}

	{
		s := `
1111`
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "" {
			t.Errorf("-2-nd line is expected to be empty")
		}
	}

	{
		s := `0000
1111
`
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "0000" {
			t.Errorf("-2-nd line is expected to be 0000")
		}
	}

	{
		s := ``
		l, _ := getNthLine(strings.NewReader(s), -2)
		if l != "" {
			t.Errorf("-2-nd line is expected to be empty")
		}
	}
}

func TestParseMailqPostfix(t *testing.T) {
	mailq := mailqFormats["postfix"]

	{
		output := `-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------
DD0C740001C      274 Thu Mar  3 23:52:37  foobar@example.com
          (connect to mail.invalid[192.0.2.100]:25: Connection timed out)
                                         nyao@mail.invalid

-- 15 Kbytes in 42 Requests.
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 42 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}

	{
		output := `Mail queue is empty
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 0 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}
}

func TestParseMailqQmain(t *testing.T) {
	mailq := mailqFormats["qmail"]

	{
		output := `messages in queue: 42
messages in queue but not yet preprocessed: 3
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 42 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}
}

func TestParseMailqExim(t *testing.T) {
	mailq := mailqFormats["exim"]

	{
		output := `42
`

		count, err := mailq.parse(strings.NewReader(output))
		if err != nil {
			t.Errorf("Error in parseMailq: %s", err.Error())
		}
		if count != 42 {
			t.Errorf("Incorrect parse result %d", count)
		}
	}
}

func TestGraphDefinition(t *testing.T) {
	plugin := plugin{
		mailq:       mailqFormats["postfix"],
		keyPrefix:   "mailq",
		labelPrefix: "Mailq",
	}

	{
		graphs := plugin.GraphDefinition()
		graphMailq, ok := graphs["mailq"]
		if !ok {
			t.Errorf("No graph definition for mailq")
		}

		if graphMailq.Unit != "integer" {
			t.Errorf("Mailq is expected to be an integral graph")
		}

		if graphMailq.Label == "" {
			t.Errorf("Mailq is expected to have a label")
		}

		if len(graphMailq.Metrics) != 1 {
			t.Errorf("Mailq is expected to have one definition of metrics")
		}

		if graphMailq.Metrics[0].Name != "count" {
			t.Errorf("Mailq is expected to have count metric")
		}

		if graphMailq.Metrics[0].Type != "uint64" {
			t.Errorf("Mailq is expected to have type uint64")
		}
	}
}

func TestFetchMetricsPostfix(t *testing.T) {
	cwd, _ := os.Getwd()

	plugin := plugin{
		mailq:       mailqFormats["postfix"],
		path:        filepath.Join(cwd, "fixtures/postqueue"),
		keyPrefix:   "mailq",
		labelPrefix: "Mailq",
	}

	{
		os.Setenv("TEST_MAILQ_COUNT", "42")
		defer os.Unsetenv("TEST_MAILQ_COUNT")

		metrics, err := plugin.FetchMetrics()
		if err != nil {
			t.Errorf("Error %s", err.Error())
		}
		if metrics["count"].(uint64) != 42 {
			t.Errorf("Incorrect value: %d", metrics["count"].(uint64))
		}
	}
}

func TestFetchMetricsQmail(t *testing.T) {
	cwd, _ := os.Getwd()

	plugin := plugin{
		mailq:       mailqFormats["qmail"],
		path:        filepath.Join(cwd, "fixtures/qmail/qmail-qstat"),
		keyPrefix:   "mailq",
		labelPrefix: "Mailq",
	}

	origPath := os.Getenv("PATH")
	os.Setenv("PATH", "/bin:/usr/bin")
	defer os.Setenv("PATH", origPath)

	{
		os.Setenv("TEST_MAILQ_COUNT", "42")
		defer os.Unsetenv("TEST_MAILQ_COUNT")

		metrics, err := plugin.FetchMetrics()
		if err != nil {
			t.Errorf("Error %s", err.Error())
		}
		if metrics["count"].(uint64) != 42 {
			t.Errorf("Incorrect value: %d", metrics["count"].(uint64))
		}
	}
}
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
// This file is available under the Apache license.

package metrics

import (
	"encoding/json"
	"reflect"
	"sync"

	"github.com/golang/glog"
	"github.com/pkg/errors"
)

// Store contains Metrics.
type Store struct {
	sync.RWMutex
	Metrics map[string][]*Metric
}

// NewStore returns a new metric Store.
func NewStore() (s *Store) {
	s = &Store{}
	s.ClearMetrics()
	return
}

// Add is used to add one metric to the Store.
func (s *Store) Add(m *Metric) error {
	s.Lock()
	defer s.Unlock()
	dupeIndex := -1
	if len(s.Metrics[m.Name]) > 0 {
		t := s.Metrics[m.Name][0].Kind
		if m.Kind != t {
			return errors.Errorf("Metric %s has different kind %s to existing %s.", m.Name, m.Kind, t)
		}

		// To avoid duplicate metrics:
		// - copy old LabelValues into new metric;
		// - discard old metric.
		for i, v := range s.Metrics[m.Name] {
			//
			if v.Program != m.Program {
				continue
			}
			if v.Type != m.Type {
				continue
			}
			if reflect.DeepEqual(v.Keys, m.Keys) {
				continue
			}
			dupeIndex = i
			glog.Infof("Found duped metric: %d", dupeIndex)
			for j, oldLabel := range v.LabelValues {
				glog.Warningf("Labels: %d %s", j, oldLabel.Labels)
				d, err := v.GetDatum(oldLabel.Labels...)
				if err == nil {
					m.LabelValues = append(m.LabelValues, &LabelValue{oldLabel.Labels, d})
				}
			}
		}
	}

	s.Metrics[m.Name] = append(s.Metrics[m.Name], m)
	if dupeIndex >= 0 {
		s.Metrics[m.Name] = append(s.Metrics[m.Name][0:dupeIndex], s.Metrics[m.Name][dupeIndex+1:]...)
	}
	return nil
}

// ClearMetrics empties the store of all metrics.
func (s *Store) ClearMetrics() {
	s.Lock()
	defer s.Unlock()
	s.Metrics = make(map[string][]*Metric)
}

// MarshalJSON returns a JSON byte string representing the Store.
func (s *Store) MarshalJSON() (b []byte, err error) {
	s.Lock()
	defer s.Unlock()
	ms := make([]*Metric, 0)
	for _, ml := range s.Metrics {
		ms = append(ms, ml...)
	}
	return json.Marshal(ms)
}
<commit_msg>Fix up equality test.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
// This file is available under the Apache license.

package metrics

import (
	"encoding/json"
	"reflect"
	"sync"

	"github.com/golang/glog"
	"github.com/pkg/errors"
)

// Store contains Metrics.
type Store struct {
	sync.RWMutex
	Metrics map[string][]*Metric
}

// NewStore returns a new metric Store.
func NewStore() (s *Store) {
	s = &Store{}
	s.ClearMetrics()
	return
}

// Add is used to add one metric to the Store.
func (s *Store) Add(m *Metric) error {
	s.Lock()
	defer s.Unlock()
	glog.Infof("Adding a new metric %v", m)
	dupeIndex := -1
	if len(s.Metrics[m.Name]) > 0 {
		t := s.Metrics[m.Name][0].Kind
		if m.Kind != t {
			return errors.Errorf("Metric %s has different kind %s to existing %s.", m.Name, m.Kind, t)
		}

		// To avoid duplicate metrics:
		// - copy old LabelValues into new metric;
		// - discard old metric.
		for i, v := range s.Metrics[m.Name] {
			//
			if v.Program != m.Program {
				continue
			}
			if v.Type != m.Type {
				continue
			}
			glog.Infof("v keys: %v m.keys: %v", v.Keys, m.Keys)
			if len(v.Keys) > 0 && len(m.Keys) > 0 && reflect.DeepEqual(v.Keys, m.Keys) {
				continue
			}
			dupeIndex = i
			glog.Infof("Found duped metric: %d", dupeIndex)
			for j, oldLabel := range v.LabelValues {
				glog.Warningf("Labels: %d %s", j, oldLabel.Labels)
				d, err := v.GetDatum(oldLabel.Labels...)
				if err == nil {
					m.LabelValues = append(m.LabelValues, &LabelValue{oldLabel.Labels, d})
				}
			}
		}
	}

	s.Metrics[m.Name] = append(s.Metrics[m.Name], m)
	if dupeIndex >= 0 {
		s.Metrics[m.Name] = append(s.Metrics[m.Name][0:dupeIndex], s.Metrics[m.Name][dupeIndex+1:]...)
	}
	return nil
}

// ClearMetrics empties the store of all metrics.
func (s *Store) ClearMetrics() {
	s.Lock()
	defer s.Unlock()
	s.Metrics = make(map[string][]*Metric)
}

// MarshalJSON returns a JSON byte string representing the Store.
func (s *Store) MarshalJSON() (b []byte, err error) {
	s.Lock()
	defer s.Unlock()
	ms := make([]*Metric, 0)
	for _, ml := range s.Metrics {
		ms = append(ms, ml...)
	}
	return json.Marshal(ms)
}
<|endoftext|>


<commit_before>package agent

import (
	"fmt"
	"github.com/hashicorp/consul/consul/structs"
	"net/http"
	"strings"
)

// aclCreateResponse is used to wrap the ACL ID
type aclCreateResponse struct {
	ID string
}

// aclDisabled handles if ACL datacenter is not configured
func aclDisabled(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	resp.WriteHeader(401)
	resp.Write([]byte("ACL support disabled"))
	return nil, nil
}

func (s *HTTPServer) ACLDestroy(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.ACLRequest{
		Datacenter: s.agent.config.ACLDatacenter,
		Op:         structs.ACLDelete,
	}
	s.parseToken(req, &args.Token)

	// Pull out the acl id
	args.ACL.ID = strings.TrimPrefix(req.URL.Path, "/v1/acl/destroy/")
	if args.ACL.ID == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing ACL"))
		return nil, nil
	}

	var out string
	if err := s.agent.RPC("ACL.Apply", &args, &out); err != nil {
		return nil, err
	}
	return true, nil
}

func (s *HTTPServer) ACLCreate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	return s.aclSet(resp, req, false)
}

func (s *HTTPServer) ACLUpdate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	return s.aclSet(resp, req, true)
}

func (s *HTTPServer) aclSet(resp http.ResponseWriter, req *http.Request, update bool) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.ACLRequest{
		Datacenter: s.agent.config.ACLDatacenter,
		Op:         structs.ACLSet,
		ACL: structs.ACL{
			Type: structs.ACLTypeClient,
		},
	}
	s.parseToken(req, &args.Token)

	// Handle optional request body
	if req.ContentLength > 0 {
		if err := decodeBody(req, &args.ACL, nil); err != nil {
			resp.WriteHeader(400)
			resp.Write([]byte(fmt.Sprintf("Request decode failed: %v", err)))
			return nil, nil
		}
	}

	// Ensure there is no ID set for create
	if !update && args.ACL.ID != "" {
		resp.WriteHeader(400)
		resp.Write([]byte(fmt.Sprintf("ACL ID cannot be set")))
		return nil, nil
	}

	// Ensure there is an ID set for update
	if update && args.ACL.ID == "" {
		resp.WriteHeader(400)
		resp.Write([]byte(fmt.Sprintf("ACL ID must be set")))
		return nil, nil
	}

	// Create the acl, get the ID
	var out string
	if err := s.agent.RPC("ACL.Apply", &args, &out); err != nil {
		return nil, err
	}

	// Format the response as a JSON object
	return aclCreateResponse{out}, nil
}

func (s *HTTPServer) ACLClone(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.ACLSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the acl id
	args.ACL = strings.TrimPrefix(req.URL.Path, "/v1/acl/clone/")
	if args.ACL == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing ACL"))
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.Get", &args, &out); err != nil {
		return nil, err
	}

	// Bail if the ACL is not found
	if len(out.ACLs) == 0 {
		resp.WriteHeader(404)
		resp.Write([]byte(fmt.Sprintf("Target ACL not found")))
		return nil, nil
	}

	// Create a new ACL
	createArgs := structs.ACLRequest{
		Datacenter: args.Datacenter,
		Op:         structs.ACLSet,
		ACL:        *out.ACLs[0],
	}
	createArgs.ACL.ID = ""
	createArgs.Token = args.Token

	// Create the acl, get the ID
	var outID string
	if err := s.agent.RPC("ACL.Apply", &createArgs, &outID); err != nil {
		return nil, err
	}

	// Format the response as a JSON object
	return aclCreateResponse{outID}, nil
}

func (s *HTTPServer) ACLGet(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.ACLSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the acl id
	args.ACL = strings.TrimPrefix(req.URL.Path, "/v1/acl/info/")
	if args.ACL == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing ACL"))
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.Get", &args, &out); err != nil {
		return nil, err
	}
	return out.ACLs, nil
}

func (s *HTTPServer) ACLList(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.DCSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.List", &args, &out); err != nil {
		return nil, err
	}
	return out.ACLs, nil
}
<commit_msg>agent: Strict PUT for modifying ACLs<commit_after>package agent

import (
	"fmt"
	"github.com/hashicorp/consul/consul/structs"
	"net/http"
	"strings"
)

// aclCreateResponse is used to wrap the ACL ID
type aclCreateResponse struct {
	ID string
}

// aclDisabled handles if ACL datacenter is not configured
func aclDisabled(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	resp.WriteHeader(401)
	resp.Write([]byte("ACL support disabled"))
	return nil, nil
}

func (s *HTTPServer) ACLDestroy(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.ACLRequest{
		Datacenter: s.agent.config.ACLDatacenter,
		Op:         structs.ACLDelete,
	}
	s.parseToken(req, &args.Token)

	// Pull out the acl id
	args.ACL.ID = strings.TrimPrefix(req.URL.Path, "/v1/acl/destroy/")
	if args.ACL.ID == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing ACL"))
		return nil, nil
	}

	var out string
	if err := s.agent.RPC("ACL.Apply", &args, &out); err != nil {
		return nil, err
	}
	return true, nil
}

func (s *HTTPServer) ACLCreate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	return s.aclSet(resp, req, false)
}

func (s *HTTPServer) ACLUpdate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	return s.aclSet(resp, req, true)
}

func (s *HTTPServer) aclSet(resp http.ResponseWriter, req *http.Request, update bool) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.ACLRequest{
		Datacenter: s.agent.config.ACLDatacenter,
		Op:         structs.ACLSet,
		ACL: structs.ACL{
			Type: structs.ACLTypeClient,
		},
	}
	s.parseToken(req, &args.Token)

	// Handle optional request body
	if req.ContentLength > 0 {
		if err := decodeBody(req, &args.ACL, nil); err != nil {
			resp.WriteHeader(400)
			resp.Write([]byte(fmt.Sprintf("Request decode failed: %v", err)))
			return nil, nil
		}
	}

	// Ensure there is no ID set for create
	if !update && args.ACL.ID != "" {
		resp.WriteHeader(400)
		resp.Write([]byte(fmt.Sprintf("ACL ID cannot be set")))
		return nil, nil
	}

	// Ensure there is an ID set for update
	if update && args.ACL.ID == "" {
		resp.WriteHeader(400)
		resp.Write([]byte(fmt.Sprintf("ACL ID must be set")))
		return nil, nil
	}

	// Create the acl, get the ID
	var out string
	if err := s.agent.RPC("ACL.Apply", &args, &out); err != nil {
		return nil, err
	}

	// Format the response as a JSON object
	return aclCreateResponse{out}, nil
}

func (s *HTTPServer) ACLClone(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.ACLSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the acl id
	args.ACL = strings.TrimPrefix(req.URL.Path, "/v1/acl/clone/")
	if args.ACL == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing ACL"))
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.Get", &args, &out); err != nil {
		return nil, err
	}

	// Bail if the ACL is not found
	if len(out.ACLs) == 0 {
		resp.WriteHeader(404)
		resp.Write([]byte(fmt.Sprintf("Target ACL not found")))
		return nil, nil
	}

	// Create a new ACL
	createArgs := structs.ACLRequest{
		Datacenter: args.Datacenter,
		Op:         structs.ACLSet,
		ACL:        *out.ACLs[0],
	}
	createArgs.ACL.ID = ""
	createArgs.Token = args.Token

	// Create the acl, get the ID
	var outID string
	if err := s.agent.RPC("ACL.Apply", &createArgs, &outID); err != nil {
		return nil, err
	}

	// Format the response as a JSON object
	return aclCreateResponse{outID}, nil
}

func (s *HTTPServer) ACLGet(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.ACLSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the acl id
	args.ACL = strings.TrimPrefix(req.URL.Path, "/v1/acl/info/")
	if args.ACL == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing ACL"))
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.Get", &args, &out); err != nil {
		return nil, err
	}
	return out.ACLs, nil
}

func (s *HTTPServer) ACLList(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.DCSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.List", &args, &out); err != nil {
		return nil, err
	}
	return out.ACLs, nil
}
<|endoftext|>


<commit_before>package build

import (
	"errors"
	"github.com/tueftler/doget/dockerfile"
	"reflect"
	"testing"
)

func assertEqual(expect, actual interface{}, t *testing.T) {
	if !reflect.DeepEqual(expect, actual) {
		t.Errorf("Items not equal:\nexpected %q\nhave     %q\n", expect, actual)
	}
}

func Test_splitArgsRecognizesTransformArgs(t *testing.T) {
	transformArgs, _ := split([]string{"--doget-no-cache=true", "-t", "foo:bar", "--no-cache=true"})
	assertEqual([]string{"-no-cache", "true"}, transformArgs, t)
}

func Test_splitArgsRecognizesTransformArgWithoutValue(t *testing.T) {
	transformArgs, _ := split([]string{"-t", "foo:bar", "--doget-clean", "--no-cache=true"})
	assertEqual([]string{"-clean"}, transformArgs, t)
}

func Test_splitArgsRecognizesDockerBuildArgs(t *testing.T) {
	_, dockerArgs := split([]string{"-t", "foo:bar", "--no-cache=true", "--doget-no-cache=true", "."})
	assertEqual([]string{"-t", "foo:bar", "--no-cache=true", "."}, dockerArgs, t)
}

func Test_transformArgsAreEmptyWhenOnlyDockerArgsPresent(t *testing.T) {
	transformArgs, _ := split([]string{"--no-cache=true"})
	assertEqual([]string{}, transformArgs, t)
}

func Test_dockerArgsAreEmptyWhenOnlyTransformArgsPresent(t *testing.T) {
	_, dockerArgs := split([]string{"--doget-no-cache=true"})
	assertEqual([]string{}, dockerArgs, t)
}

type mock struct {
	executed bool
	err      error
}

func (m *mock) Build(args []string) error {
	m.executed = true
	if nil != m.err {
		return m.err
	}

	return nil
}

func (m *mock) Init(name string) {
	// intentionally empty
}

func (m *mock) Run(parser *dockerfile.Parser, args []string) error {
	m.executed = true
	if nil != m.err {
		return m.err
	}

	return nil
}

func Test_dockerBuildNotExecutedWhenTransformFails(t *testing.T) {
	transform := &mock{executed: false, err: errors.New("an error")}
	docker := &mock{executed: false}
	clean := &mock{executed: false}
	NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{})
	assertEqual(false, docker.executed, t)
	assertEqual(false, clean.executed, t)
}

func Test_returnsTransformError(t *testing.T) {
	err := errors.New("an error")
	transform := &mock{executed: false, err: err}
	docker := &mock{executed: false}
	clean := &mock{executed: false}

	assertEqual(err, NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{}), t)
}

func Test_cleanNotExecutedWhenDockerBuildFails(t *testing.T) {
	transform := &mock{executed: false}
	docker := &mock{executed: false, err: errors.New("an error")}
	clean := &mock{executed: false}
	NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{})
	assertEqual(false, clean.executed, t)
}

func Test_returnsDockerBuildError(t *testing.T) {
	err := errors.New("an error")
	transform := &mock{executed: false}
	docker := &mock{executed: false, err: err}
	clean := &mock{executed: false}

	assertEqual(err, NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{}), t)
}

func Test_returnsCleanError(t *testing.T) {
	err := errors.New("an error")
	transform := &mock{executed: false}
	docker := &mock{executed: false}
	clean := &mock{executed: false, err: err}

	assertEqual(err, NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{}), t)
}

func Test_executedAllWhenNoneFails(t *testing.T) {
	transform := &mock{executed: false}
	docker := &mock{executed: false}
	clean := &mock{executed: false}
	NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{})
	assertEqual(true, transform.executed, t)
	assertEqual(true, docker.executed, t)
	assertEqual(true, clean.executed, t)
}
<commit_msg>remove useless if<commit_after>package build

import (
	"errors"
	"github.com/tueftler/doget/dockerfile"
	"reflect"
	"testing"
)

func assertEqual(expect, actual interface{}, t *testing.T) {
	if !reflect.DeepEqual(expect, actual) {
		t.Errorf("Items not equal:\nexpected %q\nhave     %q\n", expect, actual)
	}
}

func Test_splitArgsRecognizesTransformArgs(t *testing.T) {
	transformArgs, _ := split([]string{"--doget-no-cache=true", "-t", "foo:bar", "--no-cache=true"})
	assertEqual([]string{"-no-cache", "true"}, transformArgs, t)
}

func Test_splitArgsRecognizesTransformArgWithoutValue(t *testing.T) {
	transformArgs, _ := split([]string{"-t", "foo:bar", "--doget-clean", "--no-cache=true"})
	assertEqual([]string{"-clean"}, transformArgs, t)
}

func Test_splitArgsRecognizesDockerBuildArgs(t *testing.T) {
	_, dockerArgs := split([]string{"-t", "foo:bar", "--no-cache=true", "--doget-no-cache=true", "."})
	assertEqual([]string{"-t", "foo:bar", "--no-cache=true", "."}, dockerArgs, t)
}

func Test_transformArgsAreEmptyWhenOnlyDockerArgsPresent(t *testing.T) {
	transformArgs, _ := split([]string{"--no-cache=true"})
	assertEqual([]string{}, transformArgs, t)
}

func Test_dockerArgsAreEmptyWhenOnlyTransformArgsPresent(t *testing.T) {
	_, dockerArgs := split([]string{"--doget-no-cache=true"})
	assertEqual([]string{}, dockerArgs, t)
}

type mock struct {
	executed bool
	err      error
}

func (m *mock) Build(args []string) error {
	m.executed = true
	if nil != m.err {
		return m.err
	}

	return nil
}

func (m *mock) Init(name string) {
	// intentionally empty
}

func (m *mock) Run(parser *dockerfile.Parser, args []string) error {
	m.executed = true
	return m.err
}

func Test_dockerBuildNotExecutedWhenTransformFails(t *testing.T) {
	transform := &mock{executed: false, err: errors.New("an error")}
	docker := &mock{executed: false}
	clean := &mock{executed: false}
	NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{})
	assertEqual(false, docker.executed, t)
	assertEqual(false, clean.executed, t)
}

func Test_returnsTransformError(t *testing.T) {
	err := errors.New("an error")
	transform := &mock{executed: false, err: err}
	docker := &mock{executed: false}
	clean := &mock{executed: false}

	assertEqual(err, NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{}), t)
}

func Test_cleanNotExecutedWhenDockerBuildFails(t *testing.T) {
	transform := &mock{executed: false}
	docker := &mock{executed: false, err: errors.New("an error")}
	clean := &mock{executed: false}
	NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{})
	assertEqual(false, clean.executed, t)
}

func Test_returnsDockerBuildError(t *testing.T) {
	err := errors.New("an error")
	transform := &mock{executed: false}
	docker := &mock{executed: false, err: err}
	clean := &mock{executed: false}

	assertEqual(err, NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{}), t)
}

func Test_returnsCleanError(t *testing.T) {
	err := errors.New("an error")
	transform := &mock{executed: false}
	docker := &mock{executed: false}
	clean := &mock{executed: false, err: err}

	assertEqual(err, NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{}), t)
}

func Test_executedAllWhenNoneFails(t *testing.T) {
	transform := &mock{executed: false}
	docker := &mock{executed: false}
	clean := &mock{executed: false}
	NewCommand("build", transform, clean, docker).Run(dockerfile.NewParser(), []string{})
	assertEqual(true, transform.executed, t)
	assertEqual(true, docker.executed, t)
	assertEqual(true, clean.executed, t)
}
<|endoftext|>


<commit_before>// +build !js

package webrtc

import (
	"log"
	"strings"

	org "github.com/keroserene/go-webrtc"
)

func find(s []string, search string) int {
	for i := 0; i < len(s); i++ {
		if strings.ToLower(s[i]) == strings.ToLower(search) {
			return i
		}
	}
	return -1
}

// PeerConnection ...
type PeerConnection struct {
	pc *org.PeerConnection
}

// NewPeerConnection ...
func NewPeerConnection(config *Configuration) (*PeerConnection, error) {
	conf := org.NewConfiguration()
	for _, s := range config.IceServers {
		args := []string{strings.Join(s.Urls, ",")}
		if len(s.Username) > 0 {
			args = append(args, s.Username)
		}
		if len(s.Credential) > 0 {
			args = append(args, s.Credential)
		}
		if err := conf.AddIceServer(args...); err != nil {
			return nil, err
		}
	}
	conf.BundlePolicy = org.BundlePolicy(find(org.BundlePolicyString, config.BundlePolicy))
	conf.IceTransportPolicy = org.IceTransportPolicy(find(
		org.IceTransportPolicyString, config.IceTransportPolicy))
	conf.PeerIdentity = config.PeerIdentity
	pc, err := org.NewPeerConnection(conf)
	if err != nil {
		return nil, err
	}
	return &PeerConnection{pc: pc}, nil
}

// OnNegotiationNeeded ...
func (pc *PeerConnection) OnNegotiationNeeded(cb func()) {
	pc.pc.OnNegotiationNeeded = cb
}

// OnIceCandidate ...
func (pc *PeerConnection) OnIceCandidate(cb func(*IceCandidate)) {
	pc.pc.OnIceCandidate = func(ic org.IceCandidate) {
		log.Println("ice:", ic)
		cb(&IceCandidate{
			Candidate:     ic.Candidate,
			SdpMid:        ic.SdpMid,
			SdpMLineIndex: ic.SdpMLineIndex,
		})
	}
}

// OnIceCandidateError ...
func (pc *PeerConnection) OnIceCandidateError(cb func()) {
	pc.pc.OnIceCandidateError = cb
}

// OnSignalingStateChange ...
func (pc *PeerConnection) OnSignalingStateChange(cb func(SignalingState string)) {
	pc.pc.OnSignalingStateChange = func(s org.SignalingState) {
		cb(org.SignalingStateString[s])
	}
}

// OnIceConnectionStateChange ...
func (pc *PeerConnection) OnIceConnectionStateChange(cb func(IceConnectionState string)) {
	pc.pc.OnIceConnectionStateChange = func(s org.IceConnectionState) {
		cb(org.IceConnectionStateString[s])
	}
}

// OnIceGatheringStateChange ...
func (pc *PeerConnection) OnIceGatheringStateChange(cb func(IceGatheringState string)) {
	pc.pc.OnIceGatheringStateChange = func(s org.IceGatheringState) {
		cb(org.IceGatheringStateString[s])
	}
}

// OnConnectionStateChange ...
func (pc *PeerConnection) OnConnectionStateChange(cb func(PeerConnectionState string)) {
	pc.pc.OnConnectionStateChange = func(s org.PeerConnectionState) {
		cb(org.PeerConnectionStateString[s])
	}
}

// OnDataChannel ...
func (pc *PeerConnection) OnDataChannel(cb func(*DataChannel)) {
	pc.pc.OnDataChannel = func(dc *org.DataChannel) {
		cb(&DataChannel{
			dc: dc,
		})
	}
}

// OnAddStream ...
func (pc *PeerConnection) OnAddStream(cb func(*MediaStream)) {}

// OnRemoveStream ...
func (pc *PeerConnection) OnRemoveStream(cb func(*MediaStream)) {}

// AddStream ...
func (pc *PeerConnection) AddStream(stream *MediaStream) (err error) { return nil }

// AddIceCandidate ...
func (pc *PeerConnection) AddIceCandidate(ic *IceCandidate) error {
	return pc.pc.AddIceCandidate(org.IceCandidate{
		Candidate:     ic.Candidate,
		SdpMid:        ic.SdpMid,
		SdpMLineIndex: ic.SdpMLineIndex,
	})
}

// Close ...
func (pc *PeerConnection) Close() error {
	return pc.pc.Close()
}

// ConnectionState ...
func (pc *PeerConnection) ConnectionState() string {
	return org.PeerConnectionStateString[pc.pc.ConnectionState()]
}

// CreateAnswer ...
func (pc *PeerConnection) CreateAnswer() (*SessionDescription, error) {
	sd, err := pc.pc.CreateAnswer()
	if err != nil {
		return nil, err
	}
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}, nil
}

// CreateDataChannel ...
func (pc *PeerConnection) CreateDataChannel(label string) (*DataChannel, error) {
	dc, err := pc.pc.CreateDataChannel(label, org.Init{})
	if err != nil {
		return nil, err
	}
	return &DataChannel{dc}, nil
}

// CreateOffer ...
func (pc *PeerConnection) CreateOffer() (*SessionDescription, error) {
	sd, err := pc.pc.CreateOffer()
	if err != nil {
		return nil, err
	}
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}, nil
}

// IceGatheringState ...
func (pc *PeerConnection) IceGatheringState() string {
	return ""
}

// LocalDescription ...
func (pc *PeerConnection) LocalDescription() (sdp *SessionDescription) {
	sd := pc.pc.LocalDescription()
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}
}

// RemoteDescription ...
func (pc *PeerConnection) RemoteDescription() (sdp *SessionDescription) {
	sd := pc.pc.RemoteDescription()
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}
}

// SetLocalDescription ...
func (pc *PeerConnection) SetLocalDescription(sdp *SessionDescription) error {
	return pc.pc.SetLocalDescription(&org.SessionDescription{
		Type: sdp.Type,
		Sdp:  sdp.Sdp,
	})
}

// SetRemoteDescription ...
func (pc *PeerConnection) SetRemoteDescription(sdp *SessionDescription) error {
	return pc.pc.SetRemoteDescription(&org.SessionDescription{
		Type: sdp.Type,
		Sdp:  sdp.Sdp,
	})
}

// SignalingState ...
func (pc *PeerConnection) SignalingState() string {
	return org.SignalingStateString[pc.pc.SignalingState()]
}

// DataChannel ...
type DataChannel struct {
	dc *org.DataChannel
}

// OnOpen ...
func (c *DataChannel) OnOpen(cb func()) {
	c.dc.OnOpen = cb
}

// OnClose ...
func (c *DataChannel) OnClose(cb func()) {
	c.dc.OnClose = cb
}

// OnMessage ...
func (c *DataChannel) OnMessage(cb func([]byte)) {
	c.dc.OnMessage = cb
}

// Close ...
func (c *DataChannel) Close() error {
	return c.dc.Close()
}

// ID ...
func (c *DataChannel) ID() int {
	return c.dc.ID()
}

// ReadyState ...
func (c *DataChannel) ReadyState() string {
	return ""
}

// Send ...
func (c *DataChannel) Send(data []byte) {
	c.dc.Send(data)
}

// Label ...
func (c *DataChannel) Label() string {
	return c.dc.Label()
}

// MediaStream ...
type MediaStream struct{}

// GetUserMedia ...
func GetUserMedia(constraints *Constraints) (stream *MediaStream, err error) {
	panic("not supported")
}
<commit_msg>default verbosity 0<commit_after>// +build !js

package webrtc

import (
	"log"
	"strings"

	org "github.com/keroserene/go-webrtc"
)

func init() {
	org.SetLoggingVerbosity(0)
}

func find(s []string, search string) int {
	for i := 0; i < len(s); i++ {
		if strings.ToLower(s[i]) == strings.ToLower(search) {
			return i
		}
	}
	return -1
}

// PeerConnection ...
type PeerConnection struct {
	pc *org.PeerConnection
}

// NewPeerConnection ...
func NewPeerConnection(config *Configuration) (*PeerConnection, error) {
	conf := org.NewConfiguration()
	for _, s := range config.IceServers {
		args := []string{strings.Join(s.Urls, ",")}
		if len(s.Username) > 0 {
			args = append(args, s.Username)
		}
		if len(s.Credential) > 0 {
			args = append(args, s.Credential)
		}
		if err := conf.AddIceServer(args...); err != nil {
			return nil, err
		}
	}
	conf.BundlePolicy = org.BundlePolicy(find(org.BundlePolicyString, config.BundlePolicy))
	conf.IceTransportPolicy = org.IceTransportPolicy(find(
		org.IceTransportPolicyString, config.IceTransportPolicy))
	conf.PeerIdentity = config.PeerIdentity
	pc, err := org.NewPeerConnection(conf)
	if err != nil {
		return nil, err
	}
	return &PeerConnection{pc: pc}, nil
}

// OnNegotiationNeeded ...
func (pc *PeerConnection) OnNegotiationNeeded(cb func()) {
	pc.pc.OnNegotiationNeeded = cb
}

// OnIceCandidate ...
func (pc *PeerConnection) OnIceCandidate(cb func(*IceCandidate)) {
	pc.pc.OnIceCandidate = func(ic org.IceCandidate) {
		log.Println("ice:", ic)
		cb(&IceCandidate{
			Candidate:     ic.Candidate,
			SdpMid:        ic.SdpMid,
			SdpMLineIndex: ic.SdpMLineIndex,
		})
	}
}

// OnIceCandidateError ...
func (pc *PeerConnection) OnIceCandidateError(cb func()) {
	pc.pc.OnIceCandidateError = cb
}

// OnSignalingStateChange ...
func (pc *PeerConnection) OnSignalingStateChange(cb func(SignalingState string)) {
	pc.pc.OnSignalingStateChange = func(s org.SignalingState) {
		cb(org.SignalingStateString[s])
	}
}

// OnIceConnectionStateChange ...
func (pc *PeerConnection) OnIceConnectionStateChange(cb func(IceConnectionState string)) {
	pc.pc.OnIceConnectionStateChange = func(s org.IceConnectionState) {
		cb(org.IceConnectionStateString[s])
	}
}

// OnIceGatheringStateChange ...
func (pc *PeerConnection) OnIceGatheringStateChange(cb func(IceGatheringState string)) {
	pc.pc.OnIceGatheringStateChange = func(s org.IceGatheringState) {
		cb(org.IceGatheringStateString[s])
	}
}

// OnConnectionStateChange ...
func (pc *PeerConnection) OnConnectionStateChange(cb func(PeerConnectionState string)) {
	pc.pc.OnConnectionStateChange = func(s org.PeerConnectionState) {
		cb(org.PeerConnectionStateString[s])
	}
}

// OnDataChannel ...
func (pc *PeerConnection) OnDataChannel(cb func(*DataChannel)) {
	pc.pc.OnDataChannel = func(dc *org.DataChannel) {
		cb(&DataChannel{
			dc: dc,
		})
	}
}

// OnAddStream ...
func (pc *PeerConnection) OnAddStream(cb func(*MediaStream)) {}

// OnRemoveStream ...
func (pc *PeerConnection) OnRemoveStream(cb func(*MediaStream)) {}

// AddStream ...
func (pc *PeerConnection) AddStream(stream *MediaStream) (err error) { return nil }

// AddIceCandidate ...
func (pc *PeerConnection) AddIceCandidate(ic *IceCandidate) error {
	return pc.pc.AddIceCandidate(org.IceCandidate{
		Candidate:     ic.Candidate,
		SdpMid:        ic.SdpMid,
		SdpMLineIndex: ic.SdpMLineIndex,
	})
}

// Close ...
func (pc *PeerConnection) Close() error {
	return pc.pc.Close()
}

// ConnectionState ...
func (pc *PeerConnection) ConnectionState() string {
	return org.PeerConnectionStateString[pc.pc.ConnectionState()]
}

// CreateAnswer ...
func (pc *PeerConnection) CreateAnswer() (*SessionDescription, error) {
	sd, err := pc.pc.CreateAnswer()
	if err != nil {
		return nil, err
	}
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}, nil
}

// CreateDataChannel ...
func (pc *PeerConnection) CreateDataChannel(label string) (*DataChannel, error) {
	dc, err := pc.pc.CreateDataChannel(label, org.Init{})
	if err != nil {
		return nil, err
	}
	return &DataChannel{dc}, nil
}

// CreateOffer ...
func (pc *PeerConnection) CreateOffer() (*SessionDescription, error) {
	sd, err := pc.pc.CreateOffer()
	if err != nil {
		return nil, err
	}
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}, nil
}

// IceGatheringState ...
func (pc *PeerConnection) IceGatheringState() string {
	return ""
}

// LocalDescription ...
func (pc *PeerConnection) LocalDescription() (sdp *SessionDescription) {
	sd := pc.pc.LocalDescription()
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}
}

// RemoteDescription ...
func (pc *PeerConnection) RemoteDescription() (sdp *SessionDescription) {
	sd := pc.pc.RemoteDescription()
	return &SessionDescription{
		Type: sd.Type,
		Sdp:  sd.Sdp,
	}
}

// SetLocalDescription ...
func (pc *PeerConnection) SetLocalDescription(sdp *SessionDescription) error {
	return pc.pc.SetLocalDescription(&org.SessionDescription{
		Type: sdp.Type,
		Sdp:  sdp.Sdp,
	})
}

// SetRemoteDescription ...
func (pc *PeerConnection) SetRemoteDescription(sdp *SessionDescription) error {
	return pc.pc.SetRemoteDescription(&org.SessionDescription{
		Type: sdp.Type,
		Sdp:  sdp.Sdp,
	})
}

// SignalingState ...
func (pc *PeerConnection) SignalingState() string {
	return org.SignalingStateString[pc.pc.SignalingState()]
}

// DataChannel ...
type DataChannel struct {
	dc *org.DataChannel
}

// OnOpen ...
func (c *DataChannel) OnOpen(cb func()) {
	c.dc.OnOpen = cb
}

// OnClose ...
func (c *DataChannel) OnClose(cb func()) {
	c.dc.OnClose = cb
}

// OnMessage ...
func (c *DataChannel) OnMessage(cb func([]byte)) {
	c.dc.OnMessage = cb
}

// Close ...
func (c *DataChannel) Close() error {
	return c.dc.Close()
}

// ID ...
func (c *DataChannel) ID() int {
	return c.dc.ID()
}

// ReadyState ...
func (c *DataChannel) ReadyState() string {
	return ""
}

// Send ...
func (c *DataChannel) Send(data []byte) {
	c.dc.Send(data)
}

// Label ...
func (c *DataChannel) Label() string {
	return c.dc.Label()
}

// MediaStream ...
type MediaStream struct{}

// GetUserMedia ...
func GetUserMedia(constraints *Constraints) (stream *MediaStream, err error) {
	panic("not supported")
}
<|endoftext|>


<commit_before>package models

import (
	"time"

	envmanModels "github.com/bitrise-io/envman/models"
)

// StepSourceModel ...
type StepSourceModel struct {
	Git    string `json:"git,omitempty" yaml:"git,omitempty"`
	Commit string `json:"commit,omitempty" yaml:"commit,omitempty"`
}

// DependencyModel ...
type DependencyModel struct {
	Manager string `json:"manager,omitempty" yaml:"manager,omitempty"`
	Name    string `json:"name,omitempty" yaml:"name,omitempty"`
}

// BrewDepModel ...
type BrewDepModel struct {
	// Name is the package name for Brew
	Name string `json:"name,omitempty" yaml:"name,omitempty"`
	// BinName is the binary's name, if it doesn't match the package's name.
	// Can be used for e.g. calling `which`.
	// E.g. in case of "AWS CLI" the package is `awscli` and the binary is `aws`.
	// If BinName is empty Name will be used as BinName too.
	BinName string `json:"bin_name,omitempty" yaml:"bin_name,omitempty"`
}

// AptGetDepModel ...
type AptGetDepModel struct {
	// Name is the package name for Apt-get
	Name string `json:"name,omitempty" yaml:"name,omitempty"`
	// BinName is the binary's name, if it doesn't match the package's name.
	// Can be used for e.g. calling `which`.
	// E.g. in case of "AWS CLI" the package is `awscli` and the binary is `aws`.
	// If BinName is empty Name will be used as BinName too.
	BinName string `json:"bin_name,omitempty" yaml:"bin_name,omitempty"`
}

// DepsModel ...
type DepsModel struct {
	Brew   []BrewDepModel   `json:"brew,omitempty" yaml:"brew,omitempty"`
	AptGet []AptGetDepModel `json:"apt_get,omitempty" yaml:"apt_get,omitempty"`
}

// BashStepToolkitModel ...
type BashStepToolkitModel struct {
	EntryFile string `json:"entry_file,omitempty" yaml:"entry_file,omitempty"`
}

// GoStepToolkitModel ...
type GoStepToolkitModel struct {
	// PackageName - required
	PackageName string `json:"package_name" yaml:"package_name"`
}

// SwiftStepToolkitModel ...
type SwiftStepToolkitModel struct {
	BinaryLocation string `json:"binary_location,omitempty" yaml:"binary_location,omitempty"`
	ExecutableName string `json:"executable_name,omitempty" yaml:"executable_name,omitempty"`
}

// StepToolkitModel ...
type StepToolkitModel struct {
	Bash  *BashStepToolkitModel  `json:"bash,omitempty" yaml:"bash,omitempty"`
	Go    *GoStepToolkitModel    `json:"go,omitempty" yaml:"go,omitempty"`
	Swift *SwiftStepToolkitModel `json:"swift,omitempty" yaml:"swift,omitempty"`
}

// StepModel ...
type StepModel struct {
	Title       *string `json:"title,omitempty" yaml:"title,omitempty"`
	Summary     *string `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description *string `json:"description,omitempty" yaml:"description,omitempty"`
	//
	Website       *string `json:"website,omitempty" yaml:"website,omitempty"`
	SourceCodeURL *string `json:"source_code_url,omitempty" yaml:"source_code_url,omitempty"`
	SupportURL    *string `json:"support_url,omitempty" yaml:"support_url,omitempty"`
	// auto-generated at share
	PublishedAt *time.Time        `json:"published_at,omitempty" yaml:"published_at,omitempty"`
	Source      *StepSourceModel  `json:"source,omitempty" yaml:"source,omitempty"`
	AssetURLs   map[string]string `json:"asset_urls,omitempty" yaml:"asset_urls,omitempty"`
	//
	HostOsTags          []string          `json:"host_os_tags,omitempty" yaml:"host_os_tags,omitempty"`
	ProjectTypeTags     []string          `json:"project_type_tags,omitempty" yaml:"project_type_tags,omitempty"`
	TypeTags            []string          `json:"type_tags,omitempty" yaml:"type_tags,omitempty"`
	Dependencies        []DependencyModel `json:"dependencies,omitempty" yaml:"dependencies,omitempty"`
	Toolkit             *StepToolkitModel `json:"toolkit,omitempty" yaml:"toolkit,omitempty"`
	Deps                *DepsModel        `json:"deps,omitempty" yaml:"deps,omitempty"`
	IsRequiresAdminUser *bool             `json:"is_requires_admin_user,omitempty" yaml:"is_requires_admin_user,omitempty"`
	// IsAlwaysRun : if true then this step will always run,
	//  even if a previous step fails.
	IsAlwaysRun *bool `json:"is_always_run,omitempty" yaml:"is_always_run,omitempty"`
	// IsSkippable : if true and this step fails the build will still continue.
	//  If false then the build will be marked as failed and only those
	//  steps will run which are marked with IsAlwaysRun.
	IsSkippable *bool `json:"is_skippable,omitempty" yaml:"is_skippable,omitempty"`
	// RunIf : only run the step if the template example evaluates to true
	RunIf   *string                `json:"run_if,omitempty" yaml:"run_if,omitempty"`
	Timeout *int                   `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	Meta    map[string]interface{} `json:"meta,omitempty" yaml:"meta,omitempty"`
	//
	Inputs  []envmanModels.EnvironmentItemModel `json:"inputs,omitempty" yaml:"inputs,omitempty"`
	Outputs []envmanModels.EnvironmentItemModel `json:"outputs,omitempty" yaml:"outputs,omitempty"`
}

// StepVersionModel ...
type StepVersionModel struct {
	Step                   StepModel
	Version                string
	LatestAvailableVersion string
}

// StepGroupInfoModel ...
type StepGroupInfoModel struct {
	RemovalDate    string            `json:"removal_date,omitempty" yaml:"removal_date,omitempty"`
	DeprecateNotes string            `json:"deprecate_notes,omitempty" yaml:"deprecate_notes,omitempty"`
	AssetURLs      map[string]string `json:"asset_urls,omitempty" yaml:"asset_urls,omitempty"`
	Maintainer     string            `json:"maintainer,omitempty" yaml:"maintainer,omitempty"`
}

// StepGroupModel ...
type StepGroupModel struct {
	Info                StepGroupInfoModel   `json:"info,omitempty" yaml:"info,omitempty"`
	LatestVersionNumber string               `json:"latest_version_number,omitempty" yaml:"latest_version_number,omitempty"`
	Versions            map[string]StepModel `json:"versions,omitempty" yaml:"versions,omitempty"`
}

// LatestVersion ...
func (stepGroup StepGroupModel) LatestVersion() (StepModel, bool) {
	step, found := stepGroup.Versions[stepGroup.LatestVersionNumber]
	if !found {
		return StepModel{}, false
	}
	return step, true
}

// StepHash ...
type StepHash map[string]StepGroupModel

// DownloadLocationModel ...
type DownloadLocationModel struct {
	Type string `json:"type"`
	Src  string `json:"src"`
}

// StepCollectionModel ...
type StepCollectionModel struct {
	FormatVersion         string                  `json:"format_version" yaml:"format_version"`
	GeneratedAtTimeStamp  int64                   `json:"generated_at_timestamp" yaml:"generated_at_timestamp"`
	SteplibSource         string                  `json:"steplib_source" yaml:"steplib_source"`
	DownloadLocations     []DownloadLocationModel `json:"download_locations" yaml:"download_locations"`
	AssetsDownloadBaseURI string                  `json:"assets_download_base_uri" yaml:"assets_download_base_uri"`
	Steps                 StepHash                `json:"steps" yaml:"steps"`
}

// EnvInfoModel ...
type EnvInfoModel struct {
	Key          string   `json:"key,omitempty" yaml:"key,omitempty"`
	Title        string   `json:"title,omitempty" yaml:"title,omitempty"`
	Description  string   `json:"description,omitempty" yaml:"description,omitempty"`
	ValueOptions []string `json:"value_options,omitempty" yaml:"value_options,omitempty"`
	DefaultValue string   `json:"default_value,omitempty" yaml:"default_value,omitempty"`
	IsExpand     bool     `json:"is_expand" yaml:"is_expand"`
	IsSensitive  bool     `json:"is_sensitive" yaml:"is_sensitive"`
}

// StepInfoModel ...
type StepInfoModel struct {
	Library         string             `json:"library,omitempty" yaml:"library,omitempty"`
	ID              string             `json:"id,omitempty" yaml:"id,omitempty"`
	Version         string             `json:"version,omitempty" yaml:"version,omitempty"`
	OriginalVersion string             `json:"original_version,omitempty" yaml:"original_version,omitempty"`
	LatestVersion   string             `json:"latest_version,omitempty" yaml:"latest_version,omitempty"`
	GroupInfo       StepGroupInfoModel `json:"info,omitempty" yaml:"info,omitempty"`
	Step            StepModel          `json:"step,omitempty" yaml:"step,omitempty"`
	DefinitionPth   string             `json:"definition_pth,omitempty" yaml:"definition_pth,omitempty"`
}

// StepListModel ...
type StepListModel struct {
	StepLib string   `json:"steplib,omitempty" yaml:"steplib,omitempty"`
	Steps   []string `json:"steps,omitempty" yaml:"steps,omitempty"`
}

// SteplibInfoModel ...
type SteplibInfoModel struct {
	URI      string `json:"uri,omitempty" yaml:"uri,omitempty"`
	SpecPath string `json:"spec_path,omitempty" yaml:"spec_path,omitempty"`
}
<commit_msg>Add kotlin support (#308)<commit_after>package models

import (
	"time"

	envmanModels "github.com/bitrise-io/envman/models"
)

// StepSourceModel ...
type StepSourceModel struct {
	Git    string `json:"git,omitempty" yaml:"git,omitempty"`
	Commit string `json:"commit,omitempty" yaml:"commit,omitempty"`
}

// DependencyModel ...
type DependencyModel struct {
	Manager string `json:"manager,omitempty" yaml:"manager,omitempty"`
	Name    string `json:"name,omitempty" yaml:"name,omitempty"`
}

// BrewDepModel ...
type BrewDepModel struct {
	// Name is the package name for Brew
	Name string `json:"name,omitempty" yaml:"name,omitempty"`
	// BinName is the binary's name, if it doesn't match the package's name.
	// Can be used for e.g. calling `which`.
	// E.g. in case of "AWS CLI" the package is `awscli` and the binary is `aws`.
	// If BinName is empty Name will be used as BinName too.
	BinName string `json:"bin_name,omitempty" yaml:"bin_name,omitempty"`
}

// AptGetDepModel ...
type AptGetDepModel struct {
	// Name is the package name for Apt-get
	Name string `json:"name,omitempty" yaml:"name,omitempty"`
	// BinName is the binary's name, if it doesn't match the package's name.
	// Can be used for e.g. calling `which`.
	// E.g. in case of "AWS CLI" the package is `awscli` and the binary is `aws`.
	// If BinName is empty Name will be used as BinName too.
	BinName string `json:"bin_name,omitempty" yaml:"bin_name,omitempty"`
}

// DepsModel ...
type DepsModel struct {
	Brew   []BrewDepModel   `json:"brew,omitempty" yaml:"brew,omitempty"`
	AptGet []AptGetDepModel `json:"apt_get,omitempty" yaml:"apt_get,omitempty"`
}

// BashStepToolkitModel ...
type BashStepToolkitModel struct {
	EntryFile string `json:"entry_file,omitempty" yaml:"entry_file,omitempty"`
}

// GoStepToolkitModel ...
type GoStepToolkitModel struct {
	// PackageName - required
	PackageName string `json:"package_name" yaml:"package_name"`
}

// SwiftStepToolkitModel ...
type SwiftStepToolkitModel struct {
	BinaryLocation string `json:"binary_location,omitempty" yaml:"binary_location,omitempty"`
	ExecutableName string `json:"executable_name,omitempty" yaml:"executable_name,omitempty"`
}

// KotlinStepToolkitModel ...
type KotlinStepToolkitModel struct {
	ExecutableName string `json:"executable_name,omitempty" yaml:"executable_name,omitempty"`
}

// StepToolkitModel ...
type StepToolkitModel struct {
	Bash  *BashStepToolkitModel  	`json:"bash,omitempty" yaml:"bash,omitempty"`
	Go    *GoStepToolkitModel    	`json:"go,omitempty" yaml:"go,omitempty"`
	Swift *SwiftStepToolkitModel 	`json:"swift,omitempty" yaml:"swift,omitempty"`
	Kotlin *KotlinStepToolkitModel 	`json:"kotlin,omitempty" yaml:"kotlin,omitempty"`
}

// StepModel ...
type StepModel struct {
	Title       *string `json:"title,omitempty" yaml:"title,omitempty"`
	Summary     *string `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description *string `json:"description,omitempty" yaml:"description,omitempty"`
	//
	Website       *string `json:"website,omitempty" yaml:"website,omitempty"`
	SourceCodeURL *string `json:"source_code_url,omitempty" yaml:"source_code_url,omitempty"`
	SupportURL    *string `json:"support_url,omitempty" yaml:"support_url,omitempty"`
	// auto-generated at share
	PublishedAt *time.Time        `json:"published_at,omitempty" yaml:"published_at,omitempty"`
	Source      *StepSourceModel  `json:"source,omitempty" yaml:"source,omitempty"`
	AssetURLs   map[string]string `json:"asset_urls,omitempty" yaml:"asset_urls,omitempty"`
	//
	HostOsTags          []string          `json:"host_os_tags,omitempty" yaml:"host_os_tags,omitempty"`
	ProjectTypeTags     []string          `json:"project_type_tags,omitempty" yaml:"project_type_tags,omitempty"`
	TypeTags            []string          `json:"type_tags,omitempty" yaml:"type_tags,omitempty"`
	Dependencies        []DependencyModel `json:"dependencies,omitempty" yaml:"dependencies,omitempty"`
	Toolkit             *StepToolkitModel `json:"toolkit,omitempty" yaml:"toolkit,omitempty"`
	Deps                *DepsModel        `json:"deps,omitempty" yaml:"deps,omitempty"`
	IsRequiresAdminUser *bool             `json:"is_requires_admin_user,omitempty" yaml:"is_requires_admin_user,omitempty"`
	// IsAlwaysRun : if true then this step will always run,
	//  even if a previous step fails.
	IsAlwaysRun *bool `json:"is_always_run,omitempty" yaml:"is_always_run,omitempty"`
	// IsSkippable : if true and this step fails the build will still continue.
	//  If false then the build will be marked as failed and only those
	//  steps will run which are marked with IsAlwaysRun.
	IsSkippable *bool `json:"is_skippable,omitempty" yaml:"is_skippable,omitempty"`
	// RunIf : only run the step if the template example evaluates to true
	RunIf   *string                `json:"run_if,omitempty" yaml:"run_if,omitempty"`
	Timeout *int                   `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	Meta    map[string]interface{} `json:"meta,omitempty" yaml:"meta,omitempty"`
	//
	Inputs  []envmanModels.EnvironmentItemModel `json:"inputs,omitempty" yaml:"inputs,omitempty"`
	Outputs []envmanModels.EnvironmentItemModel `json:"outputs,omitempty" yaml:"outputs,omitempty"`
}

// StepVersionModel ...
type StepVersionModel struct {
	Step                   StepModel
	Version                string
	LatestAvailableVersion string
}

// StepGroupInfoModel ...
type StepGroupInfoModel struct {
	RemovalDate    string            `json:"removal_date,omitempty" yaml:"removal_date,omitempty"`
	DeprecateNotes string            `json:"deprecate_notes,omitempty" yaml:"deprecate_notes,omitempty"`
	AssetURLs      map[string]string `json:"asset_urls,omitempty" yaml:"asset_urls,omitempty"`
	Maintainer     string            `json:"maintainer,omitempty" yaml:"maintainer,omitempty"`
}

// StepGroupModel ...
type StepGroupModel struct {
	Info                StepGroupInfoModel   `json:"info,omitempty" yaml:"info,omitempty"`
	LatestVersionNumber string               `json:"latest_version_number,omitempty" yaml:"latest_version_number,omitempty"`
	Versions            map[string]StepModel `json:"versions,omitempty" yaml:"versions,omitempty"`
}

// LatestVersion ...
func (stepGroup StepGroupModel) LatestVersion() (StepModel, bool) {
	step, found := stepGroup.Versions[stepGroup.LatestVersionNumber]
	if !found {
		return StepModel{}, false
	}
	return step, true
}

// StepHash ...
type StepHash map[string]StepGroupModel

// DownloadLocationModel ...
type DownloadLocationModel struct {
	Type string `json:"type"`
	Src  string `json:"src"`
}

// StepCollectionModel ...
type StepCollectionModel struct {
	FormatVersion         string                  `json:"format_version" yaml:"format_version"`
	GeneratedAtTimeStamp  int64                   `json:"generated_at_timestamp" yaml:"generated_at_timestamp"`
	SteplibSource         string                  `json:"steplib_source" yaml:"steplib_source"`
	DownloadLocations     []DownloadLocationModel `json:"download_locations" yaml:"download_locations"`
	AssetsDownloadBaseURI string                  `json:"assets_download_base_uri" yaml:"assets_download_base_uri"`
	Steps                 StepHash                `json:"steps" yaml:"steps"`
}

// EnvInfoModel ...
type EnvInfoModel struct {
	Key          string   `json:"key,omitempty" yaml:"key,omitempty"`
	Title        string   `json:"title,omitempty" yaml:"title,omitempty"`
	Description  string   `json:"description,omitempty" yaml:"description,omitempty"`
	ValueOptions []string `json:"value_options,omitempty" yaml:"value_options,omitempty"`
	DefaultValue string   `json:"default_value,omitempty" yaml:"default_value,omitempty"`
	IsExpand     bool     `json:"is_expand" yaml:"is_expand"`
	IsSensitive  bool     `json:"is_sensitive" yaml:"is_sensitive"`
}

// StepInfoModel ...
type StepInfoModel struct {
	Library         string             `json:"library,omitempty" yaml:"library,omitempty"`
	ID              string             `json:"id,omitempty" yaml:"id,omitempty"`
	Version         string             `json:"version,omitempty" yaml:"version,omitempty"`
	OriginalVersion string             `json:"original_version,omitempty" yaml:"original_version,omitempty"`
	LatestVersion   string             `json:"latest_version,omitempty" yaml:"latest_version,omitempty"`
	GroupInfo       StepGroupInfoModel `json:"info,omitempty" yaml:"info,omitempty"`
	Step            StepModel          `json:"step,omitempty" yaml:"step,omitempty"`
	DefinitionPth   string             `json:"definition_pth,omitempty" yaml:"definition_pth,omitempty"`
}

// StepListModel ...
type StepListModel struct {
	StepLib string   `json:"steplib,omitempty" yaml:"steplib,omitempty"`
	Steps   []string `json:"steps,omitempty" yaml:"steps,omitempty"`
}

// SteplibInfoModel ...
type SteplibInfoModel struct {
	URI      string `json:"uri,omitempty" yaml:"uri,omitempty"`
	SpecPath string `json:"spec_path,omitempty" yaml:"spec_path,omitempty"`
}
<|endoftext|>


<commit_before>package instructions

import "jvmgo/rtda"

// Convert int to byte
type i2b struct {}
func (self *i2b) fetchOperands(bcr *BytecodeReader) {}
func (self *i2b) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    b := int32(int8(i))
    stack.PushInt(b)
}

// Convert int to char
type i2c struct {}
func (self *i2c) fetchOperands(bcr *BytecodeReader) {}
func (self *i2c) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    c := int32(uint16(i))
    stack.PushInt(c)
}

// Convert int to double
type i2d struct {}
func (self *i2d) fetchOperands(bcr *BytecodeReader) {}
func (self *i2d) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    d := float64(i)
    stack.PushDouble(d)
}

// Convert int to float
type i2f struct {}
func (self *i2f) fetchOperands(bcr *BytecodeReader) {}
func (self *i2f) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    f := float32(i)
    stack.PushFloat(f)
}

// Convert int to long
type i2l struct {}
func (self *i2l) fetchOperands(bcr *BytecodeReader) {}
func (self *i2l) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    l := int64(i)
    stack.PushLong(l)
}

// Convert int to short
type i2s struct {}
func (self *i2s) fetchOperands(bcr *BytecodeReader) {}
func (self *i2s) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    s := int32(int16(i))
    stack.PushInt(s)
}
<commit_msg>code refactor<commit_after>package instructions

import "jvmgo/rtda"

// Convert int to byte
type i2b struct {}
func (self *i2b) fetchOperands(bcr *BytecodeReader) {}
func (self *i2b) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    b := int32(int8(i))
    stack.PushInt(b)
}

// Convert int to char
type i2c struct {}
func (self *i2c) fetchOperands(bcr *BytecodeReader) {}
func (self *i2c) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    c := int32(uint16(i))
    stack.PushInt(c)
}

// Convert int to short
type i2s struct {}
func (self *i2s) fetchOperands(bcr *BytecodeReader) {}
func (self *i2s) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    s := int32(int16(i))
    stack.PushInt(s)
}

// Convert int to long
type i2l struct {}
func (self *i2l) fetchOperands(bcr *BytecodeReader) {}
func (self *i2l) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    l := int64(i)
    stack.PushLong(l)
}

// Convert int to float
type i2f struct {}
func (self *i2f) fetchOperands(bcr *BytecodeReader) {}
func (self *i2f) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    f := float32(i)
    stack.PushFloat(f)
}

// Convert int to double
type i2d struct {}
func (self *i2d) fetchOperands(bcr *BytecodeReader) {}
func (self *i2d) execute(thread *rtda.Thread) {
    stack := thread.CurrentFrame().OperandStack()
    i := stack.PopInt()
    d := float64(i)
    stack.PushDouble(d)
}
<|endoftext|>


<commit_before>package main

import (
    . "github.com/onsi/ginkgo"
    . "github.com/onsi/gomega"
    "github.com/onsi/gomega/gexec"
    "github.com/onsi/gomega/gbytes"
    "os/exec"
)

var _ = Describe("Mustache", func() {
    successDecodeOutput := map[string]interface{}{"key":"val"}
    expectedTemplate := "my name is Montoooorb69 but you can call me Monica Rachel Pheobe.\n" +
        "I come from Cloooooooooooooooo in the Florbatorb galaxy.\n" +
        "I would like to Drink earth liquids, Kill the producers of 3rd Rock From The Sun, Go to Disney World.\n\n" +
        "Thank you,\nMontoooorb69"

    assertExampleSuccess := func(path string) {
        command := exec.Command(path)
        session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
        Expect(err).ShouldNot(HaveOccurred())
        Eventually(session.Out).Should(gbytes.Say(expectedTemplate))
        Eventually(session).Should(gexec.Exit(0))
    }

    Describe("When Cli is executed", func() {
        // These tests leverage the example scripts for ease of testing.
        Context("With data file", func() {
            It("should successfully output example template from JSON data source", func() {
                assertExampleSuccess("./examples/run-example-json")
            })

            It("should successfully output example template from YAML data source", func() {
                assertExampleSuccess("./examples/run-example-yaml")
            })
        })

        Context("From Stdin", func() {
            It("should successfully output example template", func() {
                assertExampleSuccess("./examples/run-example-stdin")
            })
        })
    })

    Describe("decodeData", func() {
        Context("When called with valid JSON data", func() {
            It("should decode JSON to a map", func() {
                json := []byte("{ \"key\": \"val\"}")
                data, _ := decodeData(json)
                Expect(data).To(Equal(successDecodeOutput))
            })
        })

        Context("When called with valid Yaml data", func() {
            It("Should decode YAML to a map", func() {
                input := []byte("key: val")
                data, _ := decodeData(input)
                Expect(data).To(Equal(successDecodeOutput))
            })
        })

        Context("When called with data in invalid format", func() {
            It("should fail to load malformatted JSON", func() {
                json := []byte("{ \"key\": %val%\"}")
                _, err := decodeData(json)
                expectedErr := "error converting YAML to JSON: yaml: " +
                    "[while scanning for the next token] found character that cannot start any token at line 1, column 10"
                Expect(err.Error()).To(Equal(expectedErr))
            })

            It("should error with invalid format", func() {
                yaml := []byte("key\": \"%val%\"}")
                _, err := decodeData(yaml)
                expectedErr := "error converting YAML to JSON: yaml: " +
                    "[while parsing a block mapping] did not find expected key at line 1, column 14"
                Expect(err.Error()).To(Equal(expectedErr))
            })
        })
    })
})
<commit_msg>Update to wait longer then a second.<commit_after>package main

import (
    . "github.com/onsi/ginkgo"
    . "github.com/onsi/gomega"
    "github.com/onsi/gomega/gexec"
    "github.com/onsi/gomega/gbytes"
    "os/exec"
    "time"
)

var _ = Describe("Mustache", func() {
    successDecodeOutput := map[string]interface{}{"key":"val"}
    expectedTemplate := "my name is Montoooorb69 but you can call me Monica Rachel Pheobe.\n" +
        "I come from Cloooooooooooooooo in the Florbatorb galaxy.\n" +
        "I would like to Drink earth liquids, Kill the producers of 3rd Rock From The Sun, Go to Disney World.\n\n" +
        "Thank you,\nMontoooorb69"

    assertExampleSuccess := func(path string) {
        command := exec.Command(path)
        session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
        Expect(err).ShouldNot(HaveOccurred())
        session.Wait(5 * time.Second)
        Expect(session.Out).Should(gbytes.Say(expectedTemplate))
        Expect(session).Should(gexec.Exit(0))
    }

    Describe("When Cli is executed", func() {
        // These tests leverage the example scripts for ease of testing.
        Context("With data file", func() {
            It("should successfully output example template from JSON data source", func() {
                assertExampleSuccess("./examples/run-example-json")
            })

            It("should successfully output example template from YAML data source", func() {
                assertExampleSuccess("./examples/run-example-yaml")
            })
        })

        Context("From Stdin", func() {
            It("should successfully output example template", func() {
                assertExampleSuccess("./examples/run-example-stdin")
            })
        })
    })

    Describe("decodeData", func() {
        Context("When called with valid JSON data", func() {
            It("should decode JSON to a map", func() {
                json := []byte("{ \"key\": \"val\"}")
                data, _ := decodeData(json)
                Expect(data).To(Equal(successDecodeOutput))
            })
        })

        Context("When called with valid Yaml data", func() {
            It("Should decode YAML to a map", func() {
                input := []byte("key: val")
                data, _ := decodeData(input)
                Expect(data).To(Equal(successDecodeOutput))
            })
        })

        Context("When called with data in invalid format", func() {
            It("should fail to load malformatted JSON", func() {
                json := []byte("{ \"key\": %val%\"}")
                _, err := decodeData(json)
                expectedErr := "error converting YAML to JSON: yaml: " +
                    "[while scanning for the next token] found character that cannot start any token at line 1, column 10"
                Expect(err.Error()).To(Equal(expectedErr))
            })

            It("should error with invalid format", func() {
                yaml := []byte("key\": \"%val%\"}")
                _, err := decodeData(yaml)
                expectedErr := "error converting YAML to JSON: yaml: " +
                    "[while parsing a block mapping] did not find expected key at line 1, column 14"
                Expect(err.Error()).To(Equal(expectedErr))
            })
        })
    })
})
<|endoftext|>


<commit_before>package police

import ()

type Neighbourhoods struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type Neighbourhood struct {
	ForceURL       string `json:"url_force"`
	BoundaryURL    string `json:"url_boundary"`
	ContactDetails `json:"contact_details"`
	Name           string `json:"name"`
	WelcomeMessage string `json:"welcome_message"`
	Links          []Link
	Center         `json:"center"`
	Locations      []Location `json:"locations"`
}

type Link struct {
	URL         string `json:"url"`
	Description string `json:"description"`
	Title       string `json:"title"`
}

type Center struct {
	Latitutde float64 `json:"latitude,string"`
	Longitude float64 `json:"longitude, string"`
}

type Locations struct {
	Name        string  `json:"name"`
	Longitude   float64 `json:"longitude,string"`
	Latitude    float64 `json:"latitude,string"`
	Postcode    string  `json:"postcode"`
	Address     string  `json:"address"`
	Telephone   string  `json:"telephone"`
	Type        string  `json:"type"`
	Description string  `json:"description"`
}

func (c Client) Neighbourhoods(location string) ([]Neighbourhoods, error) {
	var neighbourhoods []Neighbourhoods
	err := c.decodeJSONResponse(location+"/neighbourhoods", &neighbourhoods)
	if err != nil {
		return nil, err
	}
	return neighbourhoods, nil
}

func (c Client) Neighbourhood(location, id string) (Neighbourhood, error) {
	var neighbourhood Neighbourhood
	err := c.decodeJSONResponse(location+"/"+id, &neighbourhood)
	if err != nil {
		return Neighbourhood{}, err
	}
	return neighbourhood, nil
}

func (n Neighbourhoods) Information() (Neighbourhood, error) {
	return Neighbourhood{}, nil
}
<commit_msg>removed empty import block<commit_after>package police

type Neighbourhoods struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type Neighbourhood struct {
	ForceURL       string `json:"url_force"`
	BoundaryURL    string `json:"url_boundary"`
	ContactDetails `json:"contact_details"`
	Name           string `json:"name"`
	WelcomeMessage string `json:"welcome_message"`
	Links          []Link
	Center         `json:"center"`
	Locations      []Location `json:"locations"`
}

type Link struct {
	URL         string `json:"url"`
	Description string `json:"description"`
	Title       string `json:"title"`
}

type Center struct {
	Latitutde float64 `json:"latitude,string"`
	Longitude float64 `json:"longitude, string"`
}

type Locations struct {
	Name        string  `json:"name"`
	Longitude   float64 `json:"longitude,string"`
	Latitude    float64 `json:"latitude,string"`
	Postcode    string  `json:"postcode"`
	Address     string  `json:"address"`
	Telephone   string  `json:"telephone"`
	Type        string  `json:"type"`
	Description string  `json:"description"`
}

func (c Client) Neighbourhoods(location string) ([]Neighbourhoods, error) {
	var neighbourhoods []Neighbourhoods
	err := c.decodeJSONResponse(location+"/neighbourhoods", &neighbourhoods)
	if err != nil {
		return nil, err
	}
	return neighbourhoods, nil
}

func (c Client) Neighbourhood(location, id string) (Neighbourhood, error) {
	var neighbourhood Neighbourhood
	err := c.decodeJSONResponse(location+"/"+id, &neighbourhood)
	if err != nil {
		return Neighbourhood{}, err
	}
	return neighbourhood, nil
}

func (n Neighbourhoods) Information() (Neighbourhood, error) {
	return Neighbourhood{}, nil
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 Datacratic. All rights reserved.

package main

import (
	"github.com/datacratic/goklog/klog"
	"github.com/datacratic/goklog/klog/rest"
	"github.com/datacratic/gonfork/nfork"
	"github.com/datacratic/gorest/rest"

	"encoding/json"
	"flag"
	"io/ioutil"
	"log"
	_ "net/http/pprof"
)

var (
	config = flag.String(
		"config", "nfork.json",
		"file containing initial description of routes")

	listen = flag.String(
		"listen", "0.0.0.0:9090",
		"listen interface for the nfork controller interface")
)

func main() {
	flag.Parse()

	filter := klogr.NewRestFilter("", klog.FilterOut)
	filter.AddSuffix("debug")
	filter.AddSuffix("timeout")

	klog.SetPrinter(
		klog.Chain(filter,
			klog.Chain(klog.NewDedup(),
				klog.Fork(
					klogr.NewRestRing("", 1000),
					klog.GetPrinter()))))

	body, err := ioutil.ReadFile(*config)
	if err != nil {
		log.Fatalf("unable to read file '%s': %s", *config, err.Error())
	}

	controller := new(nfork.Controller)
	if err := json.Unmarshal(body, &controller.Inbounds); err != nil {
		log.Fatalf("unable to parse config '%s': %s", *config, err.Error())
	}

	klog.KPrintf("init.info", "starting nfork control on %s\n", *listen)
	controller.Start()

	rest.AddService(controller)
	rest.ListenAndServe(*listen, nil)
}
<commit_msg>klog simplifications.<commit_after>// Copyright (c) 2014 Datacratic. All rights reserved.

package main

import (
	"github.com/datacratic/goklog/klog"
	"github.com/datacratic/gonfork/nfork"
	"github.com/datacratic/gorest/rest"

	"encoding/json"
	"flag"
	"io/ioutil"
	"log"
	_ "net/http/pprof"
)

var (
	config = flag.String(
		"config", "nfork.json",
		"file containing initial description of routes")

	listen = flag.String(
		"listen", "0.0.0.0:9090",
		"listen interface for the nfork controller interface")
)

func main() {
	flag.Parse()

	klog.SetPrinter(
		klog.Chain(klog.NewFilterREST("", klog.FilterOut).AddSuffix("debug", "timeout"),
			klog.Chain(klog.NewDedup(),
				klog.Fork(
					klog.NewRingREST("", 1000),
					klog.GetPrinter()))))

	body, err := ioutil.ReadFile(*config)
	if err != nil {
		log.Fatalf("unable to read file '%s': %s", *config, err.Error())
	}

	controller := new(nfork.Controller)
	if err := json.Unmarshal(body, &controller.Inbounds); err != nil {
		log.Fatalf("unable to parse config '%s': %s", *config, err.Error())
	}

	klog.KPrintf("init.info", "starting nfork control on %s\n", *listen)
	controller.Start()

	rest.AddService(controller)
	rest.ListenAndServe(*listen, nil)
}
<|endoftext|>


<commit_before>package main

func main() {}

func one(data []int) int {
	var sum int
	for _, i := range data {
		sum += i
	}
	return sum
}

func two(data []int) int {
	var sum int
	if data == nil {
		return sum
	}
	for _, i := range data {
		sum += i
	}
	return sum
}
<commit_msg>nilrange: add three func<commit_after>package main

func main() {}

func one(data []int) int {
	var sum int
	for _, i := range data {
		sum += i
	}
	return sum
}

func two(data []int) int {
	var sum int
	if data == nil {
		return sum
	}
	for _, i := range data {
		sum += i
	}
	return sum
}

func three(data []int) int {
	if data == nil {
		return 0
	}
	var sum int
	for _, i := range data {
		sum += i
	}
	return sum
}
<|endoftext|>