-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeedtest_utils.go
More file actions
266 lines (222 loc) · 6.41 KB
/
speedtest_utils.go
File metadata and controls
266 lines (222 loc) · 6.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
)
// formatDuration formats a duration for short output with consistent spacing
func formatDuration(d time.Duration) string {
if d < time.Second {
return "0s"
} else {
return fmt.Sprintf("%.0fs", d.Seconds())
}
}
// formatDurationDetailed formats duration in days/hours:minutes:seconds format
func formatDurationDetailed(d time.Duration) string {
if d < time.Second {
return "0s"
}
totalSeconds := int64(d.Seconds())
days := totalSeconds / 86400
hours := (totalSeconds % 86400) / 3600
minutes := (totalSeconds % 3600) / 60
seconds := totalSeconds % 60
if days > 0 {
return fmt.Sprintf("%dd/%02d:%02d:%02d", days, hours, minutes, seconds)
} else if hours > 0 {
return fmt.Sprintf("%d:%02d:%02d", hours, minutes, seconds)
} else if minutes > 0 {
return fmt.Sprintf("%d:%02d", minutes, seconds)
} else {
return fmt.Sprintf("%ds", seconds)
}
}
// formatETA formats duration for ETA display in human-readable format
func formatETA(d time.Duration) string {
if d <= 0 {
return "0s"
}
secs := d.Seconds()
if secs < 60 {
return fmt.Sprintf("%.0fs", secs)
} else if secs < 3600 {
m := int64(secs) / 60
s := secs - float64(m*60)
return fmt.Sprintf("%dm %.0fs", m, s)
} else {
h := int64(secs) / 3600
rem := secs - float64(h*3600)
m := int64(rem) / 60
s := rem - float64(m*60)
return fmt.Sprintf("%dh %dm %.0fs", h, m, s)
}
}
// parseSize parses a size string and returns the size in MB
func parseSize(sizeStr string) (int, error) {
var size int
var err error
sizeStr = strings.TrimSpace(strings.ToLower(sizeStr))
// Handle suffixes
if strings.HasSuffix(sizeStr, "mb") || strings.HasSuffix(sizeStr, "m") {
sizeStr = strings.TrimSuffix(sizeStr, "mb")
sizeStr = strings.TrimSuffix(sizeStr, "m")
}
size, err = strconv.Atoi(sizeStr)
if err != nil {
return 0, err
}
return size, nil
}
// createRandomFile creates a test file with the specified size in MB
func createRandomFile(fileName string, sizeMB int, showProgress bool) error {
file, err := os.Create(fileName)
if err != nil {
return err
}
defer file.Close()
sizeBytes := int64(sizeMB) * 1024 * 1024
// Create a 1MB pattern block once
const blockSizeMB = 1
const blockSizeBytes = blockSizeMB * 1024 * 1024
// Generate the base pattern for 1MB block (without the number prefix)
basePattern := generateBasePattern(blockSizeBytes - 50) // Reserve 50 bytes for block number prefix
written := int64(0)
blockNumber := 1
for written < sizeBytes {
remaining := sizeBytes - written
blockSize := int64(blockSizeBytes)
if remaining < blockSize {
blockSize = remaining
}
// Create block with number prefix
blockData := createNumberedBlock(blockNumber, basePattern, int(blockSize))
n, err := file.Write(blockData)
if err != nil {
return err
}
written += int64(n)
blockNumber++
// Show progress for large files - less frequent updates
if showProgress && sizeMB >= 10 && written%(1024*1024*50) == 0 { // Every 50MB instead of 10MB
progress := float64(written) / float64(sizeBytes) * 100
fmt.Printf(" Creating file: %.1f%%\r", progress)
}
}
if showProgress && sizeMB >= 10 {
fmt.Printf(" Creating file: 100.0%%\n")
}
return nil
}
// generateBasePattern creates a readable text pattern of the specified size
func generateBasePattern(size int) []byte {
// Create readable text pattern that will be reused
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,!?\n"
const lineLength = 80 // Create lines of 80 characters
pattern := make([]byte, size)
charIndex := 0
for i := 0; i < size; i++ {
if i > 0 && i%lineLength == 0 {
pattern[i] = '\n'
} else {
pattern[i] = charset[charIndex%len(charset)]
charIndex++
}
}
return pattern
}
// createNumberedBlock creates a block with a number header and footer
func createNumberedBlock(blockNum int, basePattern []byte, targetSize int) []byte {
// Create block header with block number
header := fmt.Sprintf("=== BLOCK %06d === START ===\n", blockNum)
footer := fmt.Sprintf("\n=== BLOCK %06d === END ===\n", blockNum)
headerBytes := []byte(header)
footerBytes := []byte(footer)
// Calculate how much space we need for the pattern
patternSize := targetSize - len(headerBytes) - len(footerBytes)
if patternSize <= 0 {
// If block is too small, just return the header truncated to fit
if targetSize <= len(headerBytes) {
return headerBytes[:targetSize]
}
return append(headerBytes, footerBytes[:targetSize-len(headerBytes)]...)
}
// Create the block
block := make([]byte, 0, targetSize)
block = append(block, headerBytes...)
// Fill with pattern, repeating as necessary
patternPos := 0
for len(block) < targetSize-len(footerBytes) {
if patternPos >= len(basePattern) {
patternPos = 0
}
block = append(block, basePattern[patternPos])
patternPos++
}
// Add footer
block = append(block, footerBytes...)
// Ensure exact size
if len(block) > targetSize {
block = block[:targetSize]
}
return block
}
// copyFileWithProgress copies a file from src to dst with progress reporting
func copyFileWithProgress(src, dst string, showProgress bool) (int64, error) {
sourceFile, err := os.Open(src)
if err != nil {
return 0, err
}
defer sourceFile.Close()
sourceInfo, err := sourceFile.Stat()
if err != nil {
return 0, err
}
destFile, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destFile.Close()
totalSize := sourceInfo.Size()
buffer := make([]byte, 64*1024) // 64KB buffer
var totalCopied int64
var lastProgressUpdate int64
if showProgress {
fmt.Printf(" Progress: 0.0%%")
}
for {
n, err := sourceFile.Read(buffer)
if n > 0 {
written, writeErr := destFile.Write(buffer[:n])
if writeErr != nil {
return totalCopied, writeErr
}
totalCopied += int64(written)
// Show progress less frequently - only every 5% or 10MB
if showProgress {
progressThreshold := int64(1024 * 1024 * 10) // 10MB
if totalSize < progressThreshold {
progressThreshold = totalSize / 20 // 5% for smaller files
}
if totalCopied-lastProgressUpdate >= progressThreshold {
progress := float64(totalCopied) / float64(totalSize) * 100
fmt.Printf("\r Progress: %.1f%%", progress)
lastProgressUpdate = totalCopied
}
}
}
if err == io.EOF {
break
}
if err != nil {
return totalCopied, err
}
}
if showProgress {
fmt.Printf("\r Progress: 100.0%%")
}
return totalCopied, nil
}