# File lib/uuid.rb, line 175
175:   def generate(format = :default)
176:     template = FORMATS[format]
177: 
178:     raise ArgumentError, "invalid UUID format #{format.inspect}" unless template
179: 
180:     # The clock must be monotonically increasing. The clock resolution is at
181:     # best 100 ns (UUID spec), but practically may be lower (on my setup,
182:     # around 1ms). If this method is called too fast, we don't have a
183:     # monotonically increasing clock, so the solution is to just wait.
184:     #
185:     # It is possible for the clock to be adjusted backwards, in which case we
186:     # would end up blocking for a long time. When backward clock is detected,
187:     # we prevent duplicates by asking for a new sequence number and continue
188:     # with the new clock.
189: 
190:     clock = @mutex.synchronize do
191:       clock = (Time.new.to_f * CLOCK_MULTIPLIER).to_i & 0xFFFFFFFFFFFFFFF0
192: 
193:       if clock > @last_clock then
194:         @drift = 0
195:         @last_clock = clock
196:       elsif clock == @last_clock then
197:         drift = @drift += 1
198: 
199:         if drift < 10000 then
200:           @last_clock += 1
201:         else
202:           Thread.pass
203:           nil
204:         end
205:       else
206:         next_sequence
207:         @last_clock = clock
208:       end
209:     end until clock
210: 
211:     template % [
212:         clock        & 0xFFFFFFFF,
213:        (clock >> 32) & 0xFFFF,
214:       ((clock >> 48) & 0xFFFF | VERSION_CLOCK),
215:       @sequence      & 0xFFFF,
216:       @mac           & 0xFFFFFFFFFFFF
217:     ]
218:   end