# File lib/uuid.rb, line 277
277:   def generate(format = :default)
278:     template = FORMATS[format]
279: 
280:     raise ArgumentError, "invalid UUID format #{format.inspect}" unless template
281: 
282:     # The clock must be monotonically increasing. The clock resolution is at
283:     # best 100 ns (UUID spec), but practically may be lower (on my setup,
284:     # around 1ms). If this method is called too fast, we don't have a
285:     # monotonically increasing clock, so the solution is to just wait.
286:     #
287:     # It is possible for the clock to be adjusted backwards, in which case we
288:     # would end up blocking for a long time. When backward clock is detected,
289:     # we prevent duplicates by asking for a new sequence number and continue
290:     # with the new clock.
291: 
292:     clock = @mutex.synchronize do
293:       clock = (Time.new.to_f * CLOCK_MULTIPLIER).to_i & 0xFFFFFFFFFFFFFFF0
294: 
295:       if clock > @last_clock then
296:         @drift = 0
297:         @last_clock = clock
298:       elsif clock == @last_clock then
299:         drift = @drift += 1
300: 
301:         if drift < 10000 then
302:           @last_clock += 1
303:         else
304:           Thread.pass
305:           nil
306:         end
307:       else
308:         next_sequence
309:         @last_clock = clock
310:       end
311:     end until clock
312: 
313:     template % [
314:         clock        & 0xFFFFFFFF,
315:        (clock >> 32) & 0xFFFF,
316:       ((clock >> 48) & 0xFFFF | VERSION_CLOCK),
317:       @sequence      & 0xFFFF,
318:       @mac           & 0xFFFFFFFFFFFF
319:     ]
320:   end