Hello,
I am looking for help reviewing the function below. I need to generate 
millions of large files in a specific binary format. I do not care about 
portability (only used on Little Endian machines). The file format writes 
the data in row order, so need to loop over slices of different types and 
write them out. I came up with the solution below (it works), but the code 
is obviously ugly and possibly fragile. Can you think of another way of 
doing this that is at least as efficient, but safer or less verbose?  
 
Thanks,


func (sf *File) writeData(w io.Writer) error {
if sf.NoObs == 0 {
return nil
}
if len(sf.fields) == 0 {
return fmt.Errorf("No fields")
}
bs := make([]byte, sf.recordSize)
//var ptr uintptr
for i := int32(0); i < sf.NoObs; i++ {
offset := 0
for _, f := range sf.fields {
switch f.FieldType {
case StataByte:
v := f.data.([]int8)[i]
bs[offset] = byte(v)
offset++
case StataInt:
v := f.data.([]int16)[i]
bs[offset] = byte(v)
offset++
bs[offset] = byte(v >> 8)
offset++
case StataLong:
v := f.data.([]int32)[i]
bs[offset] = byte(v)
offset++
bs[offset] = byte(v >> 8)
offset++
bs[offset] = byte(v >> 16)
offset++
bs[offset] = byte(v >> 24)
offset++
case StataFloat:
fptr := uintptr(unsafe.Pointer(&f.data.([]float32)[i]))
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 1)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 2)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 3)))
offset++
case StataDouble:
fptr := uintptr(unsafe.Pointer(&f.data.([]float64)[i]))
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 1)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 2)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 3)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 4)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 5)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 6)))
offset++
bs[offset] = byte(*(*byte)(unsafe.Pointer(fptr + 7)))
offset++
default:
return fmt.Errorf("Field type [%d] not supported in field %s", f.FieldType, 
f.Name)
}
}
if _, err := w.Write(bs); err != nil {
return err
}
}
return nil
}



-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to