equal
deleted
inserted
replaced
139 |
139 |
140 // Random number state. |
140 // Random number state. |
141 // We generate random temporary file names so that there's a good |
141 // We generate random temporary file names so that there's a good |
142 // chance the file doesn't exist yet - keeps the number of tries in |
142 // chance the file doesn't exist yet - keeps the number of tries in |
143 // TempFile to a minimum. |
143 // TempFile to a minimum. |
144 var rand uint32 |
144 var randNum uint32 |
145 var randmu sync.Mutex |
145 var randmu sync.Mutex |
146 |
146 |
147 func reseed() uint32 { |
147 func reseed() uint32 { |
148 return uint32(time.Now().UnixNano() + int64(os.Getpid())) |
148 return uint32(time.Now().UnixNano() + int64(os.Getpid())) |
149 } |
149 } |
150 |
150 |
151 func nextRandom() string { |
151 func nextRandom() string { |
152 randmu.Lock() |
152 randmu.Lock() |
153 r := rand |
153 r := randNum |
154 if r == 0 { |
154 if r == 0 { |
155 r = reseed() |
155 r = reseed() |
156 } |
156 } |
157 r = r*1664525 + 1013904223 // constants from Numerical Recipes |
157 r = r*1664525 + 1013904223 // constants from Numerical Recipes |
158 rand = r |
158 randNum = r |
159 randmu.Unlock() |
159 randmu.Unlock() |
160 return strconv.Itoa(int(1e9 + r%1e9))[1:] |
160 return strconv.Itoa(int(1e9 + r%1e9))[1:] |
161 } |
161 } |
162 |
162 |
163 // TempFile creates a new temporary file in the directory dir, |
163 // TempFile creates a new temporary file in the directory dir, |
192 name := filepath.Join(dir, prefix+nextRandom()+suffix) |
192 name := filepath.Join(dir, prefix+nextRandom()+suffix) |
193 f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) |
193 f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) |
194 if os.IsExist(err) { |
194 if os.IsExist(err) { |
195 if nconflict++; nconflict > 10 { |
195 if nconflict++; nconflict > 10 { |
196 randmu.Lock() |
196 randmu.Lock() |
197 rand = reseed() |
197 randNum = reseed() |
198 randmu.Unlock() |
198 randmu.Unlock() |
199 } |
199 } |
200 continue |
200 continue |
201 } |
201 } |
202 break |
202 break |
224 try := filepath.Join(dir, prefix+nextRandom()) |
224 try := filepath.Join(dir, prefix+nextRandom()) |
225 err = fs.Mkdir(try, 0700) |
225 err = fs.Mkdir(try, 0700) |
226 if os.IsExist(err) { |
226 if os.IsExist(err) { |
227 if nconflict++; nconflict > 10 { |
227 if nconflict++; nconflict > 10 { |
228 randmu.Lock() |
228 randmu.Lock() |
229 rand = reseed() |
229 randNum = reseed() |
230 randmu.Unlock() |
230 randmu.Unlock() |
231 } |
231 } |
232 continue |
232 continue |
233 } |
233 } |
234 if err == nil { |
234 if err == nil { |