// Copyright 2017 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package procfs

import (
	
	
	
	
	
	
)

// A BuddyInfo is the details parsed from /proc/buddyinfo.
// The data is comprised of an array of free fragments of each size.
// The sizes are 2^n*PAGE_SIZE, where n is the array index.
type BuddyInfo struct {
	Node  string
	Zone  string
	Sizes []float64
}

// BuddyInfo reads the buddyinfo statistics from the specified `proc` filesystem.
func ( FS) () ([]BuddyInfo, error) {
	,  := os.Open(.proc.Path("buddyinfo"))
	if  != nil {
		return nil, 
	}
	defer .Close()

	return parseBuddyInfo()
}

func parseBuddyInfo( io.Reader) ([]BuddyInfo, error) {
	var (
		   = []BuddyInfo{}
		     = bufio.NewScanner()
		 = -1
	)

	for .Scan() {
		var  error
		 := .Text()
		 := strings.Fields()

		if len() < 4 {
			return nil, fmt.Errorf("%w: Invalid number of fields, found: %v", ErrFileParse, )
		}

		 := strings.TrimSuffix([1], ",")
		 := strings.TrimSuffix([3], ",")
		 := len([4:])

		if  == -1 {
			 = 
		} else {
			if  !=  {
				return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, , )
			}
		}

		 := make([]float64, )
		for  := 0;  < ; ++ {
			[],  = strconv.ParseFloat([+4], 64)
			if  != nil {
				return nil, fmt.Errorf("%w: Invalid valid in buddyinfo: %f: %w", ErrFileParse, [], )
			}
		}

		 = append(, BuddyInfo{, , })
	}

	return , .Err()
}