Exemple #1
1
func (se *sliceEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
	if v.IsNil() {
		e.WriteString("null")
		return
	}
	se.arrayEnc(e, v, false)
}
Exemple #2
1
func (par field) WriteValue(out io.Writer, valueOf reflect.Value) error {
	if (par.Flags & (fieldNotAny | fieldFollowedBy)) != 0 {
		return nil
	}

	if par.Index < 0 { // We can not out this value in all cases but if it was literal we can do it
		// TODO: Check if it is string and output only in case it is literal
		p := par.Parse
		v := valueOf
		for {
			switch tp := p.(type) {
			case *ptrParser:
				p = tp.Parser
				if v.IsNil() {
					if tp.Optional {
						return nil
					}
					return errors.New("Ptr value is nil")
				}
				v = v.Elem()
				break

			case *literalParser:
				_, err := out.Write([]byte(tp.Literal))
				return err
			default:
				return errors.New("Could not out anonymous field if it is not literal")
			}
		}
	} else {
		f := valueOf.Field(par.Index)
		return par.Parse.WriteValue(out, f)
	}
}
Exemple #3
0
func getCurrentContainer(current reflect.Value) *Container {
	if !current.CanAddr() {
		return nil
	}
	currentContainer, _ := current.Addr().Interface().(*Container)
	return currentContainer
}
Exemple #4
0
func ContainerNameUnique(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
	if fieldKind != reflect.String {
		return true
	}

	containerName := field.String()
	if containerName == "" {
		return true
	}

	if hasReplTemplate(field) {
		// all bets are off
		return true
	}

	root, ok := topStruct.Interface().(*RootConfig)
	if !ok {
		// this is an issue with the code and really should be a panic
		return true
	}

	currentContainer := getCurrentContainer(currentStructOrField)
	if currentContainer == nil {
		// this is an issue with the code and really should be a panic
		return true
	}

	container := getContainerFromName(containerName, currentContainer, root)
	if container != nil {
		return false
	}
	return true
}
Exemple #5
0
// ComponentExistsValidation will validate that the specified component name is present in the current YAML.
func ComponentExistsValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
	// validates that the component exists in the root.Components slice
	root, ok := topStruct.Interface().(*RootConfig)
	if !ok {
		// this is an issue with the code and really should be a panic
		return true
	}

	if fieldKind != reflect.String {
		// this is an issue with the code and really should be a panic
		return true
	}

	var componentName string

	componentName = field.String()

	parts := strings.SplitN(componentName, ",", 2)

	if len(parts) >= 2 {
		componentName = parts[0]
	}

	return componentExists(componentName, root)
}
// EncodeValue transmits the data item represented by the reflection value,
// guaranteeing that all necessary type information has been transmitted first.
func (enc *Encoder) EncodeValue(value reflect.Value) os.Error {
	// Make sure we're single-threaded through here, so multiple
	// goroutines can share an encoder.
	enc.mutex.Lock()
	defer enc.mutex.Unlock()

	enc.err = nil
	rt, _ := indirect(value.Type())

	// Sanity check only: encoder should never come in with data present.
	if enc.state.b.Len() > 0 || enc.countState.b.Len() > 0 {
		enc.err = os.ErrorString("encoder: buffer not empty")
		return enc.err
	}

	enc.sendTypeDescriptor(rt)
	if enc.err != nil {
		return enc.err
	}

	// Encode the object.
	err := enc.encode(enc.state.b, value)
	if err != nil {
		enc.setError(err)
	} else {
		enc.send()
	}

	return enc.err
}
Exemple #7
0
func (par *boolParser) ParseValue(ctx *parseContext, valueOf reflect.Value, location int, err *Error) int {
	if strAt(ctx.str, location, "true") {
		valueOf.SetBool(true)
		location += 4
	} else if strAt(ctx.str, location, "false") {
		valueOf.SetBool(false)
		location += 5
	} else {
		err.Location = location
		err.Message = boolError
		return -1
	}

	if location < len(ctx.str) {
		if ctx.str[location] == '_' ||
			(ctx.str[location] >= 'a' && ctx.str[location] <= 'z') ||
			(ctx.str[location] >= 'A' && ctx.str[location] <= 'Z') ||
			(ctx.str[location] >= '0' && ctx.str[location] <= '9') {
			err.Location = location
			err.Message = boolError
			return -1
		}
	}

	return location
}
Exemple #8
0
// getField gets the i'th field of the struct value.
// If the field is itself is an interface, return a value for
// the thing inside the interface, not the interface itself.
func getField(v reflect.Value, i int) reflect.Value {
	val := v.Field(i)
	if val.Kind() == reflect.Interface && !val.IsNil() {
		val = val.Elem()
	}
	return val
}
Exemple #9
0
func (d *decoder) readArrayDocTo(out reflect.Value) {
	end := int(d.readInt32())
	end += d.i - 4
	if end <= d.i || end > len(d.in) || d.in[end-1] != '\x00' {
		corrupted()
	}
	i := 0
	l := out.Len()
	for d.in[d.i] != '\x00' {
		if i >= l {
			panic("Length mismatch on array field")
		}
		kind := d.readByte()
		for d.i < end && d.in[d.i] != '\x00' {
			d.i++
		}
		if d.i >= end {
			corrupted()
		}
		d.i++
		d.readElemTo(out.Index(i), kind)
		if d.i >= end {
			corrupted()
		}
		i++
	}
	if i != l {
		panic("Length mismatch on array field")
	}
	d.i++ // '\x00'
	if d.i != end {
		corrupted()
	}
}
Exemple #10
0
func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
	value = elemOf(value)

	// no need to handle zero values
	if !value.IsValid() {
		return nil
	}

	t := tag.Get("type")
	if t == "" {
		switch value.Kind() {
		case reflect.Struct:
			t = "structure"
		case reflect.Slice:
			t = "list"
		case reflect.Map:
			t = "map"
		}
	}

	switch t {
	case "structure":
		return q.parseStruct(v, value, prefix)
	case "list":
		return q.parseList(v, value, prefix, tag)
	case "map":
		return q.parseMap(v, value, prefix, tag)
	default:
		return q.parseScalar(v, value, prefix, tag)
	}
}
Exemple #11
0
// writeExtensions writes all the extensions in pv.
// pv is assumed to be a pointer to a protocol message struct that is extendable.
func writeExtensions(w *textWriter, pv reflect.Value) error {
	emap := extensionMaps[pv.Type().Elem()]
	ep := pv.Interface().(extendableProto)

	// Order the extensions by ID.
	// This isn't strictly necessary, but it will give us
	// canonical output, which will also make testing easier.
	var m map[int32]Extension
	if em, ok := ep.(extensionsMap); ok {
		m = em.ExtensionMap()
	} else if em, ok := ep.(extensionsBytes); ok {
		eb := em.GetExtensions()
		var err error
		m, err = BytesToExtensionsMap(*eb)
		if err != nil {
			return err
		}
	}

	ids := make([]int32, 0, len(m))
	for id := range m {
		ids = append(ids, id)
	}
	sort.Sort(int32Slice(ids))

	for _, extNum := range ids {
		ext := m[extNum]
		var desc *ExtensionDesc
		if emap != nil {
			desc = emap[extNum]
		}
		if desc == nil {
			// Unknown extension.
			if err := writeUnknownStruct(w, ext.enc); err != nil {
				return err
			}
			continue
		}

		pb, err := GetExtension(ep, desc)
		if err != nil {
			return fmt.Errorf("failed getting extension: %v", err)
		}

		// Repeated extensions will appear as a slice.
		if !desc.repeated() {
			if err := writeExtension(w, desc.Name, pb); err != nil {
				return err
			}
		} else {
			v := reflect.ValueOf(pb)
			for i := 0; i < v.Len(); i++ {
				if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
					return err
				}
			}
		}
	}
	return nil
}
Exemple #12
0
func unflattenValue(v reflect.Value, t reflect.Type) reflect.Value {
	// When t is an Interface, we can't do much, since we don't know the
	// original (unflattened) type of the value placed in v, so we just nop it.
	if t.Kind() == reflect.Interface {
		return v
	}
	// v can be invalid, if it holds the nil value for pointer type
	if !v.IsValid() {
		return v
	}
	// Make sure v is indeed flat
	if v.Kind() == reflect.Ptr {
		panic("unflattening non-flat value")
	}
	// Add a *, one at a time
	for t.Kind() == reflect.Ptr {
		if v.CanAddr() {
			v = v.Addr()
		} else {
			pw := reflect.New(v.Type())
			pw.Elem().Set(v)
			v = pw
		}
		t = t.Elem()
	}
	return v
}
Exemple #13
0
// bypassCanInterface returns a version of v that
// bypasses the CanInterface check.
func bypassCanInterface(v reflect.Value) reflect.Value {
	if !v.IsValid() || v.CanInterface() {
		return v
	}
	*flagField(&v) &^= flagRO
	return v
}
Exemple #14
0
func (ce *condAddrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
	if v.CanAddr() {
		ce.canAddrEnc(e, v, quoted)
	} else {
		ce.elseEnc(e, v, quoted)
	}
}
Exemple #15
0
func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
	if v.IsNil() {
		e.WriteString("null")
		return
	}
	pe.elemEnc(e, v.Elem(), quoted)
}
Exemple #16
0
// convert a value back to the original error interface. panics if value is not
// nil and also does not implement error.
func value2error(v reflect.Value) error {
	i := v.Interface()
	if i == nil {
		return nil
	}
	return i.(error)
}
Exemple #17
0
func GetMethod(s reflect.Value, name string) reflect.Value {
	method := s.MethodByName(name)
	if !method.IsValid() {
		method = s.Elem().MethodByName(name)
	}
	return method
}
Exemple #18
0
func (e *Encoder) encode(v reflect.Value, dst map[string][]string) error {
	var opts string
	var value string
	t := v.Type()

	for i := 0; i < v.NumField(); i++ {
		tag := t.Field(i).Tag.Get(e.TagID)
		name := tag
		if idx := strings.Index(tag, ","); idx != -1 {
			name = tag[:idx]
			opts = tag[idx+1:]
		}
		if name == "-" {
			continue
		}

		encFunc, recurse := encoder(v.Field(i).Type())
		if recurse {
			e.encode(v.Field(i), dst)
			continue
		}

		value = encFunc(v.Field(i))

		if value == "" && strings.Contains(opts, "omitempty") {
			continue
		}

		dst[name] = []string{value}
	}

	return nil
}
Exemple #19
0
// See if name is a method of the value at some level of indirection.
// The return values are the result of the call (which may be nil if
// there's trouble) and whether a method of the right name exists with
// any signature.
func callMethod(data reflect.Value, name string) (result reflect.Value, found bool) {
	found = false
	// Method set depends on pointerness, and the value may be arbitrarily
	// indirect.  Simplest approach is to walk down the pointer chain and
	// see if we can find the method at each step.
	// Most steps will see NumMethod() == 0.
	for {
		typ := data.Type()
		if nMethod := data.Type().NumMethod(); nMethod > 0 {
			for i := 0; i < nMethod; i++ {
				method := typ.Method(i)
				if method.Name == name {

					found = true // we found the name regardless
					// does receiver type match? (pointerness might be off)
					if typ == method.Type.In(0) {
						return call(data, method), found
					}
				}
			}
		}
		if nd := data; nd.Kind() == reflect.Ptr {
			data = nd.Elem()
		} else {
			break
		}
	}
	return
}
Exemple #20
0
// All protocol buffer fields are nillable, but be careful.
func isNil(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
		return v.IsNil()
	}
	return false
}
Exemple #21
0
func testSetNilMapsToEmpties(curr reflect.Value) {
	actualCurrValue := curr
	if curr.Kind() == reflect.Ptr {
		actualCurrValue = curr.Elem()
	}

	switch actualCurrValue.Kind() {
	case reflect.Map:
		for _, mapKey := range actualCurrValue.MapKeys() {
			currMapValue := actualCurrValue.MapIndex(mapKey)
			testSetNilMapsToEmpties(currMapValue)
		}

	case reflect.Struct:
		for fieldIndex := 0; fieldIndex < actualCurrValue.NumField(); fieldIndex++ {
			currFieldValue := actualCurrValue.Field(fieldIndex)

			if currFieldValue.Kind() == reflect.Map && currFieldValue.IsNil() {
				newValue := reflect.MakeMap(currFieldValue.Type())
				currFieldValue.Set(newValue)
			} else {
				testSetNilMapsToEmpties(currFieldValue.Addr())
			}
		}

	}

}
func (g *Group) scanSubGroupHandler(realval reflect.Value, sfield *reflect.StructField) (bool, error) {
	mtag := newMultiTag(string(sfield.Tag))

	if err := mtag.Parse(); err != nil {
		return true, err
	}

	subgroup := mtag.Get("group")

	if len(subgroup) != 0 {
		ptrval := reflect.NewAt(realval.Type(), unsafe.Pointer(realval.UnsafeAddr()))
		description := mtag.Get("description")

		group, err := g.AddGroup(subgroup, description, ptrval.Interface())
		if err != nil {
			return true, err
		}

		group.Namespace = mtag.Get("namespace")
		group.Hidden = mtag.Get("hidden") != ""

		return true, nil
	}

	return false, nil
}
Exemple #23
0
// ConfigItemWhenValidation will validate that the when element of a config item is in a valid format and references other valid, created objects.
func ConfigItemWhenValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
	root, ok := topStruct.Interface().(*RootConfig)
	if !ok {
		// this is an issue with the code and really should be a panic
		return true
	}

	if fieldKind != reflect.String {
		// this is an issue with the code and really should be a panic
		return true
	}

	var whenValue string

	whenValue = field.String()
	if whenValue == "" {
		return true
	}

	splitString := "="
	if strings.Contains(whenValue, "!=") {
		splitString = "!="
	}

	parts := strings.SplitN(whenValue, splitString, 2)
	if len(parts) >= 2 {
		whenValue = parts[0]
	}

	return configItemExists(whenValue, root)
}
Exemple #24
0
func decodeBSONData(d *decodeState, kind int, v reflect.Value) {
	start := d.offset
	d.skipValue(kind)
	bd := BSONData{Kind: kind, Data: make([]byte, d.offset-start)}
	copy(bd.Data, d.data[start:d.offset])
	v.Set(reflect.ValueOf(bd))
}
Exemple #25
0
// IsBytesValidation will return if a field is a parseable bytes value.
func IsBytesValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
	if fieldKind != reflect.String {
		// this is an issue with the code and really should be a panic
		return true
	}

	if field.String() == "" {
		return true
	}

	if hasReplTemplate(field) {
		// all bets are off
		return true
	}

	parts := bytesRe.FindStringSubmatch(strings.TrimSpace(field.String()))
	if len(parts) < 3 {
		return false
	}

	value, err := strconv.ParseUint(parts[1], 10, 0)
	if err != nil || value < 1 {
		return false
	}

	return true
}
Exemple #26
0
func unwrap(v *reflect.Value) *reflect.Value {
	if v.Kind() == reflect.Interface {
		org := v.Elem() //  Get rid of the wrapping interface
		return &org
	}
	return v
}
Exemple #27
0
func ClusterInstanceFalse(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
	if fieldKind != reflect.String {
		return true
	}

	valueStr := field.String()
	if valueStr == "" {
		return true
	}

	if hasReplTemplate(field) {
		// all bets are off
		return true
	}

	currentContainer := getCurrentContainer(currentStructOrField)
	if currentContainer == nil {
		// this is an issue with the code and really should be a panic
		return true
	}

	cluster, err := currentContainer.Cluster.ParseBool()
	if err != nil {
		// don't worry about this here. cluster should have the "bool" validator.
		return true
	}

	if cluster {
		return false
	}

	return true
}
Exemple #28
0
func (mssql) SqlTag(value reflect.Value, size int, autoIncrease bool) string {
	switch value.Kind() {
	case reflect.Bool:
		return "bit"
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uintptr:
		if autoIncrease {
			return "int IDENTITY(1,1)"
		}
		return "int"
	case reflect.Int64, reflect.Uint64:
		if autoIncrease {
			return "bigint IDENTITY(1,1)"
		}
		return "bigint"
	case reflect.Float32, reflect.Float64:
		return "float"
	case reflect.String:
		if size > 0 && size < 65532 {
			return fmt.Sprintf("nvarchar(%d)", size)
		}
		return "text"
	case reflect.Struct:
		if _, ok := value.Interface().(time.Time); ok {
			return "datetime2"
		}
	default:
		if _, ok := value.Interface().([]byte); ok {
			if size > 0 && size < 65532 {
				return fmt.Sprintf("varchar(%d)", size)
			}
			return "text"
		}
	}
	panic(fmt.Sprintf("invalid sql type %s (%s) for mssql", value.Type().Name(), value.Kind().String()))
}
Exemple #29
0
func (w *unknownCheckWalker) Primitive(v reflect.Value) error {
	if v.Interface() == unknownValue() {
		w.Unknown = true
	}

	return nil
}
Exemple #30
0
func interfaceEncoder(e *encodeState, v reflect.Value, quoted bool) {
	if v.IsNil() {
		e.WriteString("null")
		return
	}
	e.reflectValue(v.Elem())
}