// Check if we need to accumulate more events before emitting.
//
// We accumulate extra
//  - 1 event for DOCUMENT-START
//  - 2 events for SEQUENCE-START
//  - 3 events for MAPPING-START
//
167023
func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool {
	if emitter.events_head == len(emitter.events) {
		return true
	}
	var accumulate int
	switch emitter.events[emitter.events_head].typ {
	case yaml_DOCUMENT_START_EVENT:
		accumulate = 1
		break
	case yaml_SEQUENCE_START_EVENT:
		accumulate = 2
		break
	case yaml_MAPPING_START_EVENT:
		accumulate = 3
		break
	default:
		return false
	}
	if len(emitter.events)-emitter.events_head > accumulate {
		return false
	}
	var level int
	for i := emitter.events_head; i < len(emitter.events); i++ {
		switch emitter.events[i].typ {
		case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT:
			level++
		case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT:
			level--
		}
		if level == 0 {
			return false
		}
	}
	return true
}
727467
func (c *context) emit(e *event) {
	if e.Timestamp == 0 {
		e.Timestamp = fromDuration(time.Since(consts.start))
	}
	// sync.WaitGroup.Add() use atomic.AddUint64().
	globals.wg.Add(1)
	go func() {
		defer globals.wg.Done()
		e.Pid = c.pid
		e.Tid = 1
		// Locking is done in a goroutine to not create implicit synchronization
		// when tracing.
		globals.lockWriter.Lock()
		defer globals.lockWriter.Unlock()
		if globals.out != nil {
			if globals.first {
				globals.first = false
			} else {
				// Writing is done in a goroutine to reduce cost.
				if _, err := globals.out.Write([]byte(",")); err != nil {
					log.Printf("failed writing to trace: %s", err)
					go Stop()
					return
				}
			}
			if err := globals.encoder.Encode(e); err != nil {
				log.Printf("failed writing to trace: %s", err)
				go Stop()
			}
		}
	}()
}
174877
func (r *record) Emit(ev Event, b []byte) {
	// This looks absolutely _horrible_. It'd be better in C. Anyway, the idea
	// is that we have a list of unsafe pointers, which is stored in the list
	// which is an atomic pointer itself. We can swap the pointer held at each
	// address in the list, so _that_ address needs to be loaded atomically.
	// This means we need to actually load the data from the address at
	// offset X from the start of the array underlying the slice.
	//
	// The cost of the atomic loading makes 5-10% slower, but allows us to
	// atomically insert and remove listeners in many cases.

	list := r.getUnsafeList()
	for i := 0; i < len(list); i++ {
		addr := uintptr(unsafe.Pointer(&list[i]))
		value := atomic.LoadPointer(*(**unsafe.Pointer)(unsafe.Pointer(&addr)))
		if value != nil {
			(*(*Listener)(value)).Handle(ev, b)
		}
	}
}
349267
func (e *eventEmitter) On(ev EventType, h EventHandler) {
	e.addHandlerToMap(ev, h, e.listeners)
}
638990
func calculateEvenSplits(size int64, src SourceInfo) (startIndex, endIndex []int64) {
	if size == 0 {
		return
	}

	reqParts := partsRequired(size)
	startIndex = make([]int64, reqParts)
	endIndex = make([]int64, reqParts)
	// Compute number of required parts `k`, as:
	//
	// k = ceiling(size / copyPartSize)
	//
	// Now, distribute the `size` bytes in the source into
	// k parts as evenly as possible:
	//
	// r parts sized (q+1) bytes, and
	// (k - r) parts sized q bytes, where
	//
	// size = q * k + r (by simple division of size by k,
	// so that 0 <= r < k)
	//
	start := src.start
	if start == -1 {
		start = 0
	}
	quot, rem := size/reqParts, size%reqParts
	nextStart := start
	for j := int64(0); j < reqParts; j++ {
		curPartSize := quot
		if j < rem {
			curPartSize++
		}

		cStart := nextStart
		cEnd := cStart + curPartSize - 1
		nextStart = cEnd + 1

		startIndex[j], endIndex[j] = cStart, cEnd
	}
	return
}
23704
func (m *Broadcaster) loop() {
	// Deliberately not catching crashes here. Yes, bring down the process if there's a
	// bug in watch.Broadcaster.
	for {
		event, ok := <-m.incoming
		if !ok {
			break
		}
		if event.Type == internalRunFunctionMarker {
			event.Object.(functionFakeRuntimeObject)()
			continue
		}
		m.distribute(event)
	}
	m.closeAll()
	m.distributing.Done()
}
301884
func appendTaskEvent(state *structs.TaskState, event *structs.TaskEvent, capacity int) {
	if state.Events == nil {
		state.Events = make([]*structs.TaskEvent, 1, capacity)
		state.Events[0] = event
		return
	}

	// If we hit capacity, then shift it.
	if len(state.Events) == capacity {
		old := state.Events
		state.Events = make([]*structs.TaskEvent, 0, capacity)
		state.Events = append(state.Events, old[1:]...)
	}

	state.Events = append(state.Events, event)
}
633172
func RunPreparation() {
	Time = NewClock()

	if !opts.HeadlessMode {
		window.Call("addEventListener", "onbeforeunload", js.NewEventCallback(js.PreventDefault, func(event js.Value) {
			window.Call("alert", "You're closing")
		}))
	}
}
1155899
func (w *Worker) On(e Event, cb func(*Package, ...interface{})) {
	if _, exists := w.events[e]; !exists {
		w.events[e] = make([]func(*Package, ...interface{}), 0)
	}

	w.events[e] = append(w.events[e], cb)
}
74153
func EmitEvent(c context.Context, e *api.Event) error {
	ev := Events{}
	ev.Emit(e)
	return ev.Flush(c)
}
1323681
func EmitMetadataEvents(c context.Context, before, after *api.PrefixMetadata) error {
	if before.Prefix != after.Prefix {
		panic(fmt.Sprintf("comparing metadata for different prefixes: %q != %q", before.Prefix, after.Prefix))
	}
	prefix := after.Prefix

	prev := metadata.GetACLs(before)
	next := metadata.GetACLs(after)

	var granted []*api.PrefixMetadata_ACL
	var revoked []*api.PrefixMetadata_ACL

	for _, role := range sortedRoles {
		if added := stringSetDiff(next[role], prev[role]); len(added) != 0 {
			granted = append(granted, &api.PrefixMetadata_ACL{
				Role:       role,
				Principals: added,
			})
		}
		if removed := stringSetDiff(prev[role], next[role]); len(removed) != 0 {
			revoked = append(revoked, &api.PrefixMetadata_ACL{
				Role:       role,
				Principals: removed,
			})
		}
	}

	if len(granted) == 0 && len(revoked) == 0 {
		return nil
	}

	return EmitEvent(c, &api.Event{
		Kind:        api.EventKind_PREFIX_ACL_CHANGED,
		Package:     prefix,
		GrantedRole: granted,
		RevokedRole: revoked,
	})
}
60694
func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool {
	if !yaml_emitter_process_anchor(emitter) {
		return false
	}
	if !yaml_emitter_process_tag(emitter) {
		return false
	}
	if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE ||
		yaml_emitter_check_empty_sequence(emitter) {
		emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE
	} else {
		emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE
	}
	return true
}
323780
func isRollbackEvent(e *api.Event) (bool, string) {
	rollbackEventReasons := []string{deploymentutil.RollbackRevisionNotFound, deploymentutil.RollbackTemplateUnchanged, deploymentutil.RollbackDone}
	for _, reason := range rollbackEventReasons {
		if e.Reason == reason {
			if reason == deploymentutil.RollbackDone {
				return true, "rolled back"
			}
			return true, fmt.Sprintf("skipped rollback (%s: %s)", e.Reason, e.Message)
		}
	}
	return false, ""
}
1360916
func (b *bufferedBackend) processIncomingEvents(stopCh <-chan struct{}) {
	defer close(b.buffer)

	var (
		maxWaitChan  <-chan time.Time
		maxWaitTimer *time.Timer
	)
	// Only use max wait batching if batching is enabled.
	if b.maxBatchSize > 1 {
		maxWaitTimer = time.NewTimer(b.maxBatchWait)
		maxWaitChan = maxWaitTimer.C
		defer maxWaitTimer.Stop()
	}

	for {
		func() {
			// Recover from any panics caused by this function so a panic in the
			// goroutine can't bring down the main routine.
			defer runtime.HandleCrash()

			if b.maxBatchSize > 1 {
				maxWaitTimer.Reset(b.maxBatchWait)
			}
			b.processEvents(b.collectEvents(maxWaitChan, stopCh))
		}()

		select {
		case <-stopCh:
			return
		default:
		}
	}
}
596983
func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool {
	if len(emitter.events)-emitter.events_head < 2 {
		return false
	}
	return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT &&
		emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT
}
1290483
func (ctl *taskController) EmitTrigger(ctx context.Context, trigger *internal.Trigger) {
	ctl.DebugLog("Emitting a trigger %s", trigger.Id)
	trigger.JobId = ctl.JobID()
	trigger.InvocationId = ctl.InvocationID()

	// See docs for internal.Trigger proto. Tuple (created, order_in_batch) used
	// for casual ordering of triggers emitted by an invocation. Callers of
	// EmitTrigger are free to override this by supplying their own timestamp. In
	// such case they also should provide order_in_batch. Otherwise we build the
	// tuple for them based on the order of EmitTrigger calls.
	if trigger.Created == nil {
		trigger.Created = google.NewTimestamp(clock.Now(ctx))
		trigger.OrderInBatch = ctl.triggerIndex
	}

	ctl.triggers = append(ctl.triggers, trigger)
	ctl.triggerIndex++ // note: this is NOT reset in Save, unlike ctl.triggers.
}
1274800
func (h *HistoCounter) AddEvents(ctx context.Context, events []*event.Event, next Sink) error {
	h.EventBucket.Add(float64(len(events)))
	return h.sink.AddEvents(ctx, events, next)
}