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