MCPcopy
hub / github.com/dgraph-io/dgraph / Convert

Function Convert

types/conversion.go:96–479  ·  view source on GitHub ↗

Convert converts the value to given scalar type.

(from Val, toID TypeID)

Source from the content-addressed store, hash-verified

94
95// Convert converts the value to given scalar type.
96func Convert(from Val, toID TypeID) (Val, error) {
97 to := Val{Tid: toID}
98
99 // sanity: we expect a value
100 data, ok := from.Value.([]byte)
101 if !ok {
102 return to, errors.Errorf("invalid data to convert to %s", toID.Name())
103 }
104
105 fromID := from.Tid
106 res := &to.Value
107
108 // Convert from-type to to-type and store in the result interface.
109 switch fromID {
110 case BinaryID:
111 {
112 // Unmarshal from Binary to type interfaces.
113 switch toID {
114 case BinaryID:
115 *res = data
116 case StringID, DefaultID:
117 // We never modify from Val, so this should be safe.
118 *res = *(*string)(unsafe.Pointer(&data))
119 case IntID:
120 if len(data) < 8 {
121 return to, errors.Errorf("invalid data for int64 %v", data)
122 }
123 *res = int64(binary.LittleEndian.Uint64(data))
124 case FloatID:
125 if len(data) < 8 {
126 return to, errors.Errorf("invalid data for float %v", data)
127 }
128 i := binary.LittleEndian.Uint64(data)
129 *res = math.Float64frombits(i)
130 case BigFloatID:
131 var b big.Float
132 b.SetPrec(BigFloatPrecision)
133 if err := b.UnmarshalText(data); err != nil {
134 return to, err
135 }
136 *res = b
137 case BoolID:
138 if len(data) == 0 || data[0] == 0 {
139 *res = false
140 return to, nil
141 } else if data[0] == 1 {
142 *res = true
143 return to, nil
144 }
145 return to, errors.Errorf("invalid value for bool %v", data[0])
146 case DateTimeID:
147 var t time.Time
148 if err := t.UnmarshalBinary(data); err != nil {
149 return to, err
150 }
151 *res = t
152 case GeoID:
153 w, err := wkb.Unmarshal(data)

Callers 15

ValForFunction · 0.92
validateMutationFunction · 0.92
addIndexMapEntriesMethod · 0.92
toIntFunction · 0.92
uidToValFunction · 0.92
appendPostingFunction · 0.92
conflictKeysForNQuadMethod · 0.92
valToStrFunction · 0.92
multiSortFunction · 0.92
fetchValueFunction · 0.92
toCDCEventFunction · 0.92
convertValueFunction · 0.92

Calls 10

cantConvertFunction · 0.85
ParseTimeFunction · 0.85
EncryptFunction · 0.85
ParseVFloatFunction · 0.85
FloatArrayAsStringFunction · 0.85
BytesAsFloatArrayFunction · 0.70
NameMethod · 0.65
ErrorfMethod · 0.45
ErrorMethod · 0.45
StringMethod · 0.45

Tested by 15

TestKeyGeneratorPointFunction · 0.68
TestKeyGeneratorPolygonFunction · 0.68
TestSameConversionStringFunction · 0.68
TestConversionEdgeCasesFunction · 0.68
TestConvertToDefaultFunction · 0.68
TestConvertFromDefaultFunction · 0.68
TestConvertToBinaryFunction · 0.68
TestConvertFromBinaryFunction · 0.68