# File lib/uuid.rb, line 223
223:   def generate(format = :default)
224:     template = FORMATS[format]
225: 
226:     raise ArgumentError, "invalid UUID format #{format.inspect}" unless template
227: 
228:     # The clock must be monotonically increasing. The clock resolution is at
229:     # best 100 ns (UUID spec), but practically may be lower (on my setup,
230:     # around 1ms). If this method is called too fast, we don't have a
231:     # monotonically increasing clock, so the solution is to just wait.
232:     #
233:     # It is possible for the clock to be adjusted backwards, in which case we
234:     # would end up blocking for a long time. When backward clock is detected,
235:     # we prevent duplicates by asking for a new sequence number and continue
236:     # with the new clock.
237: 
238:     clock = @mutex.synchronize do
239:       clock = (Time.new.to_f * CLOCK_MULTIPLIER).to_i & 0xFFFFFFFFFFFFFFF0
240: 
241:       if clock > @last_clock then
242:         @drift = 0
243:         @last_clock = clock
244:       elsif clock == @last_clock then
245:         drift = @drift += 1
246: 
247:         if drift < 10000 then
248:           @last_clock += 1
249:         else
250:           Thread.pass
251:           nil
252:         end
253:       else
254:         next_sequence
255:         @last_clock = clock
256:       end
257:     end until clock
258: 
259:     template % [
260:         clock        & 0xFFFFFFFF,
261:        (clock >> 32) & 0xFFFF,
262:       ((clock >> 48) & 0xFFFF | VERSION_CLOCK),
263:       @sequence      & 0xFFFF,
264:       @mac           & 0xFFFFFFFFFFFF
265:     ]
266:   end