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