github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/pci/parse.go (about)

     1  // Copyright 2017-2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package pci
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"log"
    11  	"strconv"
    12  )
    13  
    14  func isHex(b byte) bool {
    15  	return ('a' <= b && b <= 'f') || ('A' <= b && b <= 'F') || ('0' <= b && b <= '9')
    16  }
    17  
    18  // scan searches for Vendor and Device lines from the input *bufio.Scanner based
    19  // on pci.ids format. Found Vendors and Devices are added to the input ids map.
    20  func scan(s *bufio.Scanner, ids map[uint16]Vendor) {
    21  	var currentVendor uint16
    22  	var line string
    23  
    24  	for s.Scan() {
    25  		line = s.Text()
    26  
    27  		switch {
    28  		case isHex(line[0]) && isHex(line[1]):
    29  			v, err := strconv.ParseUint(line[:4], 16, 16)
    30  			if err != nil {
    31  				log.Printf("Bad hex constant for vendor: %v", line[:4])
    32  				continue
    33  			}
    34  			currentVendor = uint16(v)
    35  			ids[currentVendor] = Vendor{Name: line[6:], Devices: make(map[uint16]DeviceName)}
    36  
    37  		case currentVendor != 0 && line[0] == '\t' && isHex(line[1]) && isHex(line[3]):
    38  			v, err := strconv.ParseUint(line[1:5], 16, 16)
    39  			if err != nil {
    40  				log.Printf("Bad hex constant for device: %v", line[1:5])
    41  				continue
    42  			}
    43  			ids[currentVendor].Devices[uint16(v)] = DeviceName(line[7:])
    44  		}
    45  	}
    46  }
    47  
    48  func parse(input []byte) idMap {
    49  	ids := make(map[uint16]Vendor)
    50  	s := bufio.NewScanner(bytes.NewReader(input))
    51  	scan(s, ids)
    52  	return ids
    53  }