| 26 | } |
| 27 | |
| 28 | func NewDataBuilder(req *DataUpload) (*DataBuilder, error) { |
| 29 | if len(req.DataHash) != 32 { |
| 30 | return nil, xerrors.Errorf("data hash must be 32 bytes, got %d bytes", len(req.DataHash)) |
| 31 | } |
| 32 | |
| 33 | if req.FileSize < 0 { |
| 34 | return nil, xerrors.Errorf("file size must not be negative, got %d", req.FileSize) |
| 35 | } |
| 36 | if req.FileSize > MaxFileSize { |
| 37 | return nil, xerrors.Errorf("file size %d exceeds maximum allowed %d", req.FileSize, MaxFileSize) |
| 38 | } |
| 39 | if req.Chunks < 0 { |
| 40 | return nil, xerrors.Errorf("chunk count must not be negative, got %d", req.Chunks) |
| 41 | } |
| 42 | //nolint:gosec // FileSize is validated to be <= MaxFileSize, well within int32 range |
| 43 | maxChunks := int32((req.FileSize + ChunkSize - 1) / ChunkSize) |
| 44 | if req.Chunks > maxChunks { |
| 45 | return nil, xerrors.Errorf("chunk count %d exceeds maximum %d for file size %d", req.Chunks, maxChunks, req.FileSize) |
| 46 | } |
| 47 | |
| 48 | return &DataBuilder{ |
| 49 | Type: req.UploadType, |
| 50 | Hash: req.DataHash, |
| 51 | Size: req.FileSize, |
| 52 | ChunkCount: req.Chunks, |
| 53 | |
| 54 | // Initial conditions |
| 55 | chunkIndex: 0, |
| 56 | data: make([]byte, 0, req.FileSize), |
| 57 | }, nil |
| 58 | } |
| 59 | |
| 60 | func (b *DataBuilder) Add(chunk *ChunkPiece) (bool, error) { |
| 61 | b.mu.Lock() |