2024-08-02 12:35:46 +02:00
|
|
|
package obiformats
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"git.metabarcoding.org/obitools/obitools4/obitools4/pkg/obiiter"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2024-11-29 18:15:03 +01:00
|
|
|
func WriteFileChunk(
|
2024-08-02 12:35:46 +02:00
|
|
|
writer io.WriteCloser,
|
2024-11-29 18:15:03 +01:00
|
|
|
toBeClosed bool) ChannelFileChunk {
|
2024-08-02 12:35:46 +02:00
|
|
|
|
|
|
|
obiiter.RegisterAPipe()
|
2024-11-29 18:15:03 +01:00
|
|
|
chunk_channel := make(ChannelFileChunk)
|
2024-08-02 12:35:46 +02:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
nextToPrint := 0
|
2024-11-29 18:15:03 +01:00
|
|
|
toBePrinted := make(map[int]FileChunk)
|
2024-08-02 12:35:46 +02:00
|
|
|
for chunk := range chunk_channel {
|
|
|
|
if chunk.Order == nextToPrint {
|
2024-08-13 09:45:28 +02:00
|
|
|
log.Debugf("Writing chunk: %d of length %d bytes",
|
|
|
|
chunk.Order,
|
|
|
|
len(chunk.Raw.Bytes()))
|
|
|
|
|
|
|
|
n, err := writer.Write(chunk.Raw.Bytes())
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Cannot write chunk %d only %d bytes written on %d sended : %v",
|
|
|
|
chunk.Order, n, len(chunk.Raw.Bytes()), err)
|
|
|
|
}
|
2024-08-02 12:35:46 +02:00
|
|
|
nextToPrint++
|
|
|
|
|
|
|
|
chunk, ok := toBePrinted[nextToPrint]
|
|
|
|
for ok {
|
2024-08-13 09:45:28 +02:00
|
|
|
log.Debug("Writing buffered chunk : ", chunk.Order)
|
2024-08-02 12:35:46 +02:00
|
|
|
_, _ = writer.Write(chunk.Raw.Bytes())
|
|
|
|
delete(toBePrinted, nextToPrint)
|
|
|
|
nextToPrint++
|
|
|
|
chunk, ok = toBePrinted[nextToPrint]
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
toBePrinted[chunk.Order] = chunk
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-13 09:45:28 +02:00
|
|
|
log.Debugf("FIle have to be closed : %v", toBeClosed)
|
2024-08-02 12:35:46 +02:00
|
|
|
if toBeClosed {
|
|
|
|
err := writer.Close()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Cannot close the writer : %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
obiiter.UnregisterPipe()
|
2024-08-05 10:48:28 +02:00
|
|
|
log.Debugf("The writer has been closed")
|
2024-08-02 12:35:46 +02:00
|
|
|
}()
|
|
|
|
|
|
|
|
return chunk_channel
|
|
|
|
}
|