Source file: /~heha/hs/usbview.zip/src/usbids.c

#include <windows.h>
#include <stdio.h>
#ifdef UNICODE
# ifndef _UNICODE
#  define _UNICODE
# endif
#endif
#include <tchar.h>
#include "usbview.h"

typedef struct{
 BYTE len;	// even, 0 for end of list
 BYTE depth;	// depth of this item, 0..3
 WORD id;	// ID to lookup, it's the twoCC code for depth==0
 char desc[];	// variable-length zero-terminated 7-bit ASCII string to deliver
}USBIDITEM;

USBIDITEM *list;

const char* _stdcall Lookup(int twoCC, int pri, int sec, int ter) {
 const USBIDITEM *p=list;
 int depth=0;
 int lookfor=twoCC;
 if (!p) return NULL;
 for(;p->len;(BYTE*)p+=p->len) {
  if ((BYTE)depth==p->depth) {
   if ((WORD)lookfor==p->id) {
    depth++;				// go deeper
    lookfor=depth<4?(&twoCC)[depth]:-1;	// take the next argument
    if (lookfor==-1) return p->desc;	// we have it, a -1 terminates the list
   }
  }else if ((BYTE)depth>p->depth) return NULL;		// step out
 }
 return NULL;
}

bool UsbIdsLoad(LPCTSTR filename) {
 FILE *f=_tfopen(filename,T("r"));
 long flen;
 USBIDITEM *p;
 WORD twoCC=(WORD)-1;
 int dep=0;		// current depth for sanity check
 char desc[252];	// max. 251 characters
 char line[256];
 if (!f) return false;
 desc[251]=0;		// set termination character
 fseek(f,0,SEEK_END);
 flen=ftell(f);
 fseek(f,0,SEEK_SET);
 p=list=ALLOC(flen);				// overestimate size needed
 while (fgets(line,sizeof(line),f)) {
  union{
   char s[4];
   WORD twoCC;
   DWORD all;
  }pref;
  int hex;
  int depth=0;
  if (*line=='#' || *line=='\n') continue;	// skip comment and empty lines
  if (sscanf(line,"%*3[\t]%n%x %251[ -~]",&depth,&hex,desc)!=2) {	// no TAB-indented line?
   pref.all=0;
   if (sscanf(line,"%4[A-Z] %x %251[ -~]",pref.s,&hex,desc)==3	// non-VID line with up to four capital type code letters
   ||  sscanf(line,"%x %251[ -~]",&hex,desc)==2) {		// VID line (no type code info)
    if (twoCC!=pref.twoCC) {			// generate "root" with new twoCC code
     twoCC=pref.twoCC;
     p->len=4;					// no string
     p->depth=0;
     p->id=twoCC;
     p++;
     dep=0;
    }
   }else OOPS();
  }
  p->len=(4+strlen(desc)+1+1)&~1;
  p->depth=++depth;
  p->id=hex;
  lstrcpyA(p->desc,desc);
  if (dep<depth-1) OOPS();			// depth shall not rise by 2 or more
  dep=depth;
  (BYTE*)p+=p->len;
 }
 *((BYTE*)p)++=0;				// set terminator
 list=REALLOC(list,(BYTE*)p-(BYTE*)list);	// shrink to necessary size
 fclose(f);
 return true;
}

void UsbIdsFree() {
 FREE(list);
}
Detected encoding: ASCII (7 bit)2