MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / encodeTensor

Function encodeTensor

tensorflow/go/tensor.go:302–347  ·  view source on GitHub ↗

encodeTensor writes v to the specified buffer using the format specified in c_api.h. Use stringEncoder for String tensors.

(w *bytes.Buffer, v reflect.Value, shape []int64)

Source from the content-addressed store, hash-verified

300// encodeTensor writes v to the specified buffer using the format specified in
301// c_api.h. Use stringEncoder for String tensors.
302func encodeTensor(w *bytes.Buffer, v reflect.Value, shape []int64) error {
303 switch v.Kind() {
304 case reflect.Bool:
305 b := byte(0)
306 if v.Bool() {
307 b = 1
308 }
309 if err := w.WriteByte(b); err != nil {
310 return err
311 }
312 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
313 if err := binary.Write(w, nativeEndian, v.Interface()); err != nil {
314 return err
315 }
316
317 case reflect.Array, reflect.Slice:
318 // If current dimension is a slice, verify that it has the expected size
319 // Go's type system makes that guarantee for arrays.
320 if v.Kind() == reflect.Slice {
321 expected := int(shape[0])
322 if v.Len() != expected {
323 return fmt.Errorf("mismatched slice lengths: %d and %d", v.Len(), expected)
324 }
325 }
326
327 // Optimisation: if only one dimension is left we can use binary.Write() directly for this slice
328 if len(shape) == 1 && v.Len() > 0 {
329 switch v.Index(0).Kind() {
330 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
331 return binary.Write(w, nativeEndian, v.Interface())
332 }
333 }
334
335 subShape := shape[1:]
336 for i := 0; i < v.Len(); i++ {
337 err := encodeTensor(w, v.Index(i), subShape)
338 if err != nil {
339 return err
340 }
341 }
342
343 default:
344 return fmt.Errorf("unsupported type %v", v.Type())
345 }
346 return nil
347}
348
349// decodeTensor decodes the Tensor from the buffer to ptr using the format
350// specified in c_api.h. Use stringDecoder for String tensors.

Callers 1

NewTensorFunction · 0.85

Calls 6

WriteByteMethod · 0.80
InterfaceMethod · 0.80
KindMethod · 0.45
WriteMethod · 0.45
IndexMethod · 0.45
TypeMethod · 0.45

Tested by

no test coverage detected