// newSingleConnectionHeap creates a new heap with initial size.
165885
func newSingleConnectionHeap(size int) *singleConnectionHeap {
	if size <= 0 {
		panic("Heap size cannot be less than 1")
	}

	return &singleConnectionHeap{
		full: false,
		data: make([]*Connection, uint32(size)),
		size: uint32(size),
	}
}
962813
func parseHeap(b []byte) (p *Profile, err error) {
	r := bytes.NewBuffer(b)
	l, err := r.ReadString('\n')
	if err != nil {
		return nil, errUnrecognized
	}

	sampling := ""

	if header := heapHeaderRE.FindStringSubmatch(l); header != nil {
		p = &Profile{
			SampleType: []*ValueType{
				{Type: "objects", Unit: "count"},
				{Type: "space", Unit: "bytes"},
			},
			PeriodType: &ValueType{Type: "objects", Unit: "bytes"},
		}

		var period int64
		if len(header[6]) > 0 {
			if period, err = strconv.ParseInt(string(header[6]), 10, 64); err != nil {
				return nil, errUnrecognized
			}
		}

		switch header[5] {
		case "heapz_v2", "heap_v2":
			sampling, p.Period = "v2", period
		case "heapprofile":
			sampling, p.Period = "", 1
		case "heap":
			sampling, p.Period = "v2", period/2
		default:
			return nil, errUnrecognized
		}
	} else if header = growthHeaderRE.FindStringSubmatch(l); header != nil {
		p = &Profile{
			SampleType: []*ValueType{
				{Type: "objects", Unit: "count"},
				{Type: "space", Unit: "bytes"},
			},
			PeriodType: &ValueType{Type: "heapgrowth", Unit: "count"},
			Period:     1,
		}
	} else if header = fragmentationHeaderRE.FindStringSubmatch(l); header != nil {
		p = &Profile{
			SampleType: []*ValueType{
				{Type: "objects", Unit: "count"},
				{Type: "space", Unit: "bytes"},
			},
			PeriodType: &ValueType{Type: "allocations", Unit: "count"},
			Period:     1,
		}
	} else {
		return nil, errUnrecognized
	}

	if LegacyHeapAllocated {
		for _, st := range p.SampleType {
			st.Type = "alloc_" + st.Type
		}
	} else {
		for _, st := range p.SampleType {
			st.Type = "inuse_" + st.Type
		}
	}

	locs := make(map[uint64]*Location)
	for {
		l, err = r.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				return nil, err
			}

			if l == "" {
				break
			}
		}

		if isSpaceOrComment(l) {
			continue
		}
		l = strings.TrimSpace(l)

		if sectionTrigger(l) != unrecognizedSection {
			break
		}

		value, blocksize, addrs, err := parseHeapSample(l, p.Period, sampling)
		if err != nil {
			return nil, err
		}
		var sloc []*Location
		for i, addr := range addrs {
			// Addresses from stack traces point to the next instruction after
			// each call.  Adjust by -1 to land somewhere on the actual call
			// (except for the leaf, which is not a call).
			if i > 0 {
				addr--
			}
			loc := locs[addr]
			if locs[addr] == nil {
				loc = &Location{
					Address: addr,
				}
				p.Location = append(p.Location, loc)
				locs[addr] = loc
			}
			sloc = append(sloc, loc)
		}

		p.Sample = append(p.Sample, &Sample{
			Value:    value,
			Location: sloc,
			NumLabel: map[string][]int64{"bytes": {blocksize}},
		})
	}

	if err = parseAdditionalSections(l, r, p); err != nil {
		return nil, err
	}
	return p, nil
}
77788
func (c *Peer) OnDisconnect(f func()) {
	c.onDisconnect = append(c.onDisconnect, f)
}
1014010
func NewDeadlineHeap(ctx context.Context, coalesceWindow time.Duration) *deadlineHeap {
	d := &deadlineHeap{
		ctx:            ctx,
		coalesceWindow: coalesceWindow,
		batch:          make(chan []string),
		nodes:          make(map[string]time.Time, 64),
		trigger:        make(chan struct{}, 1),
	}

	go d.watch()
	return d
}
941247
func newSession(c *connection, es proton.Session, setting ...SessionOption) *session {
	s := &session{
		connection: c,
		pSession:   es,
	}
	s.endpoint.init(es.String())
	for _, set := range setting {
		set(s)
	}
	c.handler.sessions[s.pSession] = s
	s.pSession.SetIncomingCapacity(s.incomingCapacity)
	s.pSession.SetOutgoingWindow(s.outgoingWindow)
	s.pSession.Open()
	return s
}
316324
func NewSession(connection net.Conn) Session {
	s := session{
		connection: connection,
	}

	return &s
}
1001675
func newVaultClientHeap() *vaultClientHeap {
	return &vaultClientHeap{
		heapMap: make(map[string]*vaultClientHeapEntry),
		heap:    make(vaultDataHeapImp, 0),
	}
}
103154
func NewStreamConnection(ctx fabcontext.Client, chConfig fab.ChannelCfg, streamProvider StreamProvider, url string, opts ...options.Opt) (*StreamConnection, error) {
	conn, err := NewConnection(ctx, url, opts...)
	if err != nil {
		return nil, err
	}

	stream, err := streamProvider(conn.conn)
	if err != nil {
		conn.commManager.ReleaseConn(conn.conn)
		return nil, errors.Wrapf(err, "could not create stream to %s", url)
	}

	if stream == nil {
		return nil, errors.New("unexpected nil stream received from provider")
	}

	peer, ok := peer.FromContext(stream.Context())
	if !ok || peer == nil {
		//return error - certificate is not available
		return nil, errors.Wrap(err, "No peer cert in GRPC stream")

	}

	if peer.AuthInfo != nil {
		tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
		for _, peercert := range tlsInfo.State.PeerCertificates {
			err := verifier.ValidateCertificateDates(peercert)
			if err != nil {
				logger.Error(err)
				return nil, errors.Wrapf(err, "error validating certificate dates for [%v]", peercert.Subject)
			}
		}
	}

	return &StreamConnection{
		GRPCConnection: conn,
		chConfig:       chConfig,
		stream:         stream,
	}, nil
}
1055510
func (h *connectionHeap) Poll(hint byte) (res *Connection) {
	idx := int(hint)

	end := idx + len(h.heaps)
	for i := idx; i < end; i++ {
		if conn := h.heaps[i%len(h.heaps)].Poll(); conn != nil {
			return conn
		}
	}
	return nil
}
1240100
func (p *Plugin) NewSyncPublisher(connectionName string, topic string) (messaging.ProtoPublisher, error) {
	return p.NewProtoConnection(connectionName).NewSyncPublisher(topic)
}
79655
func (r *AttachREST) NewConnectOptions() (runtime.Object, bool, string) {
	return &api.PodAttachOptions{}, false, ""
}
1371616
func (p *Plugin) NewSyncPublisherToPartition(connectionName string, topic string, partition int32) (messaging.ProtoPublisher, error) {
	return p.NewProtoManualConnection(connectionName).NewSyncPublisherToPartition(topic, partition)
}
395431
func NewSession(config *Config) (*Session, error) {
	session := &Session{
		shutdown: make(chan struct{}),

		// Event channels, same order as api.h
		loggedIn:  make(chan error, 1),
		loggedOut: make(chan struct{}, 1),

		metadataUpdates: make(map[updatesListener]struct{}),

		connectionErrors: make(chan error, 1),
		messagesToUser:   make(chan string, 1),
		notifyMainThread: make(chan struct{}, 1),
		playTokenLost:    make(chan struct{}, 1),

		rawLogMessages: make(chan string, 128),
		logMessages:    make(chan *LogMessage, 128),

		endOfTrack:      make(chan struct{}, 1),
		streamingErrors: make(chan error, 1),

		userInfoUpdates: make(map[updatesListener]struct{}),

		offlineStatusUpdates: make(chan struct{}, 1),
		offlineErrors:        make(chan error, 1),
		credentialsBlobs:     make(chan []byte, 1),
		connectionStates:     make(chan struct{}, 1),

		scrobbleErrors:        make(chan error, 1),
		privateSessionChanges: make(chan bool, 1),

		audioConsumer: config.AudioConsumer,
	}

	if err := session.setupConfig(config); err != nil {
		return nil, err
	}

	// libspotify expects certain methods to be called from the same thread as was
	// used when the sp_session_create was called. Hence we do lock down one
	// thread to only process events and some of these special calls.
	//
	// AFAIK this is the only way we can decide which thread a given goroutine
	// executes on.
	errc := make(chan error, 1)
	go func() {
		// TODO make sure we have enough threads available
		runtime.LockOSThread()

		err := spError(C.sp_session_create(&session.config, &session.sp_session))
		errc <- err
		if err != nil {
			return
		}
		session.processEvents()
	}()

	if err := <-errc; err != nil {
		return nil, err
	}

	go session.processBackground()

	return session, nil
}
101688
func NewSocketFromPacketConnNoClose(pc net.PacketConn) (s *Socket, err error) {
	return NewSocketFromPacketConn(packetConnNopCloser{pc})
}
229867
func NewHeap(keyFn KeyFunc, lessFn LessFunc) *Heap {
	return NewHeapWithRecorder(keyFn, lessFn, nil)
}
172189
func HeapSort(stuff Sortable) {
	buildHeap(stuff)
	for i := stuff.Len() - 1; i > 0; i-- {
		stuff.Swap(0, i) // put max at end
		shuffleDown(stuff, 0, i)
	}
}
427570
func NewSession(store Store, name string) *Session {
	return &Session{
		Values:  make(map[interface{}]interface{}),
		store:   store,
		name:    name,
		Options: new(Options),
	}
}