You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

14328 lines
448 KiB

8 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /* stb.h - v2.30 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h
  2. no warranty is offered or implied; use this code at your own risk
  3. This is a single header file with a bunch of useful utilities
  4. for getting stuff done in C/C++.
  5. Documentation: http://nothings.org/stb/stb_h.html
  6. Unit tests: http://nothings.org/stb/stb.c
  7. ============================================================================
  8. You MUST
  9. #define STB_DEFINE
  10. in EXACTLY _one_ C or C++ file that includes this header, BEFORE the
  11. include, like this:
  12. #define STB_DEFINE
  13. #include "stb.h"
  14. All other files should just #include "stb.h" without the #define.
  15. ============================================================================
  16. Version History
  17. 2.30 MinGW fix
  18. 2.29 attempt to fix use of swprintf()
  19. 2.28 various new functionality
  20. 2.27 test _WIN32 not WIN32 in STB_THREADS
  21. 2.26 various warning & bugfixes
  22. 2.25 various warning & bugfixes
  23. 2.24 various warning & bugfixes
  24. 2.23 fix 2.22
  25. 2.22 64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name
  26. 2.21 utf-8 decoder rejects "overlong" encodings; attempted 64-bit improvements
  27. 2.20 fix to hash "copy" function--reported by someone with handle "!="
  28. 2.19 ???
  29. 2.18 stb_readdir_subdirs_mask
  30. 2.17 stb_cfg_dir
  31. 2.16 fix stb_bgio_, add stb_bgio_stat(); begin a streaming wrapper
  32. 2.15 upgraded hash table template to allow:
  33. - aggregate keys (explicit comparison func for EMPTY and DEL keys)
  34. - "static" implementations (so they can be culled if unused)
  35. 2.14 stb_mprintf
  36. 2.13 reduce identifiable strings in STB_NO_STB_STRINGS
  37. 2.12 fix STB_ONLY -- lots of uint32s, TRUE/FALSE things had crept in
  38. 2.11 fix bug in stb_dirtree_get() which caused "c://path" sorts of stuff
  39. 2.10 STB_F(), STB_I() inline constants (also KI,KU,KF,KD)
  40. 2.09 stb_box_face_vertex_axis_side
  41. 2.08 bugfix stb_trimwhite()
  42. 2.07 colored printing in windows (why are we in 1985?)
  43. 2.06 comparison functions are now functions-that-return-functions and
  44. accept a struct-offset as a parameter (not thread-safe)
  45. 2.05 compile and pass tests under Linux (but no threads); thread cleanup
  46. 2.04 stb_cubic_bezier_1d, smoothstep, avoid dependency on registry
  47. 2.03 ?
  48. 2.02 remove integrated documentation
  49. 2.01 integrate various fixes; stb_force_uniprocessor
  50. 2.00 revised stb_dupe to use multiple hashes
  51. 1.99 stb_charcmp
  52. 1.98 stb_arr_deleten, stb_arr_insertn
  53. 1.97 fix stb_newell_normal()
  54. 1.96 stb_hash_number()
  55. 1.95 hack stb__rec_max; clean up recursion code to use new functions
  56. 1.94 stb_dirtree; rename stb_extra to stb_ptrmap
  57. 1.93 stb_sem_new() API cleanup (no blockflag-starts blocked; use 'extra')
  58. 1.92 stb_threadqueue--multi reader/writer queue, fixed size or resizeable
  59. 1.91 stb_bgio_* for reading disk asynchronously
  60. 1.90 stb_mutex uses CRITICAL_REGION; new stb_sync primitive for thread
  61. joining; workqueue supports stb_sync instead of stb_semaphore
  62. 1.89 support ';' in constant-string wildcards; stb_mutex wrapper (can
  63. implement with EnterCriticalRegion eventually)
  64. 1.88 portable threading API (only for win32 so far); worker thread queue
  65. 1.87 fix wildcard handling in stb_readdir_recursive
  66. 1.86 support ';' in wildcards
  67. 1.85 make stb_regex work with non-constant strings;
  68. beginnings of stb_introspect()
  69. 1.84 (forgot to make notes)
  70. 1.83 whoops, stb_keep_if_different wasn't deleting the temp file
  71. 1.82 bring back stb_compress from stb_file.h for cmirror
  72. 1.81 various bugfixes, STB_FASTMALLOC_INIT inits FASTMALLOC in release
  73. 1.80 stb_readdir returns utf8; write own utf8-utf16 because lib was wrong
  74. 1.79 stb_write
  75. 1.78 calloc() support for malloc wrapper, STB_FASTMALLOC
  76. 1.77 STB_FASTMALLOC
  77. 1.76 STB_STUA - Lua-like language; (stb_image, stb_csample, stb_bilinear)
  78. 1.75 alloc/free array of blocks; stb_hheap bug; a few stb_ps_ funcs;
  79. hash*getkey, hash*copy; stb_bitset; stb_strnicmp; bugfix stb_bst
  80. 1.74 stb_replaceinplace; use stdlib C function to convert utf8 to UTF-16
  81. 1.73 fix performance bug & leak in stb_ischar (C++ port lost a 'static')
  82. 1.72 remove stb_block, stb_block_manager, stb_decompress (to stb_file.h)
  83. 1.71 stb_trimwhite, stb_tokens_nested, etc.
  84. 1.70 back out 1.69 because it might problemize mixed builds; stb_filec()
  85. 1.69 (stb_file returns 'char *' in C++)
  86. 1.68 add a special 'tree root' data type for stb_bst; stb_arr_end
  87. 1.67 full C++ port. (stb_block_manager)
  88. 1.66 stb_newell_normal
  89. 1.65 stb_lex_item_wild -- allow wildcard items which MUST match entirely
  90. 1.64 stb_data
  91. 1.63 stb_log_name
  92. 1.62 stb_define_sort; C++ cleanup
  93. 1.61 stb_hash_fast -- Paul Hsieh's hash function (beats Bob Jenkins'?)
  94. 1.60 stb_delete_directory_recursive
  95. 1.59 stb_readdir_recursive
  96. 1.58 stb_bst variant with parent pointer for O(1) iteration, not O(log N)
  97. 1.57 replace LCG random with Mersenne Twister (found a public domain one)
  98. 1.56 stb_perfect_hash, stb_ischar, stb_regex
  99. 1.55 new stb_bst API allows multiple BSTs per node (e.g. secondary keys)
  100. 1.54 bugfix: stb_define_hash, stb_wildmatch, regexp
  101. 1.53 stb_define_hash; recoded stb_extra, stb_sdict use it
  102. 1.52 stb_rand_define, stb_bst, stb_reverse
  103. 1.51 fix 'stb_arr_setlen(NULL, 0)'
  104. 1.50 stb_wordwrap
  105. 1.49 minor improvements to enable the scripting language
  106. 1.48 better approach for stb_arr using stb_malloc; more invasive, clearer
  107. 1.47 stb_lex (lexes stb.h at 1.5ML/s on 3Ghz P4; 60/70% of optimal/flex)
  108. 1.46 stb_wrapper_*, STB_MALLOC_WRAPPER
  109. 1.45 lightly tested DFA acceleration of regexp searching
  110. 1.44 wildcard matching & searching; regexp matching & searching
  111. 1.43 stb_temp
  112. 1.42 allow stb_arr to use stb_malloc/realloc; note this is global
  113. 1.41 make it compile in C++; (disable stb_arr in C++)
  114. 1.40 stb_dupe tweak; stb_swap; stb_substr
  115. 1.39 stb_dupe; improve stb_file_max to be less stupid
  116. 1.38 stb_sha1_file: generate sha1 for file, even > 4GB
  117. 1.37 stb_file_max; partial support for utf8 filenames in Windows
  118. 1.36 remove STB__NO_PREFIX - poor interaction with IDE, not worth it
  119. streamline stb_arr to make it separately publishable
  120. 1.35 bugfixes for stb_sdict, stb_malloc(0), stristr
  121. 1.34 (streaming interfaces for stb_compress)
  122. 1.33 stb_alloc; bug in stb_getopt; remove stb_overflow
  123. 1.32 (stb_compress returns, smaller&faster; encode window & 64-bit len)
  124. 1.31 stb_prefix_count
  125. 1.30 (STB__NO_PREFIX - remove stb_ prefixes for personal projects)
  126. 1.29 stb_fput_varlen64, etc.
  127. 1.28 stb_sha1
  128. 1.27 ?
  129. 1.26 stb_extra
  130. 1.25 ?
  131. 1.24 stb_copyfile
  132. 1.23 stb_readdir
  133. 1.22 ?
  134. 1.21 ?
  135. 1.20 ?
  136. 1.19 ?
  137. 1.18 ?
  138. 1.17 ?
  139. 1.16 ?
  140. 1.15 stb_fixpath, stb_splitpath, stb_strchr2
  141. 1.14 stb_arr
  142. 1.13 ?stb, stb_log, stb_fatal
  143. 1.12 ?stb_hash2
  144. 1.11 miniML
  145. 1.10 stb_crc32, stb_adler32
  146. 1.09 stb_sdict
  147. 1.08 stb_bitreverse, stb_ispow2, stb_big32
  148. stb_fopen, stb_fput_varlen, stb_fput_ranged
  149. stb_fcmp, stb_feq
  150. 1.07 (stb_encompress)
  151. 1.06 stb_compress
  152. 1.05 stb_tokens, (stb_hheap)
  153. 1.04 stb_rand
  154. 1.03 ?(s-strings)
  155. 1.02 ?stb_filelen, stb_tokens
  156. 1.01 stb_tolower
  157. 1.00 stb_hash, stb_intcmp
  158. stb_file, stb_stringfile, stb_fgets
  159. stb_prefix, stb_strlower, stb_strtok
  160. stb_image
  161. (stb_array), (stb_arena)
  162. Parenthesized items have since been removed.
  163. LICENSE
  164. See end of file for license information.
  165. CREDITS
  166. Written by Sean Barrett.
  167. Fixes:
  168. Philipp Wiesemann
  169. Robert Nix
  170. r-lyeh
  171. blackpawn
  172. github:Mojofreem
  173. Ryan Whitworth
  174. Vincent Isambart
  175. Mike Sartain
  176. Eugene Opalev
  177. Tim Sjostrand
  178. github:infatum
  179. */
  180. #include <stdarg.h>
  181. #ifndef STB__INCLUDE_STB_H
  182. #define STB__INCLUDE_STB_H
  183. #define STB_VERSION 1
  184. #ifdef STB_INTROSPECT
  185. #define STB_DEFINE
  186. #endif
  187. #ifdef STB_DEFINE_THREADS
  188. #ifndef STB_DEFINE
  189. #define STB_DEFINE
  190. #endif
  191. #ifndef STB_THREADS
  192. #define STB_THREADS
  193. #endif
  194. #endif
  195. #if defined(_WIN32) && !defined(__MINGW32__)
  196. #ifndef _CRT_SECURE_NO_WARNINGS
  197. #define _CRT_SECURE_NO_WARNINGS
  198. #endif
  199. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  200. #define _CRT_NONSTDC_NO_DEPRECATE
  201. #endif
  202. #ifndef _CRT_NON_CONFORMING_SWPRINTFS
  203. #define _CRT_NON_CONFORMING_SWPRINTFS
  204. #endif
  205. #if !defined(_MSC_VER) || _MSC_VER > 1700
  206. #include <intrin.h> // _BitScanReverse
  207. #endif
  208. #endif
  209. #include <stdlib.h> // stdlib could have min/max
  210. #include <stdio.h> // need FILE
  211. #include <string.h> // stb_define_hash needs memcpy/memset
  212. #include <time.h> // stb_dirtree
  213. #ifdef __MINGW32__
  214. #include <fcntl.h> // O_RDWR
  215. #endif
  216. #ifdef STB_PERSONAL
  217. typedef int Bool;
  218. #define False 0
  219. #define True 1
  220. #endif
  221. #ifdef STB_MALLOC_WRAPPER_PAGED
  222. #define STB_MALLOC_WRAPPER_DEBUG
  223. #endif
  224. #ifdef STB_MALLOC_WRAPPER_DEBUG
  225. #define STB_MALLOC_WRAPPER
  226. #endif
  227. #ifdef STB_MALLOC_WRAPPER_FASTMALLOC
  228. #define STB_FASTMALLOC
  229. #define STB_MALLOC_WRAPPER
  230. #endif
  231. #ifdef STB_FASTMALLOC
  232. #ifndef _WIN32
  233. #undef STB_FASTMALLOC
  234. #endif
  235. #endif
  236. #ifdef STB_DEFINE
  237. #include <assert.h>
  238. #include <stdarg.h>
  239. #include <stddef.h>
  240. #include <ctype.h>
  241. #include <math.h>
  242. #ifndef _WIN32
  243. #include <unistd.h>
  244. #else
  245. #include <io.h> // _mktemp
  246. #include <direct.h> // _rmdir
  247. #endif
  248. #include <sys/types.h> // stat()/_stat()
  249. #include <sys/stat.h> // stat()/_stat()
  250. #endif
  251. #define stb_min(a,b) ((a) < (b) ? (a) : (b))
  252. #define stb_max(a,b) ((a) > (b) ? (a) : (b))
  253. #ifndef STB_ONLY
  254. #if !defined(__cplusplus) && !defined(min) && !defined(max)
  255. #define min(x,y) stb_min(x,y)
  256. #define max(x,y) stb_max(x,y)
  257. #endif
  258. #ifndef M_PI
  259. #define M_PI 3.14159265358979323846f
  260. #endif
  261. #ifndef TRUE
  262. #define TRUE 1
  263. #define FALSE 0
  264. #endif
  265. #ifndef deg2rad
  266. #define deg2rad(a) ((a)*(M_PI/180))
  267. #endif
  268. #ifndef rad2deg
  269. #define rad2deg(a) ((a)*(180/M_PI))
  270. #endif
  271. #ifndef swap
  272. #ifndef __cplusplus
  273. #define swap(TYPE,a,b) \
  274. do { TYPE stb__t; stb__t = (a); (a) = (b); (b) = stb__t; } while (0)
  275. #endif
  276. #endif
  277. typedef unsigned char uint8 ;
  278. typedef signed char int8 ;
  279. typedef unsigned short uint16;
  280. typedef signed short int16;
  281. #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)
  282. typedef unsigned long uint32;
  283. typedef signed long int32;
  284. #else
  285. typedef unsigned int uint32;
  286. typedef signed int int32;
  287. #endif
  288. typedef unsigned char uchar ;
  289. typedef unsigned short ushort;
  290. typedef unsigned int uint ;
  291. typedef unsigned long ulong ;
  292. // produce compile errors if the sizes aren't right
  293. typedef char stb__testsize16[sizeof(int16)==2];
  294. typedef char stb__testsize32[sizeof(int32)==4];
  295. #endif
  296. #ifndef STB_TRUE
  297. #define STB_TRUE 1
  298. #define STB_FALSE 0
  299. #endif
  300. // if we're STB_ONLY, can't rely on uint32 or even uint, so all the
  301. // variables we'll use herein need typenames prefixed with 'stb':
  302. typedef unsigned char stb_uchar;
  303. typedef unsigned char stb_uint8;
  304. typedef unsigned int stb_uint;
  305. typedef unsigned short stb_uint16;
  306. typedef short stb_int16;
  307. typedef signed char stb_int8;
  308. #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)
  309. typedef unsigned long stb_uint32;
  310. typedef long stb_int32;
  311. #else
  312. typedef unsigned int stb_uint32;
  313. typedef int stb_int32;
  314. #endif
  315. typedef char stb__testsize2_16[sizeof(stb_uint16)==2 ? 1 : -1];
  316. typedef char stb__testsize2_32[sizeof(stb_uint32)==4 ? 1 : -1];
  317. #ifdef _MSC_VER
  318. typedef unsigned __int64 stb_uint64;
  319. typedef __int64 stb_int64;
  320. #define STB_IMM_UINT64(literalui64) (literalui64##ui64)
  321. #define STB_IMM_INT64(literali64) (literali64##i64)
  322. #else
  323. // ??
  324. typedef unsigned long long stb_uint64;
  325. typedef long long stb_int64;
  326. #define STB_IMM_UINT64(literalui64) (literalui64##ULL)
  327. #define STB_IMM_INT64(literali64) (literali64##LL)
  328. #endif
  329. typedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];
  330. // add platform-specific ways of checking for sizeof(char*) == 8,
  331. // and make those define STB_PTR64
  332. #if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__)
  333. #define STB_PTR64
  334. #endif
  335. #ifdef STB_PTR64
  336. typedef char stb__testsize2_ptr[sizeof(char *) == 8];
  337. typedef stb_uint64 stb_uinta;
  338. typedef stb_int64 stb_inta;
  339. #else
  340. typedef char stb__testsize2_ptr[sizeof(char *) == 4];
  341. typedef stb_uint32 stb_uinta;
  342. typedef stb_int32 stb_inta;
  343. #endif
  344. typedef char stb__testsize2_uinta[sizeof(stb_uinta)==sizeof(char*) ? 1 : -1];
  345. // if so, we should define an int type that is the pointer size. until then,
  346. // we'll have to make do with this (which is not the same at all!)
  347. typedef union
  348. {
  349. unsigned int i;
  350. void * p;
  351. } stb_uintptr;
  352. #ifdef __cplusplus
  353. #define STB_EXTERN extern "C"
  354. #else
  355. #define STB_EXTERN extern
  356. #endif
  357. // check for well-known debug defines
  358. #if defined(DEBUG) || defined(_DEBUG) || defined(DBG)
  359. #ifndef NDEBUG
  360. #define STB_DEBUG
  361. #endif
  362. #endif
  363. #ifdef STB_DEBUG
  364. #include <assert.h>
  365. #endif
  366. STB_EXTERN void stb_wrapper_malloc(void *newp, int sz, char *file, int line);
  367. STB_EXTERN void stb_wrapper_free(void *oldp, char *file, int line);
  368. STB_EXTERN void stb_wrapper_realloc(void *oldp, void *newp, int sz, char *file, int line);
  369. STB_EXTERN void stb_wrapper_calloc(size_t num, size_t sz, char *file, int line);
  370. STB_EXTERN void stb_wrapper_listall(void (*func)(void *ptr, int sz, char *file, int line));
  371. STB_EXTERN void stb_wrapper_dump(char *filename);
  372. STB_EXTERN int stb_wrapper_allocsize(void *oldp);
  373. STB_EXTERN void stb_wrapper_check(void *oldp);
  374. #ifdef STB_DEFINE
  375. // this is a special function used inside malloc wrapper
  376. // to do allocations that aren't tracked (to avoid
  377. // reentrancy). Of course if someone _else_ wraps realloc,
  378. // this breaks, but if they're doing that AND the malloc
  379. // wrapper they need to explicitly check for reentrancy.
  380. //
  381. // only define realloc_raw() and we do realloc(NULL,sz)
  382. // for malloc() and realloc(p,0) for free().
  383. static void * stb__realloc_raw(void *p, int sz)
  384. {
  385. if (p == NULL) return malloc(sz);
  386. if (sz == 0) { free(p); return NULL; }
  387. return realloc(p,sz);
  388. }
  389. #endif
  390. #ifdef _WIN32
  391. STB_EXTERN void * stb_smalloc(size_t sz);
  392. STB_EXTERN void stb_sfree(void *p);
  393. STB_EXTERN void * stb_srealloc(void *p, size_t sz);
  394. STB_EXTERN void * stb_scalloc(size_t n, size_t sz);
  395. STB_EXTERN char * stb_sstrdup(char *s);
  396. #endif
  397. #ifdef STB_FASTMALLOC
  398. #define malloc stb_smalloc
  399. #define free stb_sfree
  400. #define realloc stb_srealloc
  401. #define strdup stb_sstrdup
  402. #define calloc stb_scalloc
  403. #endif
  404. #ifndef STB_MALLOC_ALLCHECK
  405. #define stb__check(p) 1
  406. #else
  407. #ifndef STB_MALLOC_WRAPPER
  408. #error STB_MALLOC_ALLCHECK requires STB_MALLOC_WRAPPER
  409. #else
  410. #define stb__check(p) stb_mcheck(p)
  411. #endif
  412. #endif
  413. #ifdef STB_MALLOC_WRAPPER
  414. STB_EXTERN void * stb__malloc(int, char *, int);
  415. STB_EXTERN void * stb__realloc(void *, int, char *, int);
  416. STB_EXTERN void * stb__calloc(size_t n, size_t s, char *, int);
  417. STB_EXTERN void stb__free(void *, char *file, int);
  418. STB_EXTERN char * stb__strdup(char *s, char *file, int);
  419. STB_EXTERN void stb_malloc_checkall(void);
  420. STB_EXTERN void stb_malloc_check_counter(int init_delay, int rep_delay);
  421. #ifndef STB_MALLOC_WRAPPER_DEBUG
  422. #define stb_mcheck(p) 1
  423. #else
  424. STB_EXTERN int stb_mcheck(void *);
  425. #endif
  426. #ifdef STB_DEFINE
  427. #ifdef STB_MALLOC_WRAPPER_DEBUG
  428. #define STB__PAD 32
  429. #define STB__BIAS 16
  430. #define STB__SIG 0x51b01234
  431. #define STB__FIXSIZE(sz) (((sz+3) & ~3) + STB__PAD)
  432. #define STB__ptr(x,y) ((char *) (x) + (y))
  433. #else
  434. #define STB__ptr(x,y) (x)
  435. #define STB__FIXSIZE(sz) (sz)
  436. #endif
  437. #ifdef STB_MALLOC_WRAPPER_DEBUG
  438. int stb_mcheck(void *p)
  439. {
  440. unsigned int sz;
  441. if (p == NULL) return 1;
  442. p = ((char *) p) - STB__BIAS;
  443. sz = * (unsigned int *) p;
  444. assert(* (unsigned int *) STB__ptr(p,4) == STB__SIG);
  445. assert(* (unsigned int *) STB__ptr(p,8) == STB__SIG);
  446. assert(* (unsigned int *) STB__ptr(p,12) == STB__SIG);
  447. assert(* (unsigned int *) STB__ptr(p,sz-4) == STB__SIG+1);
  448. assert(* (unsigned int *) STB__ptr(p,sz-8) == STB__SIG+1);
  449. assert(* (unsigned int *) STB__ptr(p,sz-12) == STB__SIG+1);
  450. assert(* (unsigned int *) STB__ptr(p,sz-16) == STB__SIG+1);
  451. stb_wrapper_check(STB__ptr(p, STB__BIAS));
  452. return 1;
  453. }
  454. static void stb__check2(void *p, int sz, char *file, int line)
  455. {
  456. stb_mcheck(p);
  457. }
  458. void stb_malloc_checkall(void)
  459. {
  460. stb_wrapper_listall(stb__check2);
  461. }
  462. #else
  463. void stb_malloc_checkall(void) { }
  464. #endif
  465. static int stb__malloc_wait=(1 << 30), stb__malloc_next_wait = (1 << 30), stb__malloc_iter;
  466. void stb_malloc_check_counter(int init_delay, int rep_delay)
  467. {
  468. stb__malloc_wait = init_delay;
  469. stb__malloc_next_wait = rep_delay;
  470. }
  471. void stb_mcheck_all(void)
  472. {
  473. #ifdef STB_MALLOC_WRAPPER_DEBUG
  474. ++stb__malloc_iter;
  475. if (--stb__malloc_wait <= 0) {
  476. stb_malloc_checkall();
  477. stb__malloc_wait = stb__malloc_next_wait;
  478. }
  479. #endif
  480. }
  481. #ifdef STB_MALLOC_WRAPPER_PAGED
  482. #define STB__WINDOWS_PAGE (1 << 12)
  483. #ifndef _WINDOWS_
  484. STB_EXTERN __declspec(dllimport) void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);
  485. STB_EXTERN __declspec(dllimport) int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);
  486. #endif
  487. #endif
  488. static void *stb__malloc_final(int sz)
  489. {
  490. #ifdef STB_MALLOC_WRAPPER_PAGED
  491. int aligned = (sz + STB__WINDOWS_PAGE - 1) & ~(STB__WINDOWS_PAGE-1);
  492. char *p = VirtualAlloc(NULL, aligned + STB__WINDOWS_PAGE, 0x2000, 0x04); // RESERVE, READWRITE
  493. if (p == NULL) return p;
  494. VirtualAlloc(p, aligned, 0x1000, 0x04); // COMMIT, READWRITE
  495. return p;
  496. #else
  497. return malloc(sz);
  498. #endif
  499. }
  500. static void stb__free_final(void *p)
  501. {
  502. #ifdef STB_MALLOC_WRAPPER_PAGED
  503. VirtualFree(p, 0, 0x8000); // RELEASE
  504. #else
  505. free(p);
  506. #endif
  507. }
  508. int stb__malloc_failure;
  509. static void *stb__realloc_final(void *p, int sz, int old_sz)
  510. {
  511. #ifdef STB_MALLOC_WRAPPER_PAGED
  512. void *q = stb__malloc_final(sz);
  513. if (q == NULL)
  514. return ++stb__malloc_failure, q;
  515. // @TODO: deal with p being smaller!
  516. memcpy(q, p, sz < old_sz ? sz : old_sz);
  517. stb__free_final(p);
  518. return q;
  519. #else
  520. return realloc(p,sz);
  521. #endif
  522. }
  523. void stb__free(void *p, char *file, int line)
  524. {
  525. stb_mcheck_all();
  526. if (!p) return;
  527. #ifdef STB_MALLOC_WRAPPER_DEBUG
  528. stb_mcheck(p);
  529. #endif
  530. stb_wrapper_free(p,file,line);
  531. #ifdef STB_MALLOC_WRAPPER_DEBUG
  532. p = STB__ptr(p,-STB__BIAS);
  533. * (unsigned int *) STB__ptr(p,0) = 0xdeadbeef;
  534. * (unsigned int *) STB__ptr(p,4) = 0xdeadbeef;
  535. * (unsigned int *) STB__ptr(p,8) = 0xdeadbeef;
  536. * (unsigned int *) STB__ptr(p,12) = 0xdeadbeef;
  537. #endif
  538. stb__free_final(p);
  539. }
  540. void * stb__malloc(int sz, char *file, int line)
  541. {
  542. void *p;
  543. stb_mcheck_all();
  544. if (sz == 0) return NULL;
  545. p = stb__malloc_final(STB__FIXSIZE(sz));
  546. if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));
  547. if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));
  548. if (p == NULL) {
  549. ++stb__malloc_failure;
  550. #ifdef STB_MALLOC_WRAPPER_DEBUG
  551. stb_malloc_checkall();
  552. #endif
  553. return p;
  554. }
  555. #ifdef STB_MALLOC_WRAPPER_DEBUG
  556. * (int *) STB__ptr(p,0) = STB__FIXSIZE(sz);
  557. * (unsigned int *) STB__ptr(p,4) = STB__SIG;
  558. * (unsigned int *) STB__ptr(p,8) = STB__SIG;
  559. * (unsigned int *) STB__ptr(p,12) = STB__SIG;
  560. * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-4) = STB__SIG+1;
  561. * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-8) = STB__SIG+1;
  562. * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-12) = STB__SIG+1;
  563. * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-16) = STB__SIG+1;
  564. p = STB__ptr(p, STB__BIAS);
  565. #endif
  566. stb_wrapper_malloc(p,sz,file,line);
  567. return p;
  568. }
  569. void * stb__realloc(void *p, int sz, char *file, int line)
  570. {
  571. void *q;
  572. stb_mcheck_all();
  573. if (p == NULL) return stb__malloc(sz,file,line);
  574. if (sz == 0 ) { stb__free(p,file,line); return NULL; }
  575. #ifdef STB_MALLOC_WRAPPER_DEBUG
  576. stb_mcheck(p);
  577. p = STB__ptr(p,-STB__BIAS);
  578. #endif
  579. #ifdef STB_MALLOC_WRAPPER_PAGED
  580. {
  581. int n = stb_wrapper_allocsize(STB__ptr(p,STB__BIAS));
  582. if (!n)
  583. stb_wrapper_check(STB__ptr(p,STB__BIAS));
  584. q = stb__realloc_final(p, STB__FIXSIZE(sz), STB__FIXSIZE(n));
  585. }
  586. #else
  587. q = realloc(p, STB__FIXSIZE(sz));
  588. #endif
  589. if (q == NULL)
  590. return ++stb__malloc_failure, q;
  591. #ifdef STB_MALLOC_WRAPPER_DEBUG
  592. * (int *) STB__ptr(q,0) = STB__FIXSIZE(sz);
  593. * (unsigned int *) STB__ptr(q,4) = STB__SIG;
  594. * (unsigned int *) STB__ptr(q,8) = STB__SIG;
  595. * (unsigned int *) STB__ptr(q,12) = STB__SIG;
  596. * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-4) = STB__SIG+1;
  597. * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-8) = STB__SIG+1;
  598. * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-12) = STB__SIG+1;
  599. * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-16) = STB__SIG+1;
  600. q = STB__ptr(q, STB__BIAS);
  601. p = STB__ptr(p, STB__BIAS);
  602. #endif
  603. stb_wrapper_realloc(p,q,sz,file,line);
  604. return q;
  605. }
  606. STB_EXTERN int stb_log2_ceil(unsigned int);
  607. static void *stb__calloc(size_t n, size_t sz, char *file, int line)
  608. {
  609. void *q;
  610. stb_mcheck_all();
  611. if (n == 0 || sz == 0) return NULL;
  612. if (stb_log2_ceil(n) + stb_log2_ceil(sz) >= 32) return NULL;
  613. q = stb__malloc(n*sz, file, line);
  614. if (q) memset(q, 0, n*sz);
  615. return q;
  616. }
  617. char * stb__strdup(char *s, char *file, int line)
  618. {
  619. char *p;
  620. stb_mcheck_all();
  621. p = stb__malloc(strlen(s)+1, file, line);
  622. if (!p) return p;
  623. strcpy(p, s);
  624. return p;
  625. }
  626. #endif // STB_DEFINE
  627. #ifdef STB_FASTMALLOC
  628. #undef malloc
  629. #undef realloc
  630. #undef free
  631. #undef strdup
  632. #undef calloc
  633. #endif
  634. // include everything that might define these, BEFORE making macros
  635. #include <stdlib.h>
  636. #include <string.h>
  637. #include <malloc.h>
  638. #define malloc(s) stb__malloc ( s, __FILE__, __LINE__)
  639. #define realloc(p,s) stb__realloc(p,s, __FILE__, __LINE__)
  640. #define calloc(n,s) stb__calloc (n,s, __FILE__, __LINE__)
  641. #define free(p) stb__free (p, __FILE__, __LINE__)
  642. #define strdup(p) stb__strdup (p, __FILE__, __LINE__)
  643. #endif
  644. //////////////////////////////////////////////////////////////////////////////
  645. //
  646. // Windows pretty display
  647. //
  648. STB_EXTERN void stbprint(const char *fmt, ...);
  649. STB_EXTERN char *stb_sprintf(const char *fmt, ...);
  650. STB_EXTERN char *stb_mprintf(const char *fmt, ...);
  651. STB_EXTERN int stb_snprintf(char *s, size_t n, const char *fmt, ...);
  652. STB_EXTERN int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);
  653. #ifdef STB_DEFINE
  654. int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)
  655. {
  656. int res;
  657. #ifdef _WIN32
  658. // Could use "_vsnprintf_s(s, n, _TRUNCATE, fmt, v)" ?
  659. res = _vsnprintf(s,n,fmt,v);
  660. #else
  661. res = vsnprintf(s,n,fmt,v);
  662. #endif
  663. if (n) s[n-1] = 0;
  664. // Unix returns length output would require, Windows returns negative when truncated.
  665. return (res >= (int) n || res < 0) ? -1 : res;
  666. }
  667. int stb_snprintf(char *s, size_t n, const char *fmt, ...)
  668. {
  669. int res;
  670. va_list v;
  671. va_start(v,fmt);
  672. res = stb_vsnprintf(s, n, fmt, v);
  673. va_end(v);
  674. return res;
  675. }
  676. char *stb_sprintf(const char *fmt, ...)
  677. {
  678. static char buffer[1024];
  679. va_list v;
  680. va_start(v,fmt);
  681. stb_vsnprintf(buffer,1024,fmt,v);
  682. va_end(v);
  683. return buffer;
  684. }
  685. char *stb_mprintf(const char *fmt, ...)
  686. {
  687. static char buffer[1024];
  688. va_list v;
  689. va_start(v,fmt);
  690. stb_vsnprintf(buffer,1024,fmt,v);
  691. va_end(v);
  692. return strdup(buffer);
  693. }
  694. #ifdef _WIN32
  695. #ifndef _WINDOWS_
  696. STB_EXTERN __declspec(dllimport) int __stdcall WriteConsoleA(void *, const void *, unsigned int, unsigned int *, void *);
  697. STB_EXTERN __declspec(dllimport) void * __stdcall GetStdHandle(unsigned int);
  698. STB_EXTERN __declspec(dllimport) int __stdcall SetConsoleTextAttribute(void *, unsigned short);
  699. #endif
  700. static void stb__print_one(void *handle, char *s, int len)
  701. {
  702. if (len)
  703. if (WriteConsoleA(handle, s, len, NULL,NULL))
  704. fwrite(s, 1, len, stdout); // if it fails, maybe redirected, so do normal
  705. }
  706. static void stb__print(char *s)
  707. {
  708. void *handle = GetStdHandle((unsigned int) -11); // STD_OUTPUT_HANDLE
  709. int pad=0; // number of padding characters to add
  710. char *t = s;
  711. while (*s) {
  712. int lpad;
  713. while (*s && *s != '{') {
  714. if (pad) {
  715. if (*s == '\r' || *s == '\n')
  716. pad = 0;
  717. else if (s[0] == ' ' && s[1] == ' ') {
  718. stb__print_one(handle, t, s-t);
  719. t = s;
  720. while (pad) {
  721. stb__print_one(handle, t, 1);
  722. --pad;
  723. }
  724. }
  725. }
  726. ++s;
  727. }
  728. if (!*s) break;
  729. stb__print_one(handle, t, s-t);
  730. if (s[1] == '{') {
  731. ++s;
  732. continue;
  733. }
  734. if (s[1] == '#') {
  735. t = s+3;
  736. if (isxdigit(s[2]))
  737. if (isdigit(s[2]))
  738. SetConsoleTextAttribute(handle, s[2] - '0');
  739. else
  740. SetConsoleTextAttribute(handle, tolower(s[2]) - 'a' + 10);
  741. else {
  742. SetConsoleTextAttribute(handle, 0x0f);
  743. t=s+2;
  744. }
  745. } else if (s[1] == '!') {
  746. SetConsoleTextAttribute(handle, 0x0c);
  747. t = s+2;
  748. } else if (s[1] == '@') {
  749. SetConsoleTextAttribute(handle, 0x09);
  750. t = s+2;
  751. } else if (s[1] == '$') {
  752. SetConsoleTextAttribute(handle, 0x0a);
  753. t = s+2;
  754. } else {
  755. SetConsoleTextAttribute(handle, 0x08); // 0,7,8,15 => shades of grey
  756. t = s+1;
  757. }
  758. lpad = (t-s);
  759. s = t;
  760. while (*s && *s != '}') ++s;
  761. if (!*s) break;
  762. stb__print_one(handle, t, s-t);
  763. if (s[1] == '}') {
  764. t = s+2;
  765. } else {
  766. pad += 1+lpad;
  767. t = s+1;
  768. }
  769. s=t;
  770. SetConsoleTextAttribute(handle, 0x07);
  771. }
  772. stb__print_one(handle, t, s-t);
  773. SetConsoleTextAttribute(handle, 0x07);
  774. }
  775. void stbprint(const char *fmt, ...)
  776. {
  777. int res;
  778. char buffer[1024];
  779. char *tbuf = buffer;
  780. va_list v;
  781. va_start(v,fmt);
  782. res = stb_vsnprintf(buffer, sizeof(buffer), fmt, v);
  783. va_end(v);
  784. if (res < 0) {
  785. tbuf = (char *) malloc(16384);
  786. va_start(v,fmt);
  787. res = _vsnprintf(tbuf,16384, fmt, v);
  788. va_end(v);
  789. tbuf[16383] = 0;
  790. }
  791. stb__print(tbuf);
  792. if (tbuf != buffer)
  793. free(tbuf);
  794. }
  795. #else // _WIN32
  796. void stbprint(const char *fmt, ...)
  797. {
  798. va_list v;
  799. va_start(v,fmt);
  800. vprintf(fmt,v);
  801. va_end(v);
  802. }
  803. #endif // _WIN32
  804. #endif // STB_DEFINE
  805. //////////////////////////////////////////////////////////////////////////////
  806. //
  807. // Windows UTF8 filename handling
  808. //
  809. // Windows stupidly treats 8-bit filenames as some dopey code page,
  810. // rather than utf-8. If we want to use utf8 filenames, we have to
  811. // convert them to WCHAR explicitly and call WCHAR versions of the
  812. // file functions. So, ok, we do.
  813. #ifdef _WIN32
  814. #define stb__fopen(x,y) _wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))
  815. #define stb__windows(x,y) x
  816. #else
  817. #define stb__fopen(x,y) fopen(x,y)
  818. #define stb__windows(x,y) y
  819. #endif
  820. typedef unsigned short stb__wchar;
  821. STB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, char *str, int n);
  822. STB_EXTERN char * stb_to_utf8 (char *buffer, stb__wchar *str, int n);
  823. STB_EXTERN stb__wchar *stb__from_utf8(char *str);
  824. STB_EXTERN stb__wchar *stb__from_utf8_alt(char *str);
  825. STB_EXTERN char *stb__to_utf8(stb__wchar *str);
  826. #ifdef STB_DEFINE
  827. stb__wchar * stb_from_utf8(stb__wchar *buffer, char *ostr, int n)
  828. {
  829. unsigned char *str = (unsigned char *) ostr;
  830. stb_uint32 c;
  831. int i=0;
  832. --n;
  833. while (*str) {
  834. if (i >= n)
  835. return NULL;
  836. if (!(*str & 0x80))
  837. buffer[i++] = *str++;
  838. else if ((*str & 0xe0) == 0xc0) {
  839. if (*str < 0xc2) return NULL;
  840. c = (*str++ & 0x1f) << 6;
  841. if ((*str & 0xc0) != 0x80) return NULL;
  842. buffer[i++] = c + (*str++ & 0x3f);
  843. } else if ((*str & 0xf0) == 0xe0) {
  844. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL;
  845. if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below
  846. c = (*str++ & 0x0f) << 12;
  847. if ((*str & 0xc0) != 0x80) return NULL;
  848. c += (*str++ & 0x3f) << 6;
  849. if ((*str & 0xc0) != 0x80) return NULL;
  850. buffer[i++] = c + (*str++ & 0x3f);
  851. } else if ((*str & 0xf8) == 0xf0) {
  852. if (*str > 0xf4) return NULL;
  853. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL;
  854. if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below
  855. c = (*str++ & 0x07) << 18;
  856. if ((*str & 0xc0) != 0x80) return NULL;
  857. c += (*str++ & 0x3f) << 12;
  858. if ((*str & 0xc0) != 0x80) return NULL;
  859. c += (*str++ & 0x3f) << 6;
  860. if ((*str & 0xc0) != 0x80) return NULL;
  861. c += (*str++ & 0x3f);
  862. // utf-8 encodings of values used in surrogate pairs are invalid
  863. if ((c & 0xFFFFF800) == 0xD800) return NULL;
  864. if (c >= 0x10000) {
  865. c -= 0x10000;
  866. if (i + 2 > n) return NULL;
  867. buffer[i++] = 0xD800 | (0x3ff & (c >> 10));
  868. buffer[i++] = 0xDC00 | (0x3ff & (c ));
  869. }
  870. } else
  871. return NULL;
  872. }
  873. buffer[i] = 0;
  874. return buffer;
  875. }
  876. char * stb_to_utf8(char *buffer, stb__wchar *str, int n)
  877. {
  878. int i=0;
  879. --n;
  880. while (*str) {
  881. if (*str < 0x80) {
  882. if (i+1 > n) return NULL;
  883. buffer[i++] = (char) *str++;
  884. } else if (*str < 0x800) {
  885. if (i+2 > n) return NULL;
  886. buffer[i++] = 0xc0 + (*str >> 6);
  887. buffer[i++] = 0x80 + (*str & 0x3f);
  888. str += 1;
  889. } else if (*str >= 0xd800 && *str < 0xdc00) {
  890. stb_uint32 c;
  891. if (i+4 > n) return NULL;
  892. c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000;
  893. buffer[i++] = 0xf0 + (c >> 18);
  894. buffer[i++] = 0x80 + ((c >> 12) & 0x3f);
  895. buffer[i++] = 0x80 + ((c >> 6) & 0x3f);
  896. buffer[i++] = 0x80 + ((c ) & 0x3f);
  897. str += 2;
  898. } else if (*str >= 0xdc00 && *str < 0xe000) {
  899. return NULL;
  900. } else {
  901. if (i+3 > n) return NULL;
  902. buffer[i++] = 0xe0 + (*str >> 12);
  903. buffer[i++] = 0x80 + ((*str >> 6) & 0x3f);
  904. buffer[i++] = 0x80 + ((*str ) & 0x3f);
  905. str += 1;
  906. }
  907. }
  908. buffer[i] = 0;
  909. return buffer;
  910. }
  911. stb__wchar *stb__from_utf8(char *str)
  912. {
  913. static stb__wchar buffer[4096];
  914. return stb_from_utf8(buffer, str, 4096);
  915. }
  916. stb__wchar *stb__from_utf8_alt(char *str)
  917. {
  918. static stb__wchar buffer[64];
  919. return stb_from_utf8(buffer, str, 64);
  920. }
  921. char *stb__to_utf8(stb__wchar *str)
  922. {
  923. static char buffer[4096];
  924. return stb_to_utf8(buffer, str, 4096);
  925. }
  926. #endif
  927. //////////////////////////////////////////////////////////////////////////////
  928. //
  929. // Miscellany
  930. //
  931. STB_EXTERN void stb_fatal(char *fmt, ...);
  932. STB_EXTERN void stb_(char *fmt, ...);
  933. STB_EXTERN void stb_append_to_file(char *file, char *fmt, ...);
  934. STB_EXTERN void stb_log(int active);
  935. STB_EXTERN void stb_log_fileline(int active);
  936. STB_EXTERN void stb_log_name(char *filename);
  937. STB_EXTERN void stb_swap(void *p, void *q, size_t sz);
  938. STB_EXTERN void *stb_copy(void *p, size_t sz);
  939. STB_EXTERN void stb_pointer_array_free(void *p, int len);
  940. STB_EXTERN void **stb_array_block_alloc(int count, int blocksize);
  941. #define stb_arrcount(x) (sizeof(x)/sizeof((x)[0]))
  942. STB_EXTERN int stb__record_fileline(char *f, int n);
  943. #ifdef STB_DEFINE
  944. static char *stb__file;
  945. static int stb__line;
  946. int stb__record_fileline(char *f, int n)
  947. {
  948. stb__file = f;
  949. stb__line = n;
  950. return 0;
  951. }
  952. void stb_fatal(char *s, ...)
  953. {
  954. va_list a;
  955. if (stb__file)
  956. fprintf(stderr, "[%s:%d] ", stb__file, stb__line);
  957. va_start(a,s);
  958. fputs("Fatal error: ", stderr);
  959. vfprintf(stderr, s, a);
  960. va_end(a);
  961. fputs("\n", stderr);
  962. #ifdef STB_DEBUG
  963. #ifdef _MSC_VER
  964. #ifndef STB_PTR64
  965. __asm int 3; // trap to debugger!
  966. #else
  967. __debugbreak();
  968. #endif
  969. #else
  970. __builtin_trap();
  971. #endif
  972. #endif
  973. exit(1);
  974. }
  975. static int stb__log_active=1, stb__log_fileline=1;
  976. void stb_log(int active)
  977. {
  978. stb__log_active = active;
  979. }
  980. void stb_log_fileline(int active)
  981. {
  982. stb__log_fileline = active;
  983. }
  984. #ifdef STB_NO_STB_STRINGS
  985. char *stb__log_filename = "temp.log";
  986. #else
  987. char *stb__log_filename = "stb.log";
  988. #endif
  989. void stb_log_name(char *s)
  990. {
  991. stb__log_filename = s;
  992. }
  993. void stb_(char *s, ...)
  994. {
  995. if (stb__log_active) {
  996. FILE *f = fopen(stb__log_filename, "a");
  997. if (f) {
  998. va_list a;
  999. if (stb__log_fileline && stb__file)
  1000. fprintf(f, "[%s:%4d] ", stb__file, stb__line);
  1001. va_start(a,s);
  1002. vfprintf(f, s, a);
  1003. va_end(a);
  1004. fputs("\n", f);
  1005. fclose(f);
  1006. }
  1007. }
  1008. }
  1009. void stb_append_to_file(char *filename, char *s, ...)
  1010. {
  1011. FILE *f = fopen(filename, "a");
  1012. if (f) {
  1013. va_list a;
  1014. va_start(a,s);
  1015. vfprintf(f, s, a);
  1016. va_end(a);
  1017. fputs("\n", f);
  1018. fclose(f);
  1019. }
  1020. }
  1021. typedef struct { char d[4]; } stb__4;
  1022. typedef struct { char d[8]; } stb__8;
  1023. // optimize the small cases, though you shouldn't be calling this for those!
  1024. void stb_swap(void *p, void *q, size_t sz)
  1025. {
  1026. char buffer[256];
  1027. if (p == q) return;
  1028. if (sz == 4) {
  1029. stb__4 temp = * ( stb__4 *) p;
  1030. * (stb__4 *) p = * ( stb__4 *) q;
  1031. * (stb__4 *) q = temp;
  1032. return;
  1033. } else if (sz == 8) {
  1034. stb__8 temp = * ( stb__8 *) p;
  1035. * (stb__8 *) p = * ( stb__8 *) q;
  1036. * (stb__8 *) q = temp;
  1037. return;
  1038. }
  1039. while (sz > sizeof(buffer)) {
  1040. stb_swap(p, q, sizeof(buffer));
  1041. p = (char *) p + sizeof(buffer);
  1042. q = (char *) q + sizeof(buffer);
  1043. sz -= sizeof(buffer);
  1044. }
  1045. memcpy(buffer, p , sz);
  1046. memcpy(p , q , sz);
  1047. memcpy(q , buffer, sz);
  1048. }
  1049. void *stb_copy(void *p, size_t sz)
  1050. {
  1051. void *q = malloc(sz);
  1052. memcpy(q, p, sz);
  1053. return q;
  1054. }
  1055. void stb_pointer_array_free(void *q, int len)
  1056. {
  1057. void **p = (void **) q;
  1058. int i;
  1059. for (i=0; i < len; ++i)
  1060. free(p[i]);
  1061. }
  1062. void **stb_array_block_alloc(int count, int blocksize)
  1063. {
  1064. int i;
  1065. char *p = (char *) malloc(sizeof(void *) * count + count * blocksize);
  1066. void **q;
  1067. if (p == NULL) return NULL;
  1068. q = (void **) p;
  1069. p += sizeof(void *) * count;
  1070. for (i=0; i < count; ++i)
  1071. q[i] = p + i * blocksize;
  1072. return q;
  1073. }
  1074. #endif
  1075. #ifdef STB_DEBUG
  1076. // tricky hack to allow recording FILE,LINE even in varargs functions
  1077. #define STB__RECORD_FILE(x) (stb__record_fileline(__FILE__, __LINE__),(x))
  1078. #define stb_log STB__RECORD_FILE(stb_log)
  1079. #define stb_ STB__RECORD_FILE(stb_)
  1080. #ifndef STB_FATAL_CLEAN
  1081. #define stb_fatal STB__RECORD_FILE(stb_fatal)
  1082. #endif
  1083. #define STB__DEBUG(x) x
  1084. #else
  1085. #define STB__DEBUG(x)
  1086. #endif
  1087. //////////////////////////////////////////////////////////////////////////////
  1088. //
  1089. // stb_temp
  1090. //
  1091. #define stb_temp(block, sz) stb__temp(block, sizeof(block), (sz))
  1092. STB_EXTERN void * stb__temp(void *b, int b_sz, int want_sz);
  1093. STB_EXTERN void stb_tempfree(void *block, void *ptr);
  1094. #ifdef STB_DEFINE
  1095. void * stb__temp(void *b, int b_sz, int want_sz)
  1096. {
  1097. if (b_sz >= want_sz)
  1098. return b;
  1099. else
  1100. return malloc(want_sz);
  1101. }
  1102. void stb_tempfree(void *b, void *p)
  1103. {
  1104. if (p != b)
  1105. free(p);
  1106. }
  1107. #endif
  1108. //////////////////////////////////////////////////////////////////////////////
  1109. //
  1110. // math/sampling operations
  1111. //
  1112. #define stb_lerp(t,a,b) ( (a) + (t) * (float) ((b)-(a)) )
  1113. #define stb_unlerp(t,a,b) ( ((t) - (a)) / (float) ((b) - (a)) )
  1114. #define stb_clamp(x,xmin,xmax) ((x) < (xmin) ? (xmin) : (x) > (xmax) ? (xmax) : (x))
  1115. STB_EXTERN void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize);
  1116. STB_EXTERN int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis);
  1117. STB_EXTERN void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt);
  1118. STB_EXTERN int stb_float_eq(float x, float y, float delta, int max_ulps);
  1119. STB_EXTERN int stb_is_prime(unsigned int m);
  1120. STB_EXTERN unsigned int stb_power_of_two_nearest_prime(int n);
  1121. STB_EXTERN float stb_smoothstep(float t);
  1122. STB_EXTERN float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3);
  1123. STB_EXTERN double stb_linear_remap(double x, double a, double b,
  1124. double c, double d);
  1125. #ifdef STB_DEFINE
  1126. float stb_smoothstep(float t)
  1127. {
  1128. return (3 - 2*t)*(t*t);
  1129. }
  1130. float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3)
  1131. {
  1132. float it = 1-t;
  1133. return it*it*it*p0 + 3*it*it*t*p1 + 3*it*t*t*p2 + t*t*t*p3;
  1134. }
  1135. void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize)
  1136. {
  1137. int i,j;
  1138. float p;
  1139. normal[0] = normal[1] = normal[2] = 0;
  1140. for (i=num_vert-1,j=0; j < num_vert; i=j++) {
  1141. float *u = vert[i];
  1142. float *v = vert[j];
  1143. normal[0] += (u[1] - v[1]) * (u[2] + v[2]);
  1144. normal[1] += (u[2] - v[2]) * (u[0] + v[0]);
  1145. normal[2] += (u[0] - v[0]) * (u[1] + v[1]);
  1146. }
  1147. if (normalize) {
  1148. p = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2];
  1149. p = (float) (1.0 / sqrt(p));
  1150. normal[0] *= p;
  1151. normal[1] *= p;
  1152. normal[2] *= p;
  1153. }
  1154. }
  1155. int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis)
  1156. {
  1157. static int box_vertices[6][4][3] =
  1158. {
  1159. { { 1,1,1 }, { 1,0,1 }, { 1,0,0 }, { 1,1,0 } },
  1160. { { 0,0,0 }, { 0,0,1 }, { 0,1,1 }, { 0,1,0 } },
  1161. { { 0,0,0 }, { 0,1,0 }, { 1,1,0 }, { 1,0,0 } },
  1162. { { 0,0,0 }, { 1,0,0 }, { 1,0,1 }, { 0,0,1 } },
  1163. { { 1,1,1 }, { 0,1,1 }, { 0,0,1 }, { 1,0,1 } },
  1164. { { 1,1,1 }, { 1,1,0 }, { 0,1,0 }, { 0,1,1 } },
  1165. };
  1166. assert(face_number >= 0 && face_number < 6);
  1167. assert(vertex_number >= 0 && vertex_number < 4);
  1168. assert(axis >= 0 && axis < 3);
  1169. return box_vertices[face_number][vertex_number][axis];
  1170. }
  1171. void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt)
  1172. {
  1173. float sign = 1, p, cp = *curpos;
  1174. if (cp == target_pos) return;
  1175. if (target_pos < cp) {
  1176. target_pos = -target_pos;
  1177. cp = -cp;
  1178. sign = -1;
  1179. }
  1180. // first decelerate
  1181. if (cp < 0) {
  1182. p = cp + deacc * dt;
  1183. if (p > 0) {
  1184. p = 0;
  1185. dt = dt - cp / deacc;
  1186. if (dt < 0) dt = 0;
  1187. } else {
  1188. dt = 0;
  1189. }
  1190. cp = p;
  1191. }
  1192. // now accelerate
  1193. p = cp + acc*dt;
  1194. if (p > target_pos) p = target_pos;
  1195. *curpos = p * sign;
  1196. // @TODO: testing
  1197. }
  1198. float stb_quadratic_controller(float target_pos, float curpos, float maxvel, float maxacc, float dt, float *curvel)
  1199. {
  1200. return 0; // @TODO
  1201. }
  1202. int stb_float_eq(float x, float y, float delta, int max_ulps)
  1203. {
  1204. if (fabs(x-y) <= delta) return 1;
  1205. if (abs(*(int *)&x - *(int *)&y) <= max_ulps) return 1;
  1206. return 0;
  1207. }
  1208. int stb_is_prime(unsigned int m)
  1209. {
  1210. unsigned int i,j;
  1211. if (m < 2) return 0;
  1212. if (m == 2) return 1;
  1213. if (!(m & 1)) return 0;
  1214. if (m % 3 == 0) return (m == 3);
  1215. for (i=5; (j=i*i), j <= m && j > i; i += 6) {
  1216. if (m % i == 0) return 0;
  1217. if (m % (i+2) == 0) return 0;
  1218. }
  1219. return 1;
  1220. }
  1221. unsigned int stb_power_of_two_nearest_prime(int n)
  1222. {
  1223. static signed char tab[32] = { 0,0,0,0,1,0,-1,0,1,-1,-1,3,-1,0,-1,2,1,
  1224. 0,2,0,-1,-4,-1,5,-1,18,-2,15,2,-1,2,0 };
  1225. if (!tab[0]) {
  1226. int i;
  1227. for (i=0; i < 32; ++i)
  1228. tab[i] = (1 << i) + 2*tab[i] - 1;
  1229. tab[1] = 2;
  1230. tab[0] = 1;
  1231. }
  1232. if (n >= 32) return 0xfffffffb;
  1233. return tab[n];
  1234. }
  1235. double stb_linear_remap(double x, double x_min, double x_max,
  1236. double out_min, double out_max)
  1237. {
  1238. return stb_lerp(stb_unlerp(x,x_min,x_max),out_min,out_max);
  1239. }
  1240. #endif
  1241. // create a macro so it's faster, but you can get at the function pointer
  1242. #define stb_linear_remap(t,a,b,c,d) stb_lerp(stb_unlerp(t,a,b),c,d)
  1243. //////////////////////////////////////////////////////////////////////////////
  1244. //
  1245. // bit operations
  1246. //
  1247. #define stb_big32(c) (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3])
  1248. #define stb_little32(c) (((c)[3]<<24) + (c)[2]*65536 + (c)[1]*256 + (c)[0])
  1249. #define stb_big16(c) ((c)[0]*256 + (c)[1])
  1250. #define stb_little16(c) ((c)[1]*256 + (c)[0])
  1251. STB_EXTERN int stb_bitcount(unsigned int a);
  1252. STB_EXTERN unsigned int stb_bitreverse8(unsigned char n);
  1253. STB_EXTERN unsigned int stb_bitreverse(unsigned int n);
  1254. STB_EXTERN int stb_is_pow2(unsigned int n);
  1255. STB_EXTERN int stb_log2_ceil(unsigned int n);
  1256. STB_EXTERN int stb_log2_floor(unsigned int n);
  1257. STB_EXTERN int stb_lowbit8(unsigned int n);
  1258. STB_EXTERN int stb_highbit8(unsigned int n);
  1259. #ifdef STB_DEFINE
  1260. int stb_bitcount(unsigned int a)
  1261. {
  1262. a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
  1263. a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
  1264. a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
  1265. a = (a + (a >> 8)); // max 16 per 8 bits
  1266. a = (a + (a >> 16)); // max 32 per 8 bits
  1267. return a & 0xff;
  1268. }
  1269. unsigned int stb_bitreverse8(unsigned char n)
  1270. {
  1271. n = ((n & 0xAA) >> 1) + ((n & 0x55) << 1);
  1272. n = ((n & 0xCC) >> 2) + ((n & 0x33) << 2);
  1273. return (unsigned char) ((n >> 4) + (n << 4));
  1274. }
  1275. unsigned int stb_bitreverse(unsigned int n)
  1276. {
  1277. n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
  1278. n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
  1279. n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
  1280. n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
  1281. return (n >> 16) | (n << 16);
  1282. }
  1283. int stb_is_pow2(unsigned int n)
  1284. {
  1285. return (n & (n-1)) == 0;
  1286. }
  1287. // tricky use of 4-bit table to identify 5 bit positions (note the '-1')
  1288. // 3-bit table would require another tree level; 5-bit table wouldn't save one
  1289. #if defined(_WIN32) && !defined(__MINGW32__)
  1290. #pragma warning(push)
  1291. #pragma warning(disable: 4035) // disable warning about no return value
  1292. int stb_log2_floor(unsigned int n)
  1293. {
  1294. #if _MSC_VER > 1700
  1295. unsigned long i;
  1296. _BitScanReverse(&i, n);
  1297. return i != 0 ? i : -1;
  1298. #else
  1299. __asm {
  1300. bsr eax,n
  1301. jnz done
  1302. mov eax,-1
  1303. }
  1304. done:;
  1305. #endif
  1306. }
  1307. #pragma warning(pop)
  1308. #else
  1309. int stb_log2_floor(unsigned int n)
  1310. {
  1311. static signed char log2_4[16] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3 };
  1312. // 2 compares if n < 16, 3 compares otherwise
  1313. if (n < (1U << 14))
  1314. if (n < (1U << 4)) return 0 + log2_4[n ];
  1315. else if (n < (1U << 9)) return 5 + log2_4[n >> 5];
  1316. else return 10 + log2_4[n >> 10];
  1317. else if (n < (1U << 24))
  1318. if (n < (1U << 19)) return 15 + log2_4[n >> 15];
  1319. else return 20 + log2_4[n >> 20];
  1320. else if (n < (1U << 29)) return 25 + log2_4[n >> 25];
  1321. else return 30 + log2_4[n >> 30];
  1322. }
  1323. #endif
  1324. // define ceil from floor
  1325. int stb_log2_ceil(unsigned int n)
  1326. {
  1327. if (stb_is_pow2(n)) return stb_log2_floor(n);
  1328. else return 1 + stb_log2_floor(n);
  1329. }
  1330. int stb_highbit8(unsigned int n)
  1331. {
  1332. return stb_log2_ceil(n&255);
  1333. }
  1334. int stb_lowbit8(unsigned int n)
  1335. {
  1336. static signed char lowbit4[16] = { -1,0,1,0, 2,0,1,0, 3,0,1,0, 2,0,1,0 };
  1337. int k = lowbit4[n & 15];
  1338. if (k >= 0) return k;
  1339. k = lowbit4[(n >> 4) & 15];
  1340. if (k >= 0) return k+4;
  1341. return k;
  1342. }
  1343. #endif
  1344. //////////////////////////////////////////////////////////////////////////////
  1345. //
  1346. // qsort Compare Routines
  1347. //
  1348. #ifdef _WIN32
  1349. #define stb_stricmp(a,b) stricmp(a,b)
  1350. #define stb_strnicmp(a,b,n) strnicmp(a,b,n)
  1351. #else
  1352. #define stb_stricmp(a,b) strcasecmp(a,b)
  1353. #define stb_strnicmp(a,b,n) strncasecmp(a,b,n)
  1354. #endif
  1355. STB_EXTERN int (*stb_intcmp(int offset))(const void *a, const void *b);
  1356. STB_EXTERN int (*stb_qsort_strcmp(int offset))(const void *a, const void *b);
  1357. STB_EXTERN int (*stb_qsort_stricmp(int offset))(const void *a, const void *b);
  1358. STB_EXTERN int (*stb_floatcmp(int offset))(const void *a, const void *b);
  1359. STB_EXTERN int (*stb_doublecmp(int offset))(const void *a, const void *b);
  1360. STB_EXTERN int (*stb_charcmp(int offset))(const void *a, const void *b);
  1361. #ifdef STB_DEFINE
  1362. static int stb__intcmpoffset, stb__charcmpoffset, stb__strcmpoffset;
  1363. static int stb__floatcmpoffset, stb__doublecmpoffset;
  1364. int stb__intcmp(const void *a, const void *b)
  1365. {
  1366. const int p = *(const int *) ((const char *) a + stb__intcmpoffset);
  1367. const int q = *(const int *) ((const char *) b + stb__intcmpoffset);
  1368. return p < q ? -1 : p > q;
  1369. }
  1370. int stb__charcmp(const void *a, const void *b)
  1371. {
  1372. const int p = *(const unsigned char *) ((const char *) a + stb__charcmpoffset);
  1373. const int q = *(const unsigned char *) ((const char *) b + stb__charcmpoffset);
  1374. return p < q ? -1 : p > q;
  1375. }
  1376. int stb__floatcmp(const void *a, const void *b)
  1377. {
  1378. const float p = *(const float *) ((const char *) a + stb__floatcmpoffset);
  1379. const float q = *(const float *) ((const char *) b + stb__floatcmpoffset);
  1380. return p < q ? -1 : p > q;
  1381. }
  1382. int stb__doublecmp(const void *a, const void *b)
  1383. {
  1384. const double p = *(const double *) ((const char *) a + stb__doublecmpoffset);
  1385. const double q = *(const double *) ((const char *) b + stb__doublecmpoffset);
  1386. return p < q ? -1 : p > q;
  1387. }
  1388. int stb__qsort_strcmp(const void *a, const void *b)
  1389. {
  1390. const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);
  1391. const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);
  1392. return strcmp(p,q);
  1393. }
  1394. int stb__qsort_stricmp(const void *a, const void *b)
  1395. {
  1396. const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);
  1397. const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);
  1398. return stb_stricmp(p,q);
  1399. }
  1400. int (*stb_intcmp(int offset))(const void *, const void *)
  1401. {
  1402. stb__intcmpoffset = offset;
  1403. return &stb__intcmp;
  1404. }
  1405. int (*stb_charcmp(int offset))(const void *, const void *)
  1406. {
  1407. stb__charcmpoffset = offset;
  1408. return &stb__charcmp;
  1409. }
  1410. int (*stb_qsort_strcmp(int offset))(const void *, const void *)
  1411. {
  1412. stb__strcmpoffset = offset;
  1413. return &stb__qsort_strcmp;
  1414. }
  1415. int (*stb_qsort_stricmp(int offset))(const void *, const void *)
  1416. {
  1417. stb__strcmpoffset = offset;
  1418. return &stb__qsort_stricmp;
  1419. }
  1420. int (*stb_floatcmp(int offset))(const void *, const void *)
  1421. {
  1422. stb__floatcmpoffset = offset;
  1423. return &stb__floatcmp;
  1424. }
  1425. int (*stb_doublecmp(int offset))(const void *, const void *)
  1426. {
  1427. stb__doublecmpoffset = offset;
  1428. return &stb__doublecmp;
  1429. }
  1430. #endif
  1431. //////////////////////////////////////////////////////////////////////////////
  1432. //
  1433. // Binary Search Toolkit
  1434. //
  1435. typedef struct
  1436. {
  1437. int minval, maxval, guess;
  1438. int mode, step;
  1439. } stb_search;
  1440. STB_EXTERN int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest);
  1441. STB_EXTERN int stb_search_open(stb_search *s, int minv, int find_smallest);
  1442. STB_EXTERN int stb_probe(stb_search *s, int compare, int *result); // return 0 when done
  1443. #ifdef STB_DEFINE
  1444. enum
  1445. {
  1446. STB_probe_binary_smallest,
  1447. STB_probe_binary_largest,
  1448. STB_probe_open_smallest,
  1449. STB_probe_open_largest,
  1450. };
  1451. static int stb_probe_guess(stb_search *s, int *result)
  1452. {
  1453. switch(s->mode) {
  1454. case STB_probe_binary_largest:
  1455. if (s->minval == s->maxval) {
  1456. *result = s->minval;
  1457. return 0;
  1458. }
  1459. assert(s->minval < s->maxval);
  1460. // if a < b, then a < p <= b
  1461. s->guess = s->minval + (((unsigned) s->maxval - s->minval + 1) >> 1);
  1462. break;
  1463. case STB_probe_binary_smallest:
  1464. if (s->minval == s->maxval) {
  1465. *result = s->minval;
  1466. return 0;
  1467. }
  1468. assert(s->minval < s->maxval);
  1469. // if a < b, then a <= p < b
  1470. s->guess = s->minval + (((unsigned) s->maxval - s->minval) >> 1);
  1471. break;
  1472. case STB_probe_open_smallest:
  1473. case STB_probe_open_largest:
  1474. s->guess = s->maxval; // guess the current maxval
  1475. break;
  1476. }
  1477. *result = s->guess;
  1478. return 1;
  1479. }
  1480. int stb_probe(stb_search *s, int compare, int *result)
  1481. {
  1482. switch(s->mode) {
  1483. case STB_probe_open_smallest:
  1484. case STB_probe_open_largest: {
  1485. if (compare <= 0) {
  1486. // then it lies within minval & maxval
  1487. if (s->mode == STB_probe_open_smallest)
  1488. s->mode = STB_probe_binary_smallest;
  1489. else
  1490. s->mode = STB_probe_binary_largest;
  1491. } else {
  1492. // otherwise, we need to probe larger
  1493. s->minval = s->maxval + 1;
  1494. s->maxval = s->minval + s->step;
  1495. s->step += s->step;
  1496. }
  1497. break;
  1498. }
  1499. case STB_probe_binary_smallest: {
  1500. // if compare < 0, then s->minval <= a < p
  1501. // if compare = 0, then s->minval <= a <= p
  1502. // if compare > 0, then p < a <= s->maxval
  1503. if (compare <= 0)
  1504. s->maxval = s->guess;
  1505. else
  1506. s->minval = s->guess+1;
  1507. break;
  1508. }
  1509. case STB_probe_binary_largest: {
  1510. // if compare < 0, then s->minval <= a < p
  1511. // if compare = 0, then p <= a <= s->maxval
  1512. // if compare > 0, then p < a <= s->maxval
  1513. if (compare < 0)
  1514. s->maxval = s->guess-1;
  1515. else
  1516. s->minval = s->guess;
  1517. break;
  1518. }
  1519. }
  1520. return stb_probe_guess(s, result);
  1521. }
  1522. int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest)
  1523. {
  1524. int r;
  1525. if (maxv < minv) return minv-1;
  1526. s->minval = minv;
  1527. s->maxval = maxv;
  1528. s->mode = find_smallest ? STB_probe_binary_smallest : STB_probe_binary_largest;
  1529. stb_probe_guess(s, &r);
  1530. return r;
  1531. }
  1532. int stb_search_open(stb_search *s, int minv, int find_smallest)
  1533. {
  1534. int r;
  1535. s->step = 4;
  1536. s->minval = minv;
  1537. s->maxval = minv+s->step;
  1538. s->mode = find_smallest ? STB_probe_open_smallest : STB_probe_open_largest;
  1539. stb_probe_guess(s, &r);
  1540. return r;
  1541. }
  1542. #endif
  1543. //////////////////////////////////////////////////////////////////////////////
  1544. //
  1545. // String Processing
  1546. //
  1547. #define stb_prefixi(s,t) (0==stb_strnicmp((s),(t),strlen(t)))
  1548. enum stb_splitpath_flag
  1549. {
  1550. STB_PATH = 1,
  1551. STB_FILE = 2,
  1552. STB_EXT = 4,
  1553. STB_PATH_FILE = STB_PATH + STB_FILE,
  1554. STB_FILE_EXT = STB_FILE + STB_EXT,
  1555. STB_EXT_NO_PERIOD = 8,
  1556. };
  1557. STB_EXTERN char * stb_skipwhite(char *s);
  1558. STB_EXTERN char * stb_trimwhite(char *s);
  1559. STB_EXTERN char * stb_skipnewline(char *s);
  1560. STB_EXTERN char * stb_strncpy(char *s, char *t, int n);
  1561. STB_EXTERN char * stb_substr(char *t, int n);
  1562. STB_EXTERN char * stb_duplower(char *s);
  1563. STB_EXTERN void stb_tolower (char *s);
  1564. STB_EXTERN char * stb_strchr2 (char *s, char p1, char p2);
  1565. STB_EXTERN char * stb_strrchr2(char *s, char p1, char p2);
  1566. STB_EXTERN char * stb_strtok(char *output, char *src, char *delimit);
  1567. STB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit);
  1568. STB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed);
  1569. STB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace);
  1570. STB_EXTERN void stb_replaceinplace(char *s, char *find, char *replace);
  1571. STB_EXTERN char * stb_splitpath(char *output, char *src, int flag);
  1572. STB_EXTERN char * stb_splitpathdup(char *src, int flag);
  1573. STB_EXTERN char * stb_replacedir(char *output, char *src, char *dir);
  1574. STB_EXTERN char * stb_replaceext(char *output, char *src, char *ext);
  1575. STB_EXTERN void stb_fixpath(char *path);
  1576. STB_EXTERN char * stb_shorten_path_readable(char *path, int max_len);
  1577. STB_EXTERN int stb_suffix (char *s, char *t);
  1578. STB_EXTERN int stb_suffixi(char *s, char *t);
  1579. STB_EXTERN int stb_prefix (char *s, char *t);
  1580. STB_EXTERN char * stb_strichr(char *s, char t);
  1581. STB_EXTERN char * stb_stristr(char *s, char *t);
  1582. STB_EXTERN int stb_prefix_count(char *s, char *t);
  1583. STB_EXTERN char * stb_plural(int n); // "s" or ""
  1584. STB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n);
  1585. STB_EXTERN char **stb_tokens(char *src, char *delimit, int *count);
  1586. STB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out);
  1587. STB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out);
  1588. STB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count);
  1589. STB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count);
  1590. STB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count);
  1591. STB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count);
  1592. // with 'quoted', allow delimiters to appear inside quotation marks, and don't
  1593. // strip whitespace inside them (and we delete the quotation marks unless they
  1594. // appear back to back, in which case they're considered escaped)
  1595. #ifdef STB_DEFINE
  1596. size_t stb_strscpy(char *d, const char *s, size_t n)
  1597. {
  1598. size_t len = strlen(s);
  1599. if (len >= n) {
  1600. if (n) d[0] = 0;
  1601. return 0;
  1602. }
  1603. strcpy(d,s);
  1604. return len + 1;
  1605. }
  1606. char *stb_plural(int n)
  1607. {
  1608. return n == 1 ? "" : "s";
  1609. }
  1610. int stb_prefix(char *s, char *t)
  1611. {
  1612. while (*t)
  1613. if (*s++ != *t++)
  1614. return STB_FALSE;
  1615. return STB_TRUE;
  1616. }
  1617. int stb_prefix_count(char *s, char *t)
  1618. {
  1619. int c=0;
  1620. while (*t) {
  1621. if (*s++ != *t++)
  1622. break;
  1623. ++c;
  1624. }
  1625. return c;
  1626. }
  1627. int stb_suffix(char *s, char *t)
  1628. {
  1629. size_t n = strlen(s);
  1630. size_t m = strlen(t);
  1631. if (m <= n)
  1632. return 0 == strcmp(s+n-m, t);
  1633. else
  1634. return 0;
  1635. }
  1636. int stb_suffixi(char *s, char *t)
  1637. {
  1638. size_t n = strlen(s);
  1639. size_t m = strlen(t);
  1640. if (m <= n)
  1641. return 0 == stb_stricmp(s+n-m, t);
  1642. else
  1643. return 0;
  1644. }
  1645. // originally I was using this table so that I could create known sentinel
  1646. // values--e.g. change whitetable[0] to be true if I was scanning for whitespace,
  1647. // and false if I was scanning for nonwhite. I don't appear to be using that
  1648. // functionality anymore (I do for tokentable, though), so just replace it
  1649. // with isspace()
  1650. char *stb_skipwhite(char *s)
  1651. {
  1652. while (isspace((unsigned char) *s)) ++s;
  1653. return s;
  1654. }
  1655. char *stb_skipnewline(char *s)
  1656. {
  1657. if (s[0] == '\r' || s[0] == '\n') {
  1658. if (s[0]+s[1] == '\r' + '\n') ++s;
  1659. ++s;
  1660. }
  1661. return s;
  1662. }
  1663. char *stb_trimwhite(char *s)
  1664. {
  1665. int i,n;
  1666. s = stb_skipwhite(s);
  1667. n = (int) strlen(s);
  1668. for (i=n-1; i >= 0; --i)
  1669. if (!isspace(s[i]))
  1670. break;
  1671. s[i+1] = 0;
  1672. return s;
  1673. }
  1674. char *stb_strncpy(char *s, char *t, int n)
  1675. {
  1676. strncpy(s,t,n);
  1677. s[n-1] = 0;
  1678. return s;
  1679. }
  1680. char *stb_substr(char *t, int n)
  1681. {
  1682. char *a;
  1683. int z = (int) strlen(t);
  1684. if (z < n) n = z;
  1685. a = (char *) malloc(n+1);
  1686. strncpy(a,t,n);
  1687. a[n] = 0;
  1688. return a;
  1689. }
  1690. char *stb_duplower(char *s)
  1691. {
  1692. char *p = strdup(s), *q = p;
  1693. while (*q) {
  1694. *q = tolower(*q);
  1695. ++q;
  1696. }
  1697. return p;
  1698. }
  1699. void stb_tolower(char *s)
  1700. {
  1701. while (*s) {
  1702. *s = tolower(*s);
  1703. ++s;
  1704. }
  1705. }
  1706. char *stb_strchr2(char *s, char x, char y)
  1707. {
  1708. for(; *s; ++s)
  1709. if (*s == x || *s == y)
  1710. return s;
  1711. return NULL;
  1712. }
  1713. char *stb_strrchr2(char *s, char x, char y)
  1714. {
  1715. char *r = NULL;
  1716. for(; *s; ++s)
  1717. if (*s == x || *s == y)
  1718. r = s;
  1719. return r;
  1720. }
  1721. char *stb_strichr(char *s, char t)
  1722. {
  1723. if (tolower(t) == toupper(t))
  1724. return strchr(s,t);
  1725. return stb_strchr2(s, (char) tolower(t), (char) toupper(t));
  1726. }
  1727. char *stb_stristr(char *s, char *t)
  1728. {
  1729. size_t n = strlen(t);
  1730. char *z;
  1731. if (n==0) return s;
  1732. while ((z = stb_strichr(s, *t)) != NULL) {
  1733. if (0==stb_strnicmp(z, t, n))
  1734. return z;
  1735. s = z+1;
  1736. }
  1737. return NULL;
  1738. }
  1739. static char *stb_strtok_raw(char *output, char *src, char *delimit, int keep, int invert)
  1740. {
  1741. if (invert) {
  1742. while (*src && strchr(delimit, *src) != NULL) {
  1743. *output++ = *src++;
  1744. }
  1745. } else {
  1746. while (*src && strchr(delimit, *src) == NULL) {
  1747. *output++ = *src++;
  1748. }
  1749. }
  1750. *output = 0;
  1751. if (keep)
  1752. return src;
  1753. else
  1754. return *src ? src+1 : src;
  1755. }
  1756. char *stb_strtok(char *output, char *src, char *delimit)
  1757. {
  1758. return stb_strtok_raw(output, src, delimit, 0, 0);
  1759. }
  1760. char *stb_strtok_keep(char *output, char *src, char *delimit)
  1761. {
  1762. return stb_strtok_raw(output, src, delimit, 1, 0);
  1763. }
  1764. char *stb_strtok_invert(char *output, char *src, char *delimit)
  1765. {
  1766. return stb_strtok_raw(output, src, delimit, 1,1);
  1767. }
  1768. static char **stb_tokens_raw(char *src_, char *delimit, int *count,
  1769. int stripwhite, int allow_empty, char *start, char *end)
  1770. {
  1771. int nested = 0;
  1772. unsigned char *src = (unsigned char *) src_;
  1773. static char stb_tokentable[256]; // rely on static initializion to 0
  1774. static char stable[256],etable[256];
  1775. char *out;
  1776. char **result;
  1777. int num=0;
  1778. unsigned char *s;
  1779. s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 1;
  1780. if (start) {
  1781. s = (unsigned char *) start; while (*s) stable[*s++] = 1;
  1782. s = (unsigned char *) end; if (s) while (*s) stable[*s++] = 1;
  1783. s = (unsigned char *) end; if (s) while (*s) etable[*s++] = 1;
  1784. }
  1785. stable[0] = 1;
  1786. // two passes through: the first time, counting how many
  1787. s = (unsigned char *) src;
  1788. while (*s) {
  1789. // state: just found delimiter
  1790. // skip further delimiters
  1791. if (!allow_empty) {
  1792. stb_tokentable[0] = 0;
  1793. while (stb_tokentable[*s])
  1794. ++s;
  1795. if (!*s) break;
  1796. }
  1797. ++num;
  1798. // skip further non-delimiters
  1799. stb_tokentable[0] = 1;
  1800. if (stripwhite == 2) { // quoted strings
  1801. while (!stb_tokentable[*s]) {
  1802. if (*s != '"')
  1803. ++s;
  1804. else {
  1805. ++s;
  1806. if (*s == '"')
  1807. ++s; // "" -> ", not start a string
  1808. else {
  1809. // begin a string
  1810. while (*s) {
  1811. if (s[0] == '"') {
  1812. if (s[1] == '"') s += 2; // "" -> "
  1813. else { ++s; break; } // terminating "
  1814. } else
  1815. ++s;
  1816. }
  1817. }
  1818. }
  1819. }
  1820. } else
  1821. while (nested || !stb_tokentable[*s]) {
  1822. if (stable[*s]) {
  1823. if (!*s) break;
  1824. if (end ? etable[*s] : nested)
  1825. --nested;
  1826. else
  1827. ++nested;
  1828. }
  1829. ++s;
  1830. }
  1831. if (allow_empty) {
  1832. if (*s) ++s;
  1833. }
  1834. }
  1835. // now num has the actual count... malloc our output structure
  1836. // need space for all the strings: strings won't be any longer than
  1837. // original input, since for every '\0' there's at least one delimiter
  1838. result = (char **) malloc(sizeof(*result) * (num+1) + (s-src+1));
  1839. if (result == NULL) return result;
  1840. out = (char *) (result + (num+1));
  1841. // second pass: copy out the data
  1842. s = (unsigned char *) src;
  1843. num = 0;
  1844. nested = 0;
  1845. while (*s) {
  1846. char *last_nonwhite;
  1847. // state: just found delimiter
  1848. // skip further delimiters
  1849. if (!allow_empty) {
  1850. stb_tokentable[0] = 0;
  1851. if (stripwhite)
  1852. while (stb_tokentable[*s] || isspace(*s))
  1853. ++s;
  1854. else
  1855. while (stb_tokentable[*s])
  1856. ++s;
  1857. } else if (stripwhite) {
  1858. while (isspace(*s)) ++s;
  1859. }
  1860. if (!*s) break;
  1861. // we're past any leading delimiters and whitespace
  1862. result[num] = out;
  1863. ++num;
  1864. // copy non-delimiters
  1865. stb_tokentable[0] = 1;
  1866. last_nonwhite = out-1;
  1867. if (stripwhite == 2) {
  1868. while (!stb_tokentable[*s]) {
  1869. if (*s != '"') {
  1870. if (!isspace(*s)) last_nonwhite = out;
  1871. *out++ = *s++;
  1872. } else {
  1873. ++s;
  1874. if (*s == '"') {
  1875. if (!isspace(*s)) last_nonwhite = out;
  1876. *out++ = *s++; // "" -> ", not start string
  1877. } else {
  1878. // begin a quoted string
  1879. while (*s) {
  1880. if (s[0] == '"') {
  1881. if (s[1] == '"') { *out++ = *s; s += 2; }
  1882. else { ++s; break; } // terminating "
  1883. } else
  1884. *out++ = *s++;
  1885. }
  1886. last_nonwhite = out-1; // all in quotes counts as non-white
  1887. }
  1888. }
  1889. }
  1890. } else {
  1891. while (nested || !stb_tokentable[*s]) {
  1892. if (!isspace(*s)) last_nonwhite = out;
  1893. if (stable[*s]) {
  1894. if (!*s) break;
  1895. if (end ? etable[*s] : nested)
  1896. --nested;
  1897. else
  1898. ++nested;
  1899. }
  1900. *out++ = *s++;
  1901. }
  1902. }
  1903. if (stripwhite) // rewind to last non-whitespace char
  1904. out = last_nonwhite+1;
  1905. *out++ = '\0';
  1906. if (*s) ++s; // skip delimiter
  1907. }
  1908. s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 0;
  1909. if (start) {
  1910. s = (unsigned char *) start; while (*s) stable[*s++] = 1;
  1911. s = (unsigned char *) end; if (s) while (*s) stable[*s++] = 1;
  1912. s = (unsigned char *) end; if (s) while (*s) etable[*s++] = 1;
  1913. }
  1914. if (count != NULL) *count = num;
  1915. result[num] = 0;
  1916. return result;
  1917. }
  1918. char **stb_tokens(char *src, char *delimit, int *count)
  1919. {
  1920. return stb_tokens_raw(src,delimit,count,0,0,0,0);
  1921. }
  1922. char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out)
  1923. {
  1924. return stb_tokens_raw(src,delimit,count,0,0,nest_in,nest_out);
  1925. }
  1926. char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out)
  1927. {
  1928. return stb_tokens_raw(src,delimit,count,0,1,nest_in,nest_out);
  1929. }
  1930. char **stb_tokens_allowempty(char *src, char *delimit, int *count)
  1931. {
  1932. return stb_tokens_raw(src,delimit,count,0,1,0,0);
  1933. }
  1934. char **stb_tokens_stripwhite(char *src, char *delimit, int *count)
  1935. {
  1936. return stb_tokens_raw(src,delimit,count,1,1,0,0);
  1937. }
  1938. char **stb_tokens_quoted(char *src, char *delimit, int *count)
  1939. {
  1940. return stb_tokens_raw(src,delimit,count,2,1,0,0);
  1941. }
  1942. char *stb_dupreplace(char *src, char *find, char *replace)
  1943. {
  1944. size_t len_find = strlen(find);
  1945. size_t len_replace = strlen(replace);
  1946. int count = 0;
  1947. char *s,*p,*q;
  1948. s = strstr(src, find);
  1949. if (s == NULL) return strdup(src);
  1950. do {
  1951. ++count;
  1952. s = strstr(s + len_find, find);
  1953. } while (s != NULL);
  1954. p = (char *) malloc(strlen(src) + count * (len_replace - len_find) + 1);
  1955. if (p == NULL) return p;
  1956. q = p;
  1957. s = src;
  1958. for (;;) {
  1959. char *t = strstr(s, find);
  1960. if (t == NULL) {
  1961. strcpy(q,s);
  1962. assert(strlen(p) == strlen(src) + count*(len_replace-len_find));
  1963. return p;
  1964. }
  1965. memcpy(q, s, t-s);
  1966. q += t-s;
  1967. memcpy(q, replace, len_replace);
  1968. q += len_replace;
  1969. s = t + len_find;
  1970. }
  1971. }
  1972. void stb_replaceinplace(char *src, char *find, char *replace)
  1973. {
  1974. size_t len_find = strlen(find);
  1975. size_t len_replace = strlen(replace);
  1976. int delta;
  1977. char *s,*p,*q;
  1978. delta = len_replace - len_find;
  1979. assert(delta <= 0);
  1980. if (delta > 0) return;
  1981. p = strstr(src, find);
  1982. if (p == NULL) return;
  1983. s = q = p;
  1984. while (*s) {
  1985. memcpy(q, replace, len_replace);
  1986. p += len_find;
  1987. q += len_replace;
  1988. s = strstr(p, find);
  1989. if (s == NULL) s = p + strlen(p);
  1990. memmove(q, p, s-p);
  1991. q += s-p;
  1992. p = s;
  1993. }
  1994. *q = 0;
  1995. }
  1996. void stb_fixpath(char *path)
  1997. {
  1998. for(; *path; ++path)
  1999. if (*path == '\\')
  2000. *path = '/';
  2001. }
  2002. void stb__add_section(char *buffer, char *data, int curlen, int newlen)
  2003. {
  2004. if (newlen < curlen) {
  2005. int z1 = newlen >> 1, z2 = newlen-z1;
  2006. memcpy(buffer, data, z1-1);
  2007. buffer[z1-1] = '.';
  2008. buffer[z1-0] = '.';
  2009. memcpy(buffer+z1+1, data+curlen-z2+1, z2-1);
  2010. } else
  2011. memcpy(buffer, data, curlen);
  2012. }
  2013. char * stb_shorten_path_readable(char *path, int len)
  2014. {
  2015. static char buffer[1024];
  2016. int n = strlen(path),n1,n2,r1,r2;
  2017. char *s;
  2018. if (n <= len) return path;
  2019. if (len > 1024) return path;
  2020. s = stb_strrchr2(path, '/', '\\');
  2021. if (s) {
  2022. n1 = s - path + 1;
  2023. n2 = n - n1;
  2024. ++s;
  2025. } else {
  2026. n1 = 0;
  2027. n2 = n;
  2028. s = path;
  2029. }
  2030. // now we need to reduce r1 and r2 so that they fit in len
  2031. if (n1 < len>>1) {
  2032. r1 = n1;
  2033. r2 = len - r1;
  2034. } else if (n2 < len >> 1) {
  2035. r2 = n2;
  2036. r1 = len - r2;
  2037. } else {
  2038. r1 = n1 * len / n;
  2039. r2 = n2 * len / n;
  2040. if (r1 < len>>2) r1 = len>>2, r2 = len-r1;
  2041. if (r2 < len>>2) r2 = len>>2, r1 = len-r2;
  2042. }
  2043. assert(r1 <= n1 && r2 <= n2);
  2044. if (n1)
  2045. stb__add_section(buffer, path, n1, r1);
  2046. stb__add_section(buffer+r1, s, n2, r2);
  2047. buffer[len] = 0;
  2048. return buffer;
  2049. }
  2050. static char *stb__splitpath_raw(char *buffer, char *path, int flag)
  2051. {
  2052. int len=0,x,y, n = (int) strlen(path), f1,f2;
  2053. char *s = stb_strrchr2(path, '/', '\\');
  2054. char *t = strrchr(path, '.');
  2055. if (s && t && t < s) t = NULL;
  2056. if (s) ++s;
  2057. if (flag == STB_EXT_NO_PERIOD)
  2058. flag |= STB_EXT;
  2059. if (!(flag & (STB_PATH | STB_FILE | STB_EXT))) return NULL;
  2060. f1 = s == NULL ? 0 : s-path; // start of filename
  2061. f2 = t == NULL ? n : t-path; // just past end of filename
  2062. if (flag & STB_PATH) {
  2063. x = 0; if (f1 == 0 && flag == STB_PATH) len=2;
  2064. } else if (flag & STB_FILE) {
  2065. x = f1;
  2066. } else {
  2067. x = f2;
  2068. if (flag & STB_EXT_NO_PERIOD)
  2069. if (buffer[x] == '.')
  2070. ++x;
  2071. }
  2072. if (flag & STB_EXT)
  2073. y = n;
  2074. else if (flag & STB_FILE)
  2075. y = f2;
  2076. else
  2077. y = f1;
  2078. if (buffer == NULL) {
  2079. buffer = (char *) malloc(y-x + len + 1);
  2080. if (!buffer) return NULL;
  2081. }
  2082. if (len) { strcpy(buffer, "./"); return buffer; }
  2083. strncpy(buffer, path+x, y-x);
  2084. buffer[y-x] = 0;
  2085. return buffer;
  2086. }
  2087. char *stb_splitpath(char *output, char *src, int flag)
  2088. {
  2089. return stb__splitpath_raw(output, src, flag);
  2090. }
  2091. char *stb_splitpathdup(char *src, int flag)
  2092. {
  2093. return stb__splitpath_raw(NULL, src, flag);
  2094. }
  2095. char *stb_replacedir(char *output, char *src, char *dir)
  2096. {
  2097. char buffer[4096];
  2098. stb_splitpath(buffer, src, STB_FILE | STB_EXT);
  2099. if (dir)
  2100. sprintf(output, "%s/%s", dir, buffer);
  2101. else
  2102. strcpy(output, buffer);
  2103. return output;
  2104. }
  2105. char *stb_replaceext(char *output, char *src, char *ext)
  2106. {
  2107. char buffer[4096];
  2108. stb_splitpath(buffer, src, STB_PATH | STB_FILE);
  2109. if (ext)
  2110. sprintf(output, "%s.%s", buffer, ext[0] == '.' ? ext+1 : ext);
  2111. else
  2112. strcpy(output, buffer);
  2113. return output;
  2114. }
  2115. #endif
  2116. //////////////////////////////////////////////////////////////////////////////
  2117. //
  2118. // stb_alloc - hierarchical allocator
  2119. //
  2120. // inspired by http://swapped.cc/halloc
  2121. //
  2122. //
  2123. // When you alloc a given block through stb_alloc, you have these choices:
  2124. //
  2125. // 1. does it have a parent?
  2126. // 2. can it have children?
  2127. // 3. can it be freed directly?
  2128. // 4. is it transferrable?
  2129. // 5. what is its alignment?
  2130. //
  2131. // Here are interesting combinations of those:
  2132. //
  2133. // children free transfer alignment
  2134. // arena Y Y N n/a
  2135. // no-overhead, chunked N N N normal
  2136. // string pool alloc N N N 1
  2137. // parent-ptr, chunked Y N N normal
  2138. // low-overhead, unchunked N Y Y normal
  2139. // general purpose alloc Y Y Y normal
  2140. //
  2141. // Unchunked allocations will probably return 16-aligned pointers. If
  2142. // we 16-align the results, we have room for 4 pointers. For smaller
  2143. // allocations that allow finer alignment, we can reduce the pointers.
  2144. //
  2145. // The strategy is that given a pointer, assuming it has a header (only
  2146. // the no-overhead allocations have no header), we can determine the
  2147. // type of the header fields, and the number of them, by stepping backwards
  2148. // through memory and looking at the tags in the bottom bits.
  2149. //
  2150. // Implementation strategy:
  2151. // chunked allocations come from the middle of chunks, and can't
  2152. // be freed. thefore they do not need to be on a sibling chain.
  2153. // they may need child pointers if they have children.
  2154. //
  2155. // chunked, with-children
  2156. // void *parent;
  2157. //
  2158. // unchunked, no-children -- reduced storage
  2159. // void *next_sibling;
  2160. // void *prev_sibling_nextp;
  2161. //
  2162. // unchunked, general
  2163. // void *first_child;
  2164. // void *next_sibling;
  2165. // void *prev_sibling_nextp;
  2166. // void *chunks;
  2167. //
  2168. // so, if we code each of these fields with different bit patterns
  2169. // (actually same one for next/prev/child), then we can identify which
  2170. // each one is from the last field.
  2171. STB_EXTERN void stb_free(void *p);
  2172. STB_EXTERN void *stb_malloc_global(size_t size);
  2173. STB_EXTERN void *stb_malloc(void *context, size_t size);
  2174. STB_EXTERN void *stb_malloc_nofree(void *context, size_t size);
  2175. STB_EXTERN void *stb_malloc_leaf(void *context, size_t size);
  2176. STB_EXTERN void *stb_malloc_raw(void *context, size_t size);
  2177. STB_EXTERN void *stb_realloc(void *ptr, size_t newsize);
  2178. STB_EXTERN void stb_reassign(void *new_context, void *ptr);
  2179. STB_EXTERN void stb_malloc_validate(void *p, void *parent);
  2180. extern int stb_alloc_chunk_size ;
  2181. extern int stb_alloc_count_free ;
  2182. extern int stb_alloc_count_alloc;
  2183. extern int stb_alloc_alignment ;
  2184. #ifdef STB_DEFINE
  2185. int stb_alloc_chunk_size = 65536;
  2186. int stb_alloc_count_free = 0;
  2187. int stb_alloc_count_alloc = 0;
  2188. int stb_alloc_alignment = -16;
  2189. typedef struct stb__chunk
  2190. {
  2191. struct stb__chunk *next;
  2192. int data_left;
  2193. int alloc;
  2194. } stb__chunk;
  2195. typedef struct
  2196. {
  2197. void * next;
  2198. void ** prevn;
  2199. } stb__nochildren;
  2200. typedef struct
  2201. {
  2202. void ** prevn;
  2203. void * child;
  2204. void * next;
  2205. stb__chunk *chunks;
  2206. } stb__alloc;
  2207. typedef struct
  2208. {
  2209. stb__alloc *parent;
  2210. } stb__chunked;
  2211. #define STB__PARENT 1
  2212. #define STB__CHUNKS 2
  2213. typedef enum
  2214. {
  2215. STB__nochildren = 0,
  2216. STB__chunked = STB__PARENT,
  2217. STB__alloc = STB__CHUNKS,
  2218. STB__chunk_raw = 4,
  2219. } stb__alloc_type;
  2220. // these functions set the bottom bits of a pointer efficiently
  2221. #define STB__DECODE(x,v) ((void *) ((char *) (x) - (v)))
  2222. #define STB__ENCODE(x,v) ((void *) ((char *) (x) + (v)))
  2223. #define stb__parent(z) (stb__alloc *) STB__DECODE((z)->parent, STB__PARENT)
  2224. #define stb__chunks(z) (stb__chunk *) STB__DECODE((z)->chunks, STB__CHUNKS)
  2225. #define stb__setparent(z,p) (z)->parent = (stb__alloc *) STB__ENCODE((p), STB__PARENT)
  2226. #define stb__setchunks(z,c) (z)->chunks = (stb__chunk *) STB__ENCODE((c), STB__CHUNKS)
  2227. static stb__alloc stb__alloc_global =
  2228. {
  2229. NULL,
  2230. NULL,
  2231. NULL,
  2232. (stb__chunk *) STB__ENCODE(NULL, STB__CHUNKS)
  2233. };
  2234. static stb__alloc_type stb__identify(void *p)
  2235. {
  2236. void **q = (void **) p;
  2237. return (stb__alloc_type) ((stb_uinta) q[-1] & 3);
  2238. }
  2239. static void *** stb__prevn(void *p)
  2240. {
  2241. if (stb__identify(p) == STB__alloc) {
  2242. stb__alloc *s = (stb__alloc *) p - 1;
  2243. return &s->prevn;
  2244. } else {
  2245. stb__nochildren *s = (stb__nochildren *) p - 1;
  2246. return &s->prevn;
  2247. }
  2248. }
  2249. void stb_free(void *p)
  2250. {
  2251. if (p == NULL) return;
  2252. // count frees so that unit tests can see what's happening
  2253. ++stb_alloc_count_free;
  2254. switch(stb__identify(p)) {
  2255. case STB__chunked:
  2256. // freeing a chunked-block with children does nothing;
  2257. // they only get freed when the parent does
  2258. // surely this is wrong, and it should free them immediately?
  2259. // otherwise how are they getting put on the right chain?
  2260. return;
  2261. case STB__nochildren: {
  2262. stb__nochildren *s = (stb__nochildren *) p - 1;
  2263. // unlink from sibling chain
  2264. *(s->prevn) = s->next;
  2265. if (s->next)
  2266. *stb__prevn(s->next) = s->prevn;
  2267. free(s);
  2268. return;
  2269. }
  2270. case STB__alloc: {
  2271. stb__alloc *s = (stb__alloc *) p - 1;
  2272. stb__chunk *c, *n;
  2273. void *q;
  2274. // unlink from sibling chain, if any
  2275. *(s->prevn) = s->next;
  2276. if (s->next)
  2277. *stb__prevn(s->next) = s->prevn;
  2278. // first free chunks
  2279. c = (stb__chunk *) stb__chunks(s);
  2280. while (c != NULL) {
  2281. n = c->next;
  2282. stb_alloc_count_free += c->alloc;
  2283. free(c);
  2284. c = n;
  2285. }
  2286. // validating
  2287. stb__setchunks(s,NULL);
  2288. s->prevn = NULL;
  2289. s->next = NULL;
  2290. // now free children
  2291. while ((q = s->child) != NULL) {
  2292. stb_free(q);
  2293. }
  2294. // now free self
  2295. free(s);
  2296. return;
  2297. }
  2298. default:
  2299. assert(0); /* NOTREACHED */
  2300. }
  2301. }
  2302. void stb_malloc_validate(void *p, void *parent)
  2303. {
  2304. if (p == NULL) return;
  2305. switch(stb__identify(p)) {
  2306. case STB__chunked:
  2307. return;
  2308. case STB__nochildren: {
  2309. stb__nochildren *n = (stb__nochildren *) p - 1;
  2310. if (n->prevn)
  2311. assert(*n->prevn == p);
  2312. if (n->next) {
  2313. assert(*stb__prevn(n->next) == &n->next);
  2314. stb_malloc_validate(n, parent);
  2315. }
  2316. return;
  2317. }
  2318. case STB__alloc: {
  2319. stb__alloc *s = (stb__alloc *) p - 1;
  2320. if (s->prevn)
  2321. assert(*s->prevn == p);
  2322. if (s->child) {
  2323. assert(*stb__prevn(s->child) == &s->child);
  2324. stb_malloc_validate(s->child, p);
  2325. }
  2326. if (s->next) {
  2327. assert(*stb__prevn(s->next) == &s->next);
  2328. stb_malloc_validate(s->next, parent);
  2329. }
  2330. return;
  2331. }
  2332. default:
  2333. assert(0); /* NOTREACHED */
  2334. }
  2335. }
  2336. static void * stb__try_chunk(stb__chunk *c, int size, int align, int pre_align)
  2337. {
  2338. char *memblock = (char *) (c+1), *q;
  2339. stb_inta iq;
  2340. int start_offset;
  2341. // we going to allocate at the end of the chunk, not the start. confusing,
  2342. // but it means we don't need both a 'limit' and a 'cur', just a 'cur'.
  2343. // the block ends at: p + c->data_left
  2344. // then we move back by size
  2345. start_offset = c->data_left - size;
  2346. // now we need to check the alignment of that
  2347. q = memblock + start_offset;
  2348. iq = (stb_inta) q;
  2349. assert(sizeof(q) == sizeof(iq));
  2350. // suppose align = 2
  2351. // then we need to retreat iq far enough that (iq & (2-1)) == 0
  2352. // to get (iq & (align-1)) = 0 requires subtracting (iq & (align-1))
  2353. start_offset -= iq & (align-1);
  2354. assert(((stb_uinta) (memblock+start_offset) & (align-1)) == 0);
  2355. // now, if that + pre_align works, go for it!
  2356. start_offset -= pre_align;
  2357. if (start_offset >= 0) {
  2358. c->data_left = start_offset;
  2359. return memblock + start_offset;
  2360. }
  2361. return NULL;
  2362. }
  2363. static void stb__sort_chunks(stb__alloc *src)
  2364. {
  2365. // of the first two chunks, put the chunk with more data left in it first
  2366. stb__chunk *c = stb__chunks(src), *d;
  2367. if (c == NULL) return;
  2368. d = c->next;
  2369. if (d == NULL) return;
  2370. if (c->data_left > d->data_left) return;
  2371. c->next = d->next;
  2372. d->next = c;
  2373. stb__setchunks(src, d);
  2374. }
  2375. static void * stb__alloc_chunk(stb__alloc *src, int size, int align, int pre_align)
  2376. {
  2377. void *p;
  2378. stb__chunk *c = stb__chunks(src);
  2379. if (c && size <= stb_alloc_chunk_size) {
  2380. p = stb__try_chunk(c, size, align, pre_align);
  2381. if (p) { ++c->alloc; return p; }
  2382. // try a second chunk to reduce wastage
  2383. if (c->next) {
  2384. p = stb__try_chunk(c->next, size, align, pre_align);
  2385. if (p) { ++c->alloc; return p; }
  2386. // put the bigger chunk first, since the second will get buried
  2387. // the upshot of this is that, until it gets allocated from, chunk #2
  2388. // is always the largest remaining chunk. (could formalize
  2389. // this with a heap!)
  2390. stb__sort_chunks(src);
  2391. c = stb__chunks(src);
  2392. }
  2393. }
  2394. // allocate a new chunk
  2395. {
  2396. stb__chunk *n;
  2397. int chunk_size = stb_alloc_chunk_size;
  2398. // we're going to allocate a new chunk to put this in
  2399. if (size > chunk_size)
  2400. chunk_size = size;
  2401. assert(sizeof(*n) + pre_align <= 16);
  2402. // loop trying to allocate a large enough chunk
  2403. // the loop is because the alignment may cause problems if it's big...
  2404. // and we don't know what our chunk alignment is going to be
  2405. while (1) {
  2406. n = (stb__chunk *) malloc(16 + chunk_size);
  2407. if (n == NULL) return NULL;
  2408. n->data_left = chunk_size - sizeof(*n);
  2409. p = stb__try_chunk(n, size, align, pre_align);
  2410. if (p != NULL) {
  2411. n->next = c;
  2412. stb__setchunks(src, n);
  2413. // if we just used up the whole block immediately,
  2414. // move the following chunk up
  2415. n->alloc = 1;
  2416. if (size == chunk_size)
  2417. stb__sort_chunks(src);
  2418. return p;
  2419. }
  2420. free(n);
  2421. chunk_size += 16+align;
  2422. }
  2423. }
  2424. }
  2425. static stb__alloc * stb__get_context(void *context)
  2426. {
  2427. if (context == NULL) {
  2428. return &stb__alloc_global;
  2429. } else {
  2430. int u = stb__identify(context);
  2431. // if context is chunked, grab parent
  2432. if (u == STB__chunked) {
  2433. stb__chunked *s = (stb__chunked *) context - 1;
  2434. return stb__parent(s);
  2435. } else {
  2436. return (stb__alloc *) context - 1;
  2437. }
  2438. }
  2439. }
  2440. static void stb__insert_alloc(stb__alloc *src, stb__alloc *s)
  2441. {
  2442. s->prevn = &src->child;
  2443. s->next = src->child;
  2444. src->child = s+1;
  2445. if (s->next)
  2446. *stb__prevn(s->next) = &s->next;
  2447. }
  2448. static void stb__insert_nochild(stb__alloc *src, stb__nochildren *s)
  2449. {
  2450. s->prevn = &src->child;
  2451. s->next = src->child;
  2452. src->child = s+1;
  2453. if (s->next)
  2454. *stb__prevn(s->next) = &s->next;
  2455. }
  2456. static void * malloc_base(void *context, size_t size, stb__alloc_type t, int align)
  2457. {
  2458. void *p;
  2459. stb__alloc *src = stb__get_context(context);
  2460. if (align <= 0) {
  2461. // compute worst-case C packed alignment
  2462. // e.g. a 24-byte struct is 8-aligned
  2463. int align_proposed = 1 << stb_lowbit8(size);
  2464. if (align_proposed < 0)
  2465. align_proposed = 4;
  2466. if (align_proposed == 0) {
  2467. if (size == 0)
  2468. align_proposed = 1;
  2469. else
  2470. align_proposed = 256;
  2471. }
  2472. // a negative alignment means 'don't align any larger
  2473. // than this'; so -16 means we align 1,2,4,8, or 16
  2474. if (align < 0) {
  2475. if (align_proposed > -align)
  2476. align_proposed = -align;
  2477. }
  2478. align = align_proposed;
  2479. }
  2480. assert(stb_is_pow2(align));
  2481. // don't cause misalignment when allocating nochildren
  2482. if (t == STB__nochildren && align > 8)
  2483. t = STB__alloc;
  2484. switch (t) {
  2485. case STB__alloc: {
  2486. stb__alloc *s = (stb__alloc *) malloc(size + sizeof(*s));
  2487. if (s == NULL) return NULL;
  2488. p = s+1;
  2489. s->child = NULL;
  2490. stb__insert_alloc(src, s);
  2491. stb__setchunks(s,NULL);
  2492. break;
  2493. }
  2494. case STB__nochildren: {
  2495. stb__nochildren *s = (stb__nochildren *) malloc(size + sizeof(*s));
  2496. if (s == NULL) return NULL;
  2497. p = s+1;
  2498. stb__insert_nochild(src, s);
  2499. break;
  2500. }
  2501. case STB__chunk_raw: {
  2502. p = stb__alloc_chunk(src, size, align, 0);
  2503. if (p == NULL) return NULL;
  2504. break;
  2505. }
  2506. case STB__chunked: {
  2507. stb__chunked *s;
  2508. if (align < sizeof(stb_uintptr)) align = sizeof(stb_uintptr);
  2509. s = (stb__chunked *) stb__alloc_chunk(src, size, align, sizeof(*s));
  2510. if (s == NULL) return NULL;
  2511. stb__setparent(s, src);
  2512. p = s+1;
  2513. break;
  2514. }
  2515. default: p = NULL; assert(0); /* NOTREACHED */
  2516. }
  2517. ++stb_alloc_count_alloc;
  2518. return p;
  2519. }
  2520. void *stb_malloc_global(size_t size)
  2521. {
  2522. return malloc_base(NULL, size, STB__alloc, stb_alloc_alignment);
  2523. }
  2524. void *stb_malloc(void *context, size_t size)
  2525. {
  2526. return malloc_base(context, size, STB__alloc, stb_alloc_alignment);
  2527. }
  2528. void *stb_malloc_nofree(void *context, size_t size)
  2529. {
  2530. return malloc_base(context, size, STB__chunked, stb_alloc_alignment);
  2531. }
  2532. void *stb_malloc_leaf(void *context, size_t size)
  2533. {
  2534. return malloc_base(context, size, STB__nochildren, stb_alloc_alignment);
  2535. }
  2536. void *stb_malloc_raw(void *context, size_t size)
  2537. {
  2538. return malloc_base(context, size, STB__chunk_raw, stb_alloc_alignment);
  2539. }
  2540. char *stb_malloc_string(void *context, size_t size)
  2541. {
  2542. return (char *) malloc_base(context, size, STB__chunk_raw, 1);
  2543. }
  2544. void *stb_realloc(void *ptr, size_t newsize)
  2545. {
  2546. stb__alloc_type t;
  2547. if (ptr == NULL) return stb_malloc(NULL, newsize);
  2548. if (newsize == 0) { stb_free(ptr); return NULL; }
  2549. t = stb__identify(ptr);
  2550. assert(t == STB__alloc || t == STB__nochildren);
  2551. if (t == STB__alloc) {
  2552. stb__alloc *s = (stb__alloc *) ptr - 1;
  2553. s = (stb__alloc *) realloc(s, newsize + sizeof(*s));
  2554. if (s == NULL) return NULL;
  2555. ptr = s+1;
  2556. // update pointers
  2557. (*s->prevn) = ptr;
  2558. if (s->next)
  2559. *stb__prevn(s->next) = &s->next;
  2560. if (s->child)
  2561. *stb__prevn(s->child) = &s->child;
  2562. return ptr;
  2563. } else {
  2564. stb__nochildren *s = (stb__nochildren *) ptr - 1;
  2565. s = (stb__nochildren *) realloc(ptr, newsize + sizeof(s));
  2566. if (s == NULL) return NULL;
  2567. // update pointers
  2568. (*s->prevn) = s+1;
  2569. if (s->next)
  2570. *stb__prevn(s->next) = &s->next;
  2571. return s+1;
  2572. }
  2573. }
  2574. void *stb_realloc_c(void *context, void *ptr, size_t newsize)
  2575. {
  2576. if (ptr == NULL) return stb_malloc(context, newsize);
  2577. if (newsize == 0) { stb_free(ptr); return NULL; }
  2578. // @TODO: verify you haven't changed contexts
  2579. return stb_realloc(ptr, newsize);
  2580. }
  2581. void stb_reassign(void *new_context, void *ptr)
  2582. {
  2583. stb__alloc *src = stb__get_context(new_context);
  2584. stb__alloc_type t = stb__identify(ptr);
  2585. assert(t == STB__alloc || t == STB__nochildren);
  2586. if (t == STB__alloc) {
  2587. stb__alloc *s = (stb__alloc *) ptr - 1;
  2588. // unlink from old
  2589. *(s->prevn) = s->next;
  2590. if (s->next)
  2591. *stb__prevn(s->next) = s->prevn;
  2592. stb__insert_alloc(src, s);
  2593. } else {
  2594. stb__nochildren *s = (stb__nochildren *) ptr - 1;
  2595. // unlink from old
  2596. *(s->prevn) = s->next;
  2597. if (s->next)
  2598. *stb__prevn(s->next) = s->prevn;
  2599. stb__insert_nochild(src, s);
  2600. }
  2601. }
  2602. #endif
  2603. //////////////////////////////////////////////////////////////////////////////
  2604. //
  2605. // stb_arr
  2606. //
  2607. // An stb_arr is directly useable as a pointer (use the actual type in your
  2608. // definition), but when it resizes, it returns a new pointer and you can't
  2609. // use the old one, so you have to be careful to copy-in-out as necessary.
  2610. //
  2611. // Use a NULL pointer as a 0-length array.
  2612. //
  2613. // float *my_array = NULL, *temp;
  2614. //
  2615. // // add elements on the end one at a time
  2616. // stb_arr_push(my_array, 0.0f);
  2617. // stb_arr_push(my_array, 1.0f);
  2618. // stb_arr_push(my_array, 2.0f);
  2619. //
  2620. // assert(my_array[1] == 2.0f);
  2621. //
  2622. // // add an uninitialized element at the end, then assign it
  2623. // *stb_arr_add(my_array) = 3.0f;
  2624. //
  2625. // // add three uninitialized elements at the end
  2626. // temp = stb_arr_addn(my_array,3);
  2627. // temp[0] = 4.0f;
  2628. // temp[1] = 5.0f;
  2629. // temp[2] = 6.0f;
  2630. //
  2631. // assert(my_array[5] == 5.0f);
  2632. //
  2633. // // remove the last one
  2634. // stb_arr_pop(my_array);
  2635. //
  2636. // assert(stb_arr_len(my_array) == 6);
  2637. #ifdef STB_MALLOC_WRAPPER
  2638. #define STB__PARAMS , char *file, int line
  2639. #define STB__ARGS , file, line
  2640. #else
  2641. #define STB__PARAMS
  2642. #define STB__ARGS
  2643. #endif
  2644. // calling this function allocates an empty stb_arr attached to p
  2645. // (whereas NULL isn't attached to anything)
  2646. STB_EXTERN void stb_arr_malloc(void **target, void *context);
  2647. // call this function with a non-NULL value to have all successive
  2648. // stbs that are created be attached to the associated parent. Note
  2649. // that once a given stb_arr is non-empty, it stays attached to its
  2650. // current parent, even if you call this function again.
  2651. // it turns the previous value, so you can restore it
  2652. STB_EXTERN void* stb_arr_malloc_parent(void *p);
  2653. // simple functions written on top of other functions
  2654. #define stb_arr_empty(a) ( stb_arr_len(a) == 0 )
  2655. #define stb_arr_add(a) ( stb_arr_addn((a),1) )
  2656. #define stb_arr_push(a,v) ( *stb_arr_add(a)=(v) )
  2657. typedef struct
  2658. {
  2659. int len, limit;
  2660. int stb_malloc;
  2661. unsigned int signature;
  2662. } stb__arr;
  2663. #define stb_arr_signature 0x51bada7b // ends with 0123 in decimal
  2664. // access the header block stored before the data
  2665. #define stb_arrhead(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1)
  2666. #define stb_arrhead2(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1)
  2667. #ifdef STB_DEBUG
  2668. #define stb_arr_check(a) assert(!a || stb_arrhead(a)->signature == stb_arr_signature)
  2669. #define stb_arr_check2(a) assert(!a || stb_arrhead2(a)->signature == stb_arr_signature)
  2670. #else
  2671. #define stb_arr_check(a) ((void) 0)
  2672. #define stb_arr_check2(a) ((void) 0)
  2673. #endif
  2674. // ARRAY LENGTH
  2675. // get the array length; special case if pointer is NULL
  2676. #define stb_arr_len(a) (a ? stb_arrhead(a)->len : 0)
  2677. #define stb_arr_len2(a) ((stb__arr *) (a) ? stb_arrhead2(a)->len : 0)
  2678. #define stb_arr_lastn(a) (stb_arr_len(a)-1)
  2679. // check whether a given index is valid -- tests 0 <= i < stb_arr_len(a)
  2680. #define stb_arr_valid(a,i) (a ? (int) (i) < stb_arrhead(a)->len : 0)
  2681. // change the array length so is is exactly N entries long, creating
  2682. // uninitialized entries as needed
  2683. #define stb_arr_setlen(a,n) \
  2684. (stb__arr_setlen((void **) &(a), sizeof(a[0]), (n)))
  2685. // change the array length so that N is a valid index (that is, so
  2686. // it is at least N entries long), creating uninitialized entries as needed
  2687. #define stb_arr_makevalid(a,n) \
  2688. (stb_arr_len(a) < (n)+1 ? stb_arr_setlen(a,(n)+1),(a) : (a))
  2689. // remove the last element of the array, returning it
  2690. #define stb_arr_pop(a) ((stb_arr_check(a), (a))[--stb_arrhead(a)->len])
  2691. // access the last element in the array
  2692. #define stb_arr_last(a) ((stb_arr_check(a), (a))[stb_arr_len(a)-1])
  2693. // is iterator at end of list?
  2694. #define stb_arr_end(a,i) ((i) >= &(a)[stb_arr_len(a)])
  2695. // (internal) change the allocated length of the array
  2696. #define stb_arr__grow(a,n) (stb_arr_check(a), stb_arrhead(a)->len += (n))
  2697. // add N new unitialized elements to the end of the array
  2698. #define stb_arr__addn(a,n) /*lint --e(826)*/ \
  2699. ((stb_arr_len(a)+(n) > stb_arrcurmax(a)) \
  2700. ? (stb__arr_addlen((void **) &(a),sizeof(*a),(n)),0) \
  2701. : ((stb_arr__grow(a,n), 0)))
  2702. // add N new unitialized elements to the end of the array, and return
  2703. // a pointer to the first new one
  2704. #define stb_arr_addn(a,n) (stb_arr__addn((a),n),(a)+stb_arr_len(a)-(n))
  2705. // add N new uninitialized elements starting at index 'i'
  2706. #define stb_arr_insertn(a,i,n) (stb__arr_insertn((void **) &(a), sizeof(*a), i, n))
  2707. // insert an element at i
  2708. #define stb_arr_insert(a,i,v) (stb__arr_insertn((void **) &(a), sizeof(*a), i, 1), ((a)[i] = v))
  2709. // delete N elements from the middle starting at index 'i'
  2710. #define stb_arr_deleten(a,i,n) (stb__arr_deleten((void **) &(a), sizeof(*a), i, n))
  2711. // delete the i'th element
  2712. #define stb_arr_delete(a,i) stb_arr_deleten(a,i,1)
  2713. // delete the i'th element, swapping down from the end
  2714. #define stb_arr_fastdelete(a,i) \
  2715. (stb_swap(&a[i], &a[stb_arrhead(a)->len-1], sizeof(*a)), stb_arr_pop(a))
  2716. // ARRAY STORAGE
  2717. // get the array maximum storage; special case if NULL
  2718. #define stb_arrcurmax(a) (a ? stb_arrhead(a)->limit : 0)
  2719. #define stb_arrcurmax2(a) (a ? stb_arrhead2(a)->limit : 0)
  2720. // set the maxlength of the array to n in anticipation of further growth
  2721. #define stb_arr_setsize(a,n) (stb_arr_check(a), stb__arr_setsize((void **) &(a),sizeof((a)[0]),n))
  2722. // make sure maxlength is large enough for at least N new allocations
  2723. #define stb_arr_atleast(a,n) (stb_arr_len(a)+(n) > stb_arrcurmax(a) \
  2724. ? stb_arr_setsize((a), (n)) : 0)
  2725. // make a copy of a given array (copies contents via 'memcpy'!)
  2726. #define stb_arr_copy(a) stb__arr_copy(a, sizeof((a)[0]))
  2727. // compute the storage needed to store all the elements of the array
  2728. #define stb_arr_storage(a) (stb_arr_len(a) * sizeof((a)[0]))
  2729. #define stb_arr_for(v,arr) for((v)=(arr); (v) < (arr)+stb_arr_len(arr); ++(v))
  2730. // IMPLEMENTATION
  2731. STB_EXTERN void stb_arr_free_(void **p);
  2732. STB_EXTERN void *stb__arr_copy_(void *p, int elem_size);
  2733. STB_EXTERN void stb__arr_setsize_(void **p, int size, int limit STB__PARAMS);
  2734. STB_EXTERN void stb__arr_setlen_(void **p, int size, int newlen STB__PARAMS);
  2735. STB_EXTERN void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS);
  2736. STB_EXTERN void stb__arr_deleten_(void **p, int size, int loc, int n STB__PARAMS);
  2737. STB_EXTERN void stb__arr_insertn_(void **p, int size, int loc, int n STB__PARAMS);
  2738. #define stb_arr_free(p) stb_arr_free_((void **) &(p))
  2739. #define stb__arr_copy stb__arr_copy_
  2740. #ifndef STB_MALLOC_WRAPPER
  2741. #define stb__arr_setsize stb__arr_setsize_
  2742. #define stb__arr_setlen stb__arr_setlen_
  2743. #define stb__arr_addlen stb__arr_addlen_
  2744. #define stb__arr_deleten stb__arr_deleten_
  2745. #define stb__arr_insertn stb__arr_insertn_
  2746. #else
  2747. #define stb__arr_addlen(p,s,n) stb__arr_addlen_(p,s,n,__FILE__,__LINE__)
  2748. #define stb__arr_setlen(p,s,n) stb__arr_setlen_(p,s,n,__FILE__,__LINE__)
  2749. #define stb__arr_setsize(p,s,n) stb__arr_setsize_(p,s,n,__FILE__,__LINE__)
  2750. #define stb__arr_deleten(p,s,i,n) stb__arr_deleten_(p,s,i,n,__FILE__,__LINE__)
  2751. #define stb__arr_insertn(p,s,i,n) stb__arr_insertn_(p,s,i,n,__FILE__,__LINE__)
  2752. #endif
  2753. #ifdef STB_DEFINE
  2754. static void *stb__arr_context;
  2755. void *stb_arr_malloc_parent(void *p)
  2756. {
  2757. void *q = stb__arr_context;
  2758. stb__arr_context = p;
  2759. return q;
  2760. }
  2761. void stb_arr_malloc(void **target, void *context)
  2762. {
  2763. stb__arr *q = (stb__arr *) stb_malloc(context, sizeof(*q));
  2764. q->len = q->limit = 0;
  2765. q->stb_malloc = 1;
  2766. q->signature = stb_arr_signature;
  2767. *target = (void *) (q+1);
  2768. }
  2769. static void * stb__arr_malloc(int size)
  2770. {
  2771. if (stb__arr_context)
  2772. return stb_malloc(stb__arr_context, size);
  2773. return malloc(size);
  2774. }
  2775. void * stb__arr_copy_(void *p, int elem_size)
  2776. {
  2777. stb__arr *q;
  2778. if (p == NULL) return p;
  2779. q = (stb__arr *) stb__arr_malloc(sizeof(*q) + elem_size * stb_arrhead2(p)->limit);
  2780. stb_arr_check2(p);
  2781. memcpy(q, stb_arrhead2(p), sizeof(*q) + elem_size * stb_arrhead2(p)->len);
  2782. q->stb_malloc = !!stb__arr_context;
  2783. return q+1;
  2784. }
  2785. void stb_arr_free_(void **pp)
  2786. {
  2787. void *p = *pp;
  2788. stb_arr_check2(p);
  2789. if (p) {
  2790. stb__arr *q = stb_arrhead2(p);
  2791. if (q->stb_malloc)
  2792. stb_free(q);
  2793. else
  2794. free(q);
  2795. }
  2796. *pp = NULL;
  2797. }
  2798. static void stb__arrsize_(void **pp, int size, int limit, int len STB__PARAMS)
  2799. {
  2800. void *p = *pp;
  2801. stb__arr *a;
  2802. stb_arr_check2(p);
  2803. if (p == NULL) {
  2804. if (len == 0 && size == 0) return;
  2805. a = (stb__arr *) stb__arr_malloc(sizeof(*a) + size*limit);
  2806. a->limit = limit;
  2807. a->len = len;
  2808. a->stb_malloc = !!stb__arr_context;
  2809. a->signature = stb_arr_signature;
  2810. } else {
  2811. a = stb_arrhead2(p);
  2812. a->len = len;
  2813. if (a->limit < limit) {
  2814. void *p;
  2815. if (a->limit >= 4 && limit < a->limit * 2)
  2816. limit = a->limit * 2;
  2817. if (a->stb_malloc)
  2818. p = stb_realloc(a, sizeof(*a) + limit*size);
  2819. else
  2820. #ifdef STB_MALLOC_WRAPPER
  2821. p = stb__realloc(a, sizeof(*a) + limit*size, file, line);
  2822. #else
  2823. p = realloc(a, sizeof(*a) + limit*size);
  2824. #endif
  2825. if (p) {
  2826. a = (stb__arr *) p;
  2827. a->limit = limit;
  2828. } else {
  2829. // throw an error!
  2830. }
  2831. }
  2832. }
  2833. a->len = stb_min(a->len, a->limit);
  2834. *pp = a+1;
  2835. }
  2836. void stb__arr_setsize_(void **pp, int size, int limit STB__PARAMS)
  2837. {
  2838. void *p = *pp;
  2839. stb_arr_check2(p);
  2840. stb__arrsize_(pp, size, limit, stb_arr_len2(p) STB__ARGS);
  2841. }
  2842. void stb__arr_setlen_(void **pp, int size, int newlen STB__PARAMS)
  2843. {
  2844. void *p = *pp;
  2845. stb_arr_check2(p);
  2846. if (stb_arrcurmax2(p) < newlen || p == NULL) {
  2847. stb__arrsize_(pp, size, newlen, newlen STB__ARGS);
  2848. } else {
  2849. stb_arrhead2(p)->len = newlen;
  2850. }
  2851. }
  2852. void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS)
  2853. {
  2854. stb__arr_setlen_(p, size, stb_arr_len2(*p) + addlen STB__ARGS);
  2855. }
  2856. void stb__arr_insertn_(void **pp, int size, int i, int n STB__PARAMS)
  2857. {
  2858. void *p = *pp;
  2859. if (n) {
  2860. int z;
  2861. if (p == NULL) {
  2862. stb__arr_addlen_(pp, size, n STB__ARGS);
  2863. return;
  2864. }
  2865. z = stb_arr_len2(p);
  2866. stb__arr_addlen_(&p, size, n STB__ARGS);
  2867. memmove((char *) p + (i+n)*size, (char *) p + i*size, size * (z-i));
  2868. }
  2869. *pp = p;
  2870. }
  2871. void stb__arr_deleten_(void **pp, int size, int i, int n STB__PARAMS)
  2872. {
  2873. void *p = *pp;
  2874. if (n) {
  2875. memmove((char *) p + i*size, (char *) p + (i+n)*size, size * (stb_arr_len2(p)-(i+n)));
  2876. stb_arrhead2(p)->len -= n;
  2877. }
  2878. *pp = p;
  2879. }
  2880. #endif
  2881. //////////////////////////////////////////////////////////////////////////////
  2882. //
  2883. // Hashing
  2884. //
  2885. // typical use for this is to make a power-of-two hash table.
  2886. //
  2887. // let N = size of table (2^n)
  2888. // let H = stb_hash(str)
  2889. // let S = stb_rehash(H) | 1
  2890. //
  2891. // then hash probe sequence P(i) for i=0..N-1
  2892. // P(i) = (H + S*i) & (N-1)
  2893. //
  2894. // the idea is that H has 32 bits of hash information, but the
  2895. // table has only, say, 2^20 entries so only uses 20 of the bits.
  2896. // then by rehashing the original H we get 2^12 different probe
  2897. // sequences for a given initial probe location. (So it's optimal
  2898. // for 64K tables and its optimality decreases past that.)
  2899. //
  2900. // ok, so I've added something that generates _two separate_
  2901. // 32-bit hashes simultaneously which should scale better to
  2902. // very large tables.
  2903. STB_EXTERN unsigned int stb_hash(char *str);
  2904. STB_EXTERN unsigned int stb_hashptr(void *p);
  2905. STB_EXTERN unsigned int stb_hashlen(char *str, int len);
  2906. STB_EXTERN unsigned int stb_rehash_improved(unsigned int v);
  2907. STB_EXTERN unsigned int stb_hash_fast(void *p, int len);
  2908. STB_EXTERN unsigned int stb_hash2(char *str, unsigned int *hash2_ptr);
  2909. STB_EXTERN unsigned int stb_hash_number(unsigned int hash);
  2910. #define stb_rehash(x) ((x) + ((x) >> 6) + ((x) >> 19))
  2911. #ifdef STB_DEFINE
  2912. unsigned int stb_hash(char *str)
  2913. {
  2914. unsigned int hash = 0;
  2915. while (*str)
  2916. hash = (hash << 7) + (hash >> 25) + *str++;
  2917. return hash + (hash >> 16);
  2918. }
  2919. unsigned int stb_hashlen(char *str, int len)
  2920. {
  2921. unsigned int hash = 0;
  2922. while (len-- > 0 && *str)
  2923. hash = (hash << 7) + (hash >> 25) + *str++;
  2924. return hash + (hash >> 16);
  2925. }
  2926. unsigned int stb_hashptr(void *p)
  2927. {
  2928. unsigned int x = (unsigned int) p;
  2929. // typically lacking in low bits and high bits
  2930. x = stb_rehash(x);
  2931. x += x << 16;
  2932. // pearson's shuffle
  2933. x ^= x << 3;
  2934. x += x >> 5;
  2935. x ^= x << 2;
  2936. x += x >> 15;
  2937. x ^= x << 10;
  2938. return stb_rehash(x);
  2939. }
  2940. unsigned int stb_rehash_improved(unsigned int v)
  2941. {
  2942. return stb_hashptr((void *)(size_t) v);
  2943. }
  2944. unsigned int stb_hash2(char *str, unsigned int *hash2_ptr)
  2945. {
  2946. unsigned int hash1 = 0x3141592c;
  2947. unsigned int hash2 = 0x77f044ed;
  2948. while (*str) {
  2949. hash1 = (hash1 << 7) + (hash1 >> 25) + *str;
  2950. hash2 = (hash2 << 11) + (hash2 >> 21) + *str;
  2951. ++str;
  2952. }
  2953. *hash2_ptr = hash2 + (hash1 >> 16);
  2954. return hash1 + (hash2 >> 16);
  2955. }
  2956. // Paul Hsieh hash
  2957. #define stb__get16_slow(p) ((p)[0] + ((p)[1] << 8))
  2958. #if defined(_MSC_VER)
  2959. #define stb__get16(p) (*((unsigned short *) (p)))
  2960. #else
  2961. #define stb__get16(p) stb__get16_slow(p)
  2962. #endif
  2963. unsigned int stb_hash_fast(void *p, int len)
  2964. {
  2965. unsigned char *q = (unsigned char *) p;
  2966. unsigned int hash = len;
  2967. if (len <= 0 || q == NULL) return 0;
  2968. /* Main loop */
  2969. if (((int) q & 1) == 0) {
  2970. for (;len > 3; len -= 4) {
  2971. unsigned int val;
  2972. hash += stb__get16(q);
  2973. val = (stb__get16(q+2) << 11);
  2974. hash = (hash << 16) ^ hash ^ val;
  2975. q += 4;
  2976. hash += hash >> 11;
  2977. }
  2978. } else {
  2979. for (;len > 3; len -= 4) {
  2980. unsigned int val;
  2981. hash += stb__get16_slow(q);
  2982. val = (stb__get16_slow(q+2) << 11);
  2983. hash = (hash << 16) ^ hash ^ val;
  2984. q += 4;
  2985. hash += hash >> 11;
  2986. }
  2987. }
  2988. /* Handle end cases */
  2989. switch (len) {
  2990. case 3: hash += stb__get16_slow(q);
  2991. hash ^= hash << 16;
  2992. hash ^= q[2] << 18;
  2993. hash += hash >> 11;
  2994. break;
  2995. case 2: hash += stb__get16_slow(q);
  2996. hash ^= hash << 11;
  2997. hash += hash >> 17;
  2998. break;
  2999. case 1: hash += q[0];
  3000. hash ^= hash << 10;
  3001. hash += hash >> 1;
  3002. break;
  3003. case 0: break;
  3004. }
  3005. /* Force "avalanching" of final 127 bits */
  3006. hash ^= hash << 3;
  3007. hash += hash >> 5;
  3008. hash ^= hash << 4;
  3009. hash += hash >> 17;
  3010. hash ^= hash << 25;
  3011. hash += hash >> 6;
  3012. return hash;
  3013. }
  3014. unsigned int stb_hash_number(unsigned int hash)
  3015. {
  3016. hash ^= hash << 3;
  3017. hash += hash >> 5;
  3018. hash ^= hash << 4;
  3019. hash += hash >> 17;
  3020. hash ^= hash << 25;
  3021. hash += hash >> 6;
  3022. return hash;
  3023. }
  3024. #endif
  3025. //////////////////////////////////////////////////////////////////////////////
  3026. //
  3027. // Perfect hashing for ints/pointers
  3028. //
  3029. // This is mainly useful for making faster pointer-indexed tables
  3030. // that don't change frequently. E.g. for stb_ischar().
  3031. //
  3032. typedef struct
  3033. {
  3034. stb_uint32 addend;
  3035. stb_uint multiplicand;
  3036. stb_uint b_mask;
  3037. stb_uint8 small_bmap[16];
  3038. stb_uint16 *large_bmap;
  3039. stb_uint table_mask;
  3040. stb_uint32 *table;
  3041. } stb_perfect;
  3042. STB_EXTERN int stb_perfect_create(stb_perfect *,unsigned int*,int n);
  3043. STB_EXTERN void stb_perfect_destroy(stb_perfect *);
  3044. STB_EXTERN int stb_perfect_hash(stb_perfect *, unsigned int x);
  3045. extern int stb_perfect_hash_max_failures;
  3046. #ifdef STB_DEFINE
  3047. int stb_perfect_hash_max_failures;
  3048. int stb_perfect_hash(stb_perfect *p, unsigned int x)
  3049. {
  3050. stb_uint m = x * p->multiplicand;
  3051. stb_uint y = x >> 16;
  3052. stb_uint bv = (m >> 24) + y;
  3053. stb_uint av = (m + y) >> 12;
  3054. if (p->table == NULL) return -1; // uninitialized table fails
  3055. bv &= p->b_mask;
  3056. av &= p->table_mask;
  3057. if (p->large_bmap)
  3058. av ^= p->large_bmap[bv];
  3059. else
  3060. av ^= p->small_bmap[bv];
  3061. return p->table[av] == x ? av : -1;
  3062. }
  3063. static void stb__perfect_prehash(stb_perfect *p, stb_uint x, stb_uint16 *a, stb_uint16 *b)
  3064. {
  3065. stb_uint m = x * p->multiplicand;
  3066. stb_uint y = x >> 16;
  3067. stb_uint bv = (m >> 24) + y;
  3068. stb_uint av = (m + y) >> 12;
  3069. bv &= p->b_mask;
  3070. av &= p->table_mask;
  3071. *b = bv;
  3072. *a = av;
  3073. }
  3074. static unsigned long stb__perfect_rand(void)
  3075. {
  3076. static unsigned long stb__rand;
  3077. stb__rand = stb__rand * 2147001325 + 715136305;
  3078. return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16));
  3079. }
  3080. typedef struct {
  3081. unsigned short count;
  3082. unsigned short b;
  3083. unsigned short map;
  3084. unsigned short *entries;
  3085. } stb__slot;
  3086. static int stb__slot_compare(const void *p, const void *q)
  3087. {
  3088. stb__slot *a = (stb__slot *) p;
  3089. stb__slot *b = (stb__slot *) q;
  3090. return a->count > b->count ? -1 : a->count < b->count; // sort large to small
  3091. }
  3092. int stb_perfect_create(stb_perfect *p, unsigned int *v, int n)
  3093. {
  3094. unsigned int buffer1[64], buffer2[64], buffer3[64], buffer4[64], buffer5[32];
  3095. unsigned short *as = (unsigned short *) stb_temp(buffer1, sizeof(*v)*n);
  3096. unsigned short *bs = (unsigned short *) stb_temp(buffer2, sizeof(*v)*n);
  3097. unsigned short *entries = (unsigned short *) stb_temp(buffer4, sizeof(*entries) * n);
  3098. int size = 1 << stb_log2_ceil(n), bsize=8;
  3099. int failure = 0,i,j,k;
  3100. assert(n <= 32768);
  3101. p->large_bmap = NULL;
  3102. for(;;) {
  3103. stb__slot *bcount = (stb__slot *) stb_temp(buffer3, sizeof(*bcount) * bsize);
  3104. unsigned short *bloc = (unsigned short *) stb_temp(buffer5, sizeof(*bloc) * bsize);
  3105. unsigned short *e;
  3106. int bad=0;
  3107. p->addend = stb__perfect_rand();
  3108. p->multiplicand = stb__perfect_rand() | 1;
  3109. p->table_mask = size-1;
  3110. p->b_mask = bsize-1;
  3111. p->table = (stb_uint32 *) malloc(size * sizeof(*p->table));
  3112. for (i=0; i < bsize; ++i) {
  3113. bcount[i].b = i;
  3114. bcount[i].count = 0;
  3115. bcount[i].map = 0;
  3116. }
  3117. for (i=0; i < n; ++i) {
  3118. stb__perfect_prehash(p, v[i], as+i, bs+i);
  3119. ++bcount[bs[i]].count;
  3120. }
  3121. qsort(bcount, bsize, sizeof(*bcount), stb__slot_compare);
  3122. e = entries; // now setup up their entries index
  3123. for (i=0; i < bsize; ++i) {
  3124. bcount[i].entries = e;
  3125. e += bcount[i].count;
  3126. bcount[i].count = 0;
  3127. bloc[bcount[i].b] = i;
  3128. }
  3129. // now fill them out
  3130. for (i=0; i < n; ++i) {
  3131. int b = bs[i];
  3132. int w = bloc[b];
  3133. bcount[w].entries[bcount[w].count++] = i;
  3134. }
  3135. stb_tempfree(buffer5,bloc);
  3136. // verify
  3137. for (i=0; i < bsize; ++i)
  3138. for (j=0; j < bcount[i].count; ++j)
  3139. assert(bs[bcount[i].entries[j]] == bcount[i].b);
  3140. memset(p->table, 0, size*sizeof(*p->table));
  3141. // check if any b has duplicate a
  3142. for (i=0; i < bsize; ++i) {
  3143. if (bcount[i].count > 1) {
  3144. for (j=0; j < bcount[i].count; ++j) {
  3145. if (p->table[as[bcount[i].entries[j]]])
  3146. bad = 1;
  3147. p->table[as[bcount[i].entries[j]]] = 1;
  3148. }
  3149. for (j=0; j < bcount[i].count; ++j) {
  3150. p->table[as[bcount[i].entries[j]]] = 0;
  3151. }
  3152. if (bad) break;
  3153. }
  3154. }
  3155. if (!bad) {
  3156. // go through the bs and populate the table, first fit
  3157. for (i=0; i < bsize; ++i) {
  3158. if (bcount[i].count) {
  3159. // go through the candidate table[b] values
  3160. for (j=0; j < size; ++j) {
  3161. // go through the a values and see if they fit
  3162. for (k=0; k < bcount[i].count; ++k) {
  3163. int a = as[bcount[i].entries[k]];
  3164. if (p->table[(a^j)&p->table_mask]) {
  3165. break; // fails
  3166. }
  3167. }
  3168. // if succeeded, accept
  3169. if (k == bcount[i].count) {
  3170. bcount[i].map = j;
  3171. for (k=0; k < bcount[i].count; ++k) {
  3172. int a = as[bcount[i].entries[k]];
  3173. p->table[(a^j)&p->table_mask] = 1;
  3174. }
  3175. break;
  3176. }
  3177. }
  3178. if (j == size)
  3179. break; // no match for i'th entry, so break out in failure
  3180. }
  3181. }
  3182. if (i == bsize) {
  3183. // success... fill out map
  3184. if (bsize <= 16 && size <= 256) {
  3185. p->large_bmap = NULL;
  3186. for (i=0; i < bsize; ++i)
  3187. p->small_bmap[bcount[i].b] = (stb_uint8) bcount[i].map;
  3188. } else {
  3189. p->large_bmap = (unsigned short *) malloc(sizeof(*p->large_bmap) * bsize);
  3190. for (i=0; i < bsize; ++i)
  3191. p->large_bmap[bcount[i].b] = bcount[i].map;
  3192. }
  3193. // initialize table to v[0], so empty slots will fail
  3194. for (i=0; i < size; ++i)
  3195. p->table[i] = v[0];
  3196. for (i=0; i < n; ++i)
  3197. if (p->large_bmap)
  3198. p->table[as[i] ^ p->large_bmap[bs[i]]] = v[i];
  3199. else
  3200. p->table[as[i] ^ p->small_bmap[bs[i]]] = v[i];
  3201. // and now validate that none of them collided
  3202. for (i=0; i < n; ++i)
  3203. assert(stb_perfect_hash(p, v[i]) >= 0);
  3204. stb_tempfree(buffer3, bcount);
  3205. break;
  3206. }
  3207. }
  3208. free(p->table);
  3209. p->table = NULL;
  3210. stb_tempfree(buffer3, bcount);
  3211. ++failure;
  3212. if (failure >= 4 && bsize < size) bsize *= 2;
  3213. if (failure >= 8 && (failure & 3) == 0 && size < 4*n) {
  3214. size *= 2;
  3215. bsize *= 2;
  3216. }
  3217. if (failure == 6) {
  3218. // make sure the input data is unique, so we don't infinite loop
  3219. unsigned int *data = (unsigned int *) stb_temp(buffer3, n * sizeof(*data));
  3220. memcpy(data, v, sizeof(*data) * n);
  3221. qsort(data, n, sizeof(*data), stb_intcmp(0));
  3222. for (i=1; i < n; ++i) {
  3223. if (data[i] == data[i-1])
  3224. size = 0; // size is return value, so 0 it
  3225. }
  3226. stb_tempfree(buffer3, data);
  3227. if (!size) break;
  3228. }
  3229. }
  3230. if (failure > stb_perfect_hash_max_failures)
  3231. stb_perfect_hash_max_failures = failure;
  3232. stb_tempfree(buffer1, as);
  3233. stb_tempfree(buffer2, bs);
  3234. stb_tempfree(buffer4, entries);
  3235. return size;
  3236. }
  3237. void stb_perfect_destroy(stb_perfect *p)
  3238. {
  3239. if (p->large_bmap) free(p->large_bmap);
  3240. if (p->table ) free(p->table);
  3241. p->large_bmap = NULL;
  3242. p->table = NULL;
  3243. p->b_mask = 0;
  3244. p->table_mask = 0;
  3245. }
  3246. #endif
  3247. //////////////////////////////////////////////////////////////////////////////
  3248. //
  3249. // Perfect hash clients
  3250. STB_EXTERN int stb_ischar(char s, char *set);
  3251. #ifdef STB_DEFINE
  3252. int stb_ischar(char c, char *set)
  3253. {
  3254. static unsigned char bit[8] = { 1,2,4,8,16,32,64,128 };
  3255. static stb_perfect p;
  3256. static unsigned char (*tables)[256];
  3257. static char ** sets = NULL;
  3258. int z = stb_perfect_hash(&p, (int) set);
  3259. if (z < 0) {
  3260. int i,k,n,j,f;
  3261. // special code that means free all existing data
  3262. if (set == NULL) {
  3263. stb_arr_free(sets);
  3264. free(tables);
  3265. tables = NULL;
  3266. stb_perfect_destroy(&p);
  3267. return 0;
  3268. }
  3269. stb_arr_push(sets, set);
  3270. stb_perfect_destroy(&p);
  3271. n = stb_perfect_create(&p, (unsigned int *) (char **) sets, stb_arr_len(sets));
  3272. assert(n != 0);
  3273. k = (n+7) >> 3;
  3274. tables = (unsigned char (*)[256]) realloc(tables, sizeof(*tables) * k);
  3275. memset(tables, 0, sizeof(*tables) * k);
  3276. for (i=0; i < stb_arr_len(sets); ++i) {
  3277. k = stb_perfect_hash(&p, (int) sets[i]);
  3278. assert(k >= 0);
  3279. n = k >> 3;
  3280. f = bit[k&7];
  3281. for (j=0; !j || sets[i][j]; ++j) {
  3282. tables[n][(unsigned char) sets[i][j]] |= f;
  3283. }
  3284. }
  3285. z = stb_perfect_hash(&p, (int) set);
  3286. }
  3287. return tables[z >> 3][(unsigned char) c] & bit[z & 7];
  3288. }
  3289. #endif
  3290. //////////////////////////////////////////////////////////////////////////////
  3291. //
  3292. // Instantiated data structures
  3293. //
  3294. // This is an attempt to implement a templated data structure.
  3295. //
  3296. // Hash table: call stb_define_hash(TYPE,N,KEY,K1,K2,HASH,VALUE)
  3297. // TYPE -- will define a structure type containing the hash table
  3298. // N -- the name, will prefix functions named:
  3299. // N create
  3300. // N destroy
  3301. // N get
  3302. // N set, N add, N update,
  3303. // N remove
  3304. // KEY -- the type of the key. 'x == y' must be valid
  3305. // K1,K2 -- keys never used by the app, used as flags in the hashtable
  3306. // HASH -- a piece of code ending with 'return' that hashes key 'k'
  3307. // VALUE -- the type of the value. 'x = y' must be valid
  3308. //
  3309. // Note that stb_define_hash_base can be used to define more sophisticated
  3310. // hash tables, e.g. those that make copies of the key or use special
  3311. // comparisons (e.g. strcmp).
  3312. #define STB_(prefix,name) stb__##prefix##name
  3313. #define STB__(prefix,name) prefix##name
  3314. #define STB__use(x) x
  3315. #define STB__skip(x)
  3316. #define stb_declare_hash(PREFIX,TYPE,N,KEY,VALUE) \
  3317. typedef struct stb__st_##TYPE TYPE;\
  3318. PREFIX int STB__(N, init)(TYPE *h, int count);\
  3319. PREFIX int STB__(N, memory_usage)(TYPE *h);\
  3320. PREFIX TYPE * STB__(N, create)(void);\
  3321. PREFIX TYPE * STB__(N, copy)(TYPE *h);\
  3322. PREFIX void STB__(N, destroy)(TYPE *h);\
  3323. PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v);\
  3324. PREFIX VALUE STB__(N,get)(TYPE *a, KEY k);\
  3325. PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v);\
  3326. PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v);\
  3327. PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v);\
  3328. PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v);
  3329. #define STB_nocopy(x) (x)
  3330. #define STB_nodelete(x) 0
  3331. #define STB_nofields
  3332. #define STB_nonullvalue(x)
  3333. #define STB_nullvalue(x) x
  3334. #define STB_safecompare(x) x
  3335. #define STB_nosafe(x)
  3336. #define STB_noprefix
  3337. #ifdef __GNUC__
  3338. #define STB__nogcc(x)
  3339. #else
  3340. #define STB__nogcc(x) x
  3341. #endif
  3342. #define stb_define_hash_base(PREFIX,TYPE,FIELDS,N,NC,LOAD_FACTOR, \
  3343. KEY,EMPTY,DEL,COPY,DISPOSE,SAFE, \
  3344. VCOMPARE,CCOMPARE,HASH, \
  3345. VALUE,HASVNULL,VNULL) \
  3346. \
  3347. typedef struct \
  3348. { \
  3349. KEY k; \
  3350. VALUE v; \
  3351. } STB_(N,_hashpair); \
  3352. \
  3353. STB__nogcc( typedef struct stb__st_##TYPE TYPE; ) \
  3354. struct stb__st_##TYPE { \
  3355. FIELDS \
  3356. STB_(N,_hashpair) *table; \
  3357. unsigned int mask; \
  3358. int count, limit; \
  3359. int deleted; \
  3360. \
  3361. int delete_threshhold; \
  3362. int grow_threshhold; \
  3363. int shrink_threshhold; \
  3364. unsigned char alloced, has_empty, has_del; \
  3365. VALUE ev; VALUE dv; \
  3366. }; \
  3367. \
  3368. static unsigned int STB_(N, hash)(KEY k) \
  3369. { \
  3370. HASH \
  3371. } \
  3372. \
  3373. PREFIX int STB__(N, init)(TYPE *h, int count) \
  3374. { \
  3375. int i; \
  3376. if (count < 4) count = 4; \
  3377. h->limit = count; \
  3378. h->count = 0; \
  3379. h->mask = count-1; \
  3380. h->deleted = 0; \
  3381. h->grow_threshhold = (int) (count * LOAD_FACTOR); \
  3382. h->has_empty = h->has_del = 0; \
  3383. h->alloced = 0; \
  3384. if (count <= 64) \
  3385. h->shrink_threshhold = 0; \
  3386. else \
  3387. h->shrink_threshhold = (int) (count * (LOAD_FACTOR/2.25)); \
  3388. h->delete_threshhold = (int) (count * (1-LOAD_FACTOR)/2); \
  3389. h->table = (STB_(N,_hashpair)*) malloc(sizeof(h->table[0]) * count); \
  3390. if (h->table == NULL) return 0; \
  3391. /* ideally this gets turned into a memset32 automatically */ \
  3392. for (i=0; i < count; ++i) \
  3393. h->table[i].k = EMPTY; \
  3394. return 1; \
  3395. } \
  3396. \
  3397. PREFIX int STB__(N, memory_usage)(TYPE *h) \
  3398. { \
  3399. return sizeof(*h) + h->limit * sizeof(h->table[0]); \
  3400. } \
  3401. \
  3402. PREFIX TYPE * STB__(N, create)(void) \
  3403. { \
  3404. TYPE *h = (TYPE *) malloc(sizeof(*h)); \
  3405. if (h) { \
  3406. if (STB__(N, init)(h, 16)) \
  3407. h->alloced = 1; \
  3408. else { free(h); h=NULL; } \
  3409. } \
  3410. return h; \
  3411. } \
  3412. \
  3413. PREFIX void STB__(N, destroy)(TYPE *a) \
  3414. { \
  3415. int i; \
  3416. for (i=0; i < a->limit; ++i) \
  3417. if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k, DEL)) \
  3418. DISPOSE(a->table[i].k); \
  3419. free(a->table); \
  3420. if (a->alloced) \
  3421. free(a); \
  3422. } \
  3423. \
  3424. static void STB_(N, rehash)(TYPE *a, int count); \
  3425. \
  3426. PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v) \
  3427. { \
  3428. unsigned int h = STB_(N, hash)(k); \
  3429. unsigned int n = h & a->mask, s; \
  3430. if (CCOMPARE(k,EMPTY)){ if (a->has_empty) *v = a->ev; return a->has_empty;}\
  3431. if (CCOMPARE(k,DEL)) { if (a->has_del ) *v = a->dv; return a->has_del; }\
  3432. if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \
  3433. SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \
  3434. if (VCOMPARE(a->table[n].k,k)) { *v = a->table[n].v; return 1; } \
  3435. s = stb_rehash(h) | 1; \
  3436. for(;;) { \
  3437. n = (n + s) & a->mask; \
  3438. if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \
  3439. SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \
  3440. if (VCOMPARE(a->table[n].k,k)) \
  3441. { *v = a->table[n].v; return 1; } \
  3442. } \
  3443. } \
  3444. \
  3445. HASVNULL( \
  3446. PREFIX VALUE STB__(N,get)(TYPE *a, KEY k) \
  3447. { \
  3448. VALUE v; \
  3449. if (STB__(N,get_flag)(a,k,&v)) return v; \
  3450. else return VNULL; \
  3451. } \
  3452. ) \
  3453. \
  3454. PREFIX int STB__(N,getkey)(TYPE *a, KEY k, KEY *kout) \
  3455. { \
  3456. unsigned int h = STB_(N, hash)(k); \
  3457. unsigned int n = h & a->mask, s; \
  3458. if (CCOMPARE(k,EMPTY)||CCOMPARE(k,DEL)) return 0; \
  3459. if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \
  3460. SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \
  3461. if (VCOMPARE(a->table[n].k,k)) { *kout = a->table[n].k; return 1; } \
  3462. s = stb_rehash(h) | 1; \
  3463. for(;;) { \
  3464. n = (n + s) & a->mask; \
  3465. if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \
  3466. SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \
  3467. if (VCOMPARE(a->table[n].k,k)) \
  3468. { *kout = a->table[n].k; return 1; } \
  3469. } \
  3470. } \
  3471. \
  3472. static int STB_(N,addset)(TYPE *a, KEY k, VALUE v, \
  3473. int allow_new, int allow_old, int copy) \
  3474. { \
  3475. unsigned int h = STB_(N, hash)(k); \
  3476. unsigned int n = h & a->mask; \
  3477. int b = -1; \
  3478. if (CCOMPARE(k,EMPTY)) { \
  3479. if (a->has_empty ? allow_old : allow_new) { \
  3480. n=a->has_empty; a->ev = v; a->has_empty = 1; return !n; \
  3481. } else return 0; \
  3482. } \
  3483. if (CCOMPARE(k,DEL)) { \
  3484. if (a->has_del ? allow_old : allow_new) { \
  3485. n=a->has_del; a->dv = v; a->has_del = 1; return !n; \
  3486. } else return 0; \
  3487. } \
  3488. if (!CCOMPARE(a->table[n].k, EMPTY)) { \
  3489. unsigned int s; \
  3490. if (CCOMPARE(a->table[n].k, DEL)) \
  3491. b = n; \
  3492. else if (VCOMPARE(a->table[n].k,k)) { \
  3493. if (allow_old) \
  3494. a->table[n].v = v; \
  3495. return !allow_new; \
  3496. } \
  3497. s = stb_rehash(h) | 1; \
  3498. for(;;) { \
  3499. n = (n + s) & a->mask; \
  3500. if (CCOMPARE(a->table[n].k, EMPTY)) break; \
  3501. if (CCOMPARE(a->table[n].k, DEL)) { \
  3502. if (b < 0) b = n; \
  3503. } else if (VCOMPARE(a->table[n].k,k)) { \
  3504. if (allow_old) \
  3505. a->table[n].v = v; \
  3506. return !allow_new; \
  3507. } \
  3508. } \
  3509. } \
  3510. if (!allow_new) return 0; \
  3511. if (b < 0) b = n; else --a->deleted; \
  3512. a->table[b].k = copy ? COPY(k) : k; \
  3513. a->table[b].v = v; \
  3514. ++a->count; \
  3515. if (a->count > a->grow_threshhold) \
  3516. STB_(N,rehash)(a, a->limit*2); \
  3517. return 1; \
  3518. } \
  3519. \
  3520. PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,1,1);}\
  3521. PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,0,1);}\
  3522. PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v){return STB_(N,addset)(a,k,v,0,1,1);}\
  3523. \
  3524. PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v) \
  3525. { \
  3526. unsigned int h = STB_(N, hash)(k); \
  3527. unsigned int n = h & a->mask, s; \
  3528. if (CCOMPARE(k,EMPTY)) { if (a->has_empty) { if(v)*v = a->ev; a->has_empty=0; return 1; } return 0; } \
  3529. if (CCOMPARE(k,DEL)) { if (a->has_del ) { if(v)*v = a->dv; a->has_del =0; return 1; } return 0; } \
  3530. if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \
  3531. if (SAFE(CCOMPARE(a->table[n].k,DEL) || ) !VCOMPARE(a->table[n].k,k)) { \
  3532. s = stb_rehash(h) | 1; \
  3533. for(;;) { \
  3534. n = (n + s) & a->mask; \
  3535. if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \
  3536. SAFE(if (CCOMPARE(a->table[n].k, DEL)) continue;) \
  3537. if (VCOMPARE(a->table[n].k,k)) break; \
  3538. } \
  3539. } \
  3540. DISPOSE(a->table[n].k); \
  3541. a->table[n].k = DEL; \
  3542. --a->count; \
  3543. ++a->deleted; \
  3544. if (v != NULL) \
  3545. *v = a->table[n].v; \
  3546. if (a->count < a->shrink_threshhold) \
  3547. STB_(N, rehash)(a, a->limit >> 1); \
  3548. else if (a->deleted > a->delete_threshhold) \
  3549. STB_(N, rehash)(a, a->limit); \
  3550. return 1; \
  3551. } \
  3552. \
  3553. PREFIX TYPE * STB__(NC, copy)(TYPE *a) \
  3554. { \
  3555. int i; \
  3556. TYPE *h = (TYPE *) malloc(sizeof(*h)); \
  3557. if (!h) return NULL; \
  3558. if (!STB__(N, init)(h, a->limit)) { free(h); return NULL; } \
  3559. h->count = a->count; \
  3560. h->deleted = a->deleted; \
  3561. h->alloced = 1; \
  3562. h->ev = a->ev; h->dv = a->dv; \
  3563. h->has_empty = a->has_empty; h->has_del = a->has_del; \
  3564. memcpy(h->table, a->table, h->limit * sizeof(h->table[0])); \
  3565. for (i=0; i < a->limit; ++i) \
  3566. if (!CCOMPARE(h->table[i].k,EMPTY) && !CCOMPARE(h->table[i].k,DEL)) \
  3567. h->table[i].k = COPY(h->table[i].k); \
  3568. return h; \
  3569. } \
  3570. \
  3571. static void STB_(N, rehash)(TYPE *a, int count) \
  3572. { \
  3573. int i; \
  3574. TYPE b; \
  3575. STB__(N, init)(&b, count); \
  3576. for (i=0; i < a->limit; ++i) \
  3577. if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k,DEL)) \
  3578. STB_(N,addset)(&b, a->table[i].k, a->table[i].v,1,1,0); \
  3579. free(a->table); \
  3580. a->table = b.table; \
  3581. a->mask = b.mask; \
  3582. a->count = b.count; \
  3583. a->limit = b.limit; \
  3584. a->deleted = b.deleted; \
  3585. a->delete_threshhold = b.delete_threshhold; \
  3586. a->grow_threshhold = b.grow_threshhold; \
  3587. a->shrink_threshhold = b.shrink_threshhold; \
  3588. }
  3589. #define STB_equal(a,b) ((a) == (b))
  3590. #define stb_define_hash(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE) \
  3591. stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \
  3592. KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \
  3593. STB_equal,STB_equal,HASH, \
  3594. VALUE,STB_nonullvalue,0)
  3595. #define stb_define_hash_vnull(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE,VNULL) \
  3596. stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \
  3597. KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \
  3598. STB_equal,STB_equal,HASH, \
  3599. VALUE,STB_nullvalue,VNULL)
  3600. //////////////////////////////////////////////////////////////////////////////
  3601. //
  3602. // stb_ptrmap
  3603. //
  3604. // An stb_ptrmap data structure is an O(1) hash table between pointers. One
  3605. // application is to let you store "extra" data associated with pointers,
  3606. // which is why it was originally called stb_extra.
  3607. stb_declare_hash(STB_EXTERN, stb_ptrmap, stb_ptrmap_, void *, void *)
  3608. stb_declare_hash(STB_EXTERN, stb_idict, stb_idict_, stb_int32, stb_int32)
  3609. STB_EXTERN void stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *));
  3610. STB_EXTERN stb_ptrmap *stb_ptrmap_new(void);
  3611. STB_EXTERN stb_idict * stb_idict_new_size(int size);
  3612. STB_EXTERN void stb_idict_remove_all(stb_idict *e);
  3613. #ifdef STB_DEFINE
  3614. #define STB_EMPTY ((void *) 2)
  3615. #define STB_EDEL ((void *) 6)
  3616. stb_define_hash_base(STB_noprefix,stb_ptrmap, STB_nofields, stb_ptrmap_,stb_ptrmap_,0.85f,
  3617. void *,STB_EMPTY,STB_EDEL,STB_nocopy,STB_nodelete,STB_nosafe,
  3618. STB_equal,STB_equal,return stb_hashptr(k);,
  3619. void *,STB_nullvalue,NULL)
  3620. stb_ptrmap *stb_ptrmap_new(void)
  3621. {
  3622. return stb_ptrmap_create();
  3623. }
  3624. void stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *))
  3625. {
  3626. int i;
  3627. if (free_func)
  3628. for (i=0; i < e->limit; ++i)
  3629. if (e->table[i].k != STB_EMPTY && e->table[i].k != STB_EDEL) {
  3630. if (free_func == free)
  3631. free(e->table[i].v); // allow STB_MALLOC_WRAPPER to operate
  3632. else
  3633. free_func(e->table[i].v);
  3634. }
  3635. stb_ptrmap_destroy(e);
  3636. }
  3637. // extra fields needed for stua_dict
  3638. #define STB_IEMPTY ((int) 1)
  3639. #define STB_IDEL ((int) 3)
  3640. stb_define_hash_base(STB_noprefix, stb_idict, short type; short gc; STB_nofields, stb_idict_,stb_idict_,0.85f,
  3641. stb_int32,STB_IEMPTY,STB_IDEL,STB_nocopy,STB_nodelete,STB_nosafe,
  3642. STB_equal,STB_equal,
  3643. return stb_rehash_improved(k);,stb_int32,STB_nonullvalue,0)
  3644. stb_idict * stb_idict_new_size(int size)
  3645. {
  3646. stb_idict *e = (stb_idict *) malloc(sizeof(*e));
  3647. if (e) {
  3648. if (!stb_is_pow2(size))
  3649. size = 1 << stb_log2_ceil(size);
  3650. stb_idict_init(e, size);
  3651. e->alloced = 1;
  3652. }
  3653. return e;
  3654. }
  3655. void stb_idict_remove_all(stb_idict *e)
  3656. {
  3657. int n;
  3658. for (n=0; n < e->limit; ++n)
  3659. e->table[n].k = STB_IEMPTY;
  3660. e->has_empty = e->has_del = 0;
  3661. }
  3662. #endif
  3663. //////////////////////////////////////////////////////////////////////////////
  3664. //
  3665. // stb_sparse_ptr_matrix
  3666. //
  3667. // An stb_ptrmap data structure is an O(1) hash table storing an arbitrary
  3668. // block of data for a given pair of pointers.
  3669. //
  3670. // If create=0, returns
  3671. typedef struct stb__st_stb_spmatrix stb_spmatrix;
  3672. STB_EXTERN stb_spmatrix * stb_sparse_ptr_matrix_new(int val_size);
  3673. STB_EXTERN void stb_sparse_ptr_matrix_free(stb_spmatrix *z);
  3674. STB_EXTERN void * stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create);
  3675. #ifdef STB_DEFINE
  3676. typedef struct
  3677. {
  3678. void *a;
  3679. void *b;
  3680. } stb__ptrpair;
  3681. static stb__ptrpair stb__ptrpair_empty = { (void *) 1, (void *) 1 };
  3682. static stb__ptrpair stb__ptrpair_del = { (void *) 2, (void *) 2 };
  3683. #define STB__equal_ptrpair(x,y) ((x).a == (y).a && (x).b == (y).b)
  3684. stb_define_hash_base(static, stb_spmatrix, int val_size; void *arena;, stb__spmatrix_,stb__spmatrix_, 0.85,
  3685. stb__ptrpair, stb__ptrpair_empty, stb__ptrpair_del,
  3686. STB_nocopy, STB_nodelete, STB_nosafe,
  3687. STB__equal_ptrpair, STB__equal_ptrpair, return stb_rehash(stb_hashptr(k.a))+stb_hashptr(k.b);,
  3688. void *, STB_nullvalue, 0)
  3689. stb_spmatrix *stb_sparse_ptr_matrix_new(int val_size)
  3690. {
  3691. stb_spmatrix *m = stb__spmatrix_create();
  3692. if (m) m->val_size = val_size;
  3693. if (m) m->arena = stb_malloc_global(1);
  3694. return m;
  3695. }
  3696. void stb_sparse_ptr_matrix_free(stb_spmatrix *z)
  3697. {
  3698. if (z->arena) stb_free(z->arena);
  3699. stb__spmatrix_destroy(z);
  3700. }
  3701. void *stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create)
  3702. {
  3703. stb__ptrpair t = { a,b };
  3704. void *data = stb__spmatrix_get(z, t);
  3705. if (!data && create) {
  3706. data = stb_malloc_raw(z->arena, z->val_size);
  3707. if (!data) return NULL;
  3708. memset(data, 0, z->val_size);
  3709. stb__spmatrix_add(z, t, data);
  3710. }
  3711. return data;
  3712. }
  3713. #endif
  3714. //////////////////////////////////////////////////////////////////////////////
  3715. //
  3716. // SDICT: Hash Table for Strings (symbol table)
  3717. //
  3718. // if "use_arena=1", then strings will be copied
  3719. // into blocks and never freed until the sdict is freed;
  3720. // otherwise they're malloc()ed and free()d on the fly.
  3721. // (specify use_arena=1 if you never stb_sdict_remove)
  3722. stb_declare_hash(STB_EXTERN, stb_sdict, stb_sdict_, char *, void *)
  3723. STB_EXTERN stb_sdict * stb_sdict_new(int use_arena);
  3724. STB_EXTERN stb_sdict * stb_sdict_copy(stb_sdict*);
  3725. STB_EXTERN void stb_sdict_delete(stb_sdict *);
  3726. STB_EXTERN void * stb_sdict_change(stb_sdict *, char *str, void *p);
  3727. STB_EXTERN int stb_sdict_count(stb_sdict *d);
  3728. #define stb_sdict_for(d,i,q,z) \
  3729. for(i=0; i < (d)->limit ? q=(d)->table[i].k,z=(d)->table[i].v,1 : 0; ++i) \
  3730. if (q==NULL||q==(void *) 1);else // reversed makes macro friendly
  3731. #ifdef STB_DEFINE
  3732. #define STB_DEL ((void *) 1)
  3733. #define STB_SDEL ((char *) 1)
  3734. #define stb_sdict__copy(x) \
  3735. strcpy(a->arena ? stb_malloc_string(a->arena, strlen(x)+1) \
  3736. : (char *) malloc(strlen(x)+1), x)
  3737. #define stb_sdict__dispose(x) if (!a->arena) free(x)
  3738. stb_define_hash_base(STB_noprefix, stb_sdict, void*arena;, stb_sdict_,stb_sdictinternal_, 0.85f,
  3739. char *, NULL, STB_SDEL, stb_sdict__copy, stb_sdict__dispose,
  3740. STB_safecompare, !strcmp, STB_equal, return stb_hash(k);,
  3741. void *, STB_nullvalue, NULL)
  3742. int stb_sdict_count(stb_sdict *a)
  3743. {
  3744. return a->count;
  3745. }
  3746. stb_sdict * stb_sdict_new(int use_arena)
  3747. {
  3748. stb_sdict *d = stb_sdict_create();
  3749. if (d == NULL) return NULL;
  3750. d->arena = use_arena ? stb_malloc_global(1) : NULL;
  3751. return d;
  3752. }
  3753. stb_sdict* stb_sdict_copy(stb_sdict *old)
  3754. {
  3755. stb_sdict *n;
  3756. void *old_arena = old->arena;
  3757. void *new_arena = old_arena ? stb_malloc_global(1) : NULL;
  3758. old->arena = new_arena;
  3759. n = stb_sdictinternal_copy(old);
  3760. old->arena = old_arena;
  3761. if (n)
  3762. n->arena = new_arena;
  3763. else if (new_arena)
  3764. stb_free(new_arena);
  3765. return n;
  3766. }
  3767. void stb_sdict_delete(stb_sdict *d)
  3768. {
  3769. if (d->arena)
  3770. stb_free(d->arena);
  3771. stb_sdict_destroy(d);
  3772. }
  3773. void * stb_sdict_change(stb_sdict *d, char *str, void *p)
  3774. {
  3775. void *q = stb_sdict_get(d, str);
  3776. stb_sdict_set(d, str, p);
  3777. return q;
  3778. }
  3779. #endif
  3780. //////////////////////////////////////////////////////////////////////////////
  3781. //
  3782. // Instantiated data structures
  3783. //
  3784. // This is an attempt to implement a templated data structure.
  3785. // What you do is define a struct foo, and then include several
  3786. // pointer fields to struct foo in your struct. Then you call
  3787. // the instantiator, which creates the functions that implement
  3788. // the data structure. This requires massive undebuggable #defines,
  3789. // so we limit the cases where we do this.
  3790. //
  3791. // AA tree is an encoding of a 2-3 tree whereas RB trees encode a 2-3-4 tree;
  3792. // much simpler code due to fewer cases.
  3793. #define stb__bst_parent(x) x
  3794. #define stb__bst_noparent(x)
  3795. #define stb_bst_fields(N) \
  3796. *STB_(N,left), *STB_(N,right); \
  3797. unsigned char STB_(N,level)
  3798. #define stb_bst_fields_parent(N) \
  3799. *STB_(N,left), *STB_(N,right), *STB_(N,parent); \
  3800. unsigned char STB_(N,level)
  3801. #define STB__level(N,x) ((x) ? (x)->STB_(N,level) : 0)
  3802. #define stb_bst_base(TYPE, N, TREE, M, compare, PAR) \
  3803. \
  3804. static int STB_(N,_compare)(TYPE *p, TYPE *q) \
  3805. { \
  3806. compare \
  3807. } \
  3808. \
  3809. static void STB_(N,setleft)(TYPE *q, TYPE *v) \
  3810. { \
  3811. q->STB_(N,left) = v; \
  3812. PAR(if (v) v->STB_(N,parent) = q;) \
  3813. } \
  3814. \
  3815. static void STB_(N,setright)(TYPE *q, TYPE *v) \
  3816. { \
  3817. q->STB_(N,right) = v; \
  3818. PAR(if (v) v->STB_(N,parent) = q;) \
  3819. } \
  3820. \
  3821. static TYPE *STB_(N,skew)(TYPE *q) \
  3822. { \
  3823. if (q == NULL) return q; \
  3824. if (q->STB_(N,left) \
  3825. && q->STB_(N,left)->STB_(N,level) == q->STB_(N,level)) { \
  3826. TYPE *p = q->STB_(N,left); \
  3827. STB_(N,setleft)(q, p->STB_(N,right)); \
  3828. STB_(N,setright)(p, q); \
  3829. return p; \
  3830. } \
  3831. return q; \
  3832. } \
  3833. \
  3834. static TYPE *STB_(N,split)(TYPE *p) \
  3835. { \
  3836. TYPE *q = p->STB_(N,right); \
  3837. if (q && q->STB_(N,right) \
  3838. && q->STB_(N,right)->STB_(N,level) == p->STB_(N,level)) { \
  3839. STB_(N,setright)(p, q->STB_(N,left)); \
  3840. STB_(N,setleft)(q,p); \
  3841. ++q->STB_(N,level); \
  3842. return q; \
  3843. } \
  3844. return p; \
  3845. } \
  3846. \
  3847. TYPE *STB__(N,insert)(TYPE *tree, TYPE *item) \
  3848. { \
  3849. int c; \
  3850. if (tree == NULL) { \
  3851. item->STB_(N,left) = NULL; \
  3852. item->STB_(N,right) = NULL; \
  3853. item->STB_(N,level) = 1; \
  3854. PAR(item->STB_(N,parent) = NULL;) \
  3855. return item; \
  3856. } \
  3857. c = STB_(N,_compare)(item,tree); \
  3858. if (c == 0) { \
  3859. if (item != tree) { \
  3860. STB_(N,setleft)(item, tree->STB_(N,left)); \
  3861. STB_(N,setright)(item, tree->STB_(N,right)); \
  3862. item->STB_(N,level) = tree->STB_(N,level); \
  3863. PAR(item->STB_(N,parent) = NULL;) \
  3864. } \
  3865. return item; \
  3866. } \
  3867. if (c < 0) \
  3868. STB_(N,setleft )(tree, STB__(N,insert)(tree->STB_(N,left), item)); \
  3869. else \
  3870. STB_(N,setright)(tree, STB__(N,insert)(tree->STB_(N,right), item)); \
  3871. tree = STB_(N,skew)(tree); \
  3872. tree = STB_(N,split)(tree); \
  3873. PAR(tree->STB_(N,parent) = NULL;) \
  3874. return tree; \
  3875. } \
  3876. \
  3877. TYPE *STB__(N,remove)(TYPE *tree, TYPE *item) \
  3878. { \
  3879. static TYPE *delnode, *leaf, *restore; \
  3880. if (tree == NULL) return NULL; \
  3881. leaf = tree; \
  3882. if (STB_(N,_compare)(item, tree) < 0) { \
  3883. STB_(N,setleft)(tree, STB__(N,remove)(tree->STB_(N,left), item)); \
  3884. } else { \
  3885. TYPE *r; \
  3886. delnode = tree; \
  3887. r = STB__(N,remove)(tree->STB_(N,right), item); \
  3888. /* maybe move 'leaf' up to this location */ \
  3889. if (restore == tree) { tree = leaf; leaf = restore = NULL; } \
  3890. STB_(N,setright)(tree,r); \
  3891. assert(tree->STB_(N,right) != tree); \
  3892. } \
  3893. if (tree == leaf) { \
  3894. if (delnode == item) { \
  3895. tree = tree->STB_(N,right); \
  3896. assert(leaf->STB_(N,left) == NULL); \
  3897. /* move leaf (the right sibling) up to delnode */ \
  3898. STB_(N,setleft )(leaf, item->STB_(N,left )); \
  3899. STB_(N,setright)(leaf, item->STB_(N,right)); \
  3900. leaf->STB_(N,level) = item->STB_(N,level); \
  3901. if (leaf != item) \
  3902. restore = delnode; \
  3903. } \
  3904. delnode = NULL; \
  3905. } else { \
  3906. if (STB__level(N,tree->STB_(N,left) ) < tree->STB_(N,level)-1 || \
  3907. STB__level(N,tree->STB_(N,right)) < tree->STB_(N,level)-1) { \
  3908. --tree->STB_(N,level); \
  3909. if (STB__level(N,tree->STB_(N,right)) > tree->STB_(N,level)) \
  3910. tree->STB_(N,right)->STB_(N,level) = tree->STB_(N,level); \
  3911. tree = STB_(N,skew)(tree); \
  3912. STB_(N,setright)(tree, STB_(N,skew)(tree->STB_(N,right))); \
  3913. if (tree->STB_(N,right)) \
  3914. STB_(N,setright)(tree->STB_(N,right), \
  3915. STB_(N,skew)(tree->STB_(N,right)->STB_(N,right))); \
  3916. tree = STB_(N,split)(tree); \
  3917. if (tree->STB_(N,right)) \
  3918. STB_(N,setright)(tree, STB_(N,split)(tree->STB_(N,right))); \
  3919. } \
  3920. } \
  3921. PAR(if (tree) tree->STB_(N,parent) = NULL;) \
  3922. return tree; \
  3923. } \
  3924. \
  3925. TYPE *STB__(N,last)(TYPE *tree) \
  3926. { \
  3927. if (tree) \
  3928. while (tree->STB_(N,right)) tree = tree->STB_(N,right); \
  3929. return tree; \
  3930. } \
  3931. \
  3932. TYPE *STB__(N,first)(TYPE *tree) \
  3933. { \
  3934. if (tree) \
  3935. while (tree->STB_(N,left)) tree = tree->STB_(N,left); \
  3936. return tree; \
  3937. } \
  3938. \
  3939. TYPE *STB__(N,next)(TYPE *tree, TYPE *item) \
  3940. { \
  3941. TYPE *next = NULL; \
  3942. if (item->STB_(N,right)) \
  3943. return STB__(N,first)(item->STB_(N,right)); \
  3944. PAR( \
  3945. while(item->STB_(N,parent)) { \
  3946. TYPE *up = item->STB_(N,parent); \
  3947. if (up->STB_(N,left) == item) return up; \
  3948. item = up; \
  3949. } \
  3950. return NULL; \
  3951. ) \
  3952. while (tree != item) { \
  3953. if (STB_(N,_compare)(item, tree) < 0) { \
  3954. next = tree; \
  3955. tree = tree->STB_(N,left); \
  3956. } else { \
  3957. tree = tree->STB_(N,right); \
  3958. } \
  3959. } \
  3960. return next; \
  3961. } \
  3962. \
  3963. TYPE *STB__(N,prev)(TYPE *tree, TYPE *item) \
  3964. { \
  3965. TYPE *next = NULL; \
  3966. if (item->STB_(N,left)) \
  3967. return STB__(N,last)(item->STB_(N,left)); \
  3968. PAR( \
  3969. while(item->STB_(N,parent)) { \
  3970. TYPE *up = item->STB_(N,parent); \
  3971. if (up->STB_(N,right) == item) return up; \
  3972. item = up; \
  3973. } \
  3974. return NULL; \
  3975. ) \
  3976. while (tree != item) { \
  3977. if (STB_(N,_compare)(item, tree) < 0) { \
  3978. tree = tree->STB_(N,left); \
  3979. } else { \
  3980. next = tree; \
  3981. tree = tree->STB_(N,right); \
  3982. } \
  3983. } \
  3984. return next; \
  3985. } \
  3986. \
  3987. STB__DEBUG( \
  3988. void STB__(N,_validate)(TYPE *tree, int root) \
  3989. { \
  3990. if (tree == NULL) return; \
  3991. PAR(if(root) assert(tree->STB_(N,parent) == NULL);) \
  3992. assert(STB__level(N,tree->STB_(N,left) ) == tree->STB_(N,level)-1); \
  3993. assert(STB__level(N,tree->STB_(N,right)) <= tree->STB_(N,level)); \
  3994. assert(STB__level(N,tree->STB_(N,right)) >= tree->STB_(N,level)-1); \
  3995. if (tree->STB_(N,right)) { \
  3996. assert(STB__level(N,tree->STB_(N,right)->STB_(N,right)) \
  3997. != tree->STB_(N,level)); \
  3998. PAR(assert(tree->STB_(N,right)->STB_(N,parent) == tree);) \
  3999. } \
  4000. PAR(if(tree->STB_(N,left)) assert(tree->STB_(N,left)->STB_(N,parent) == tree);) \
  4001. STB__(N,_validate)(tree->STB_(N,left) ,0); \
  4002. STB__(N,_validate)(tree->STB_(N,right),0); \
  4003. } \
  4004. ) \
  4005. \
  4006. typedef struct \
  4007. { \
  4008. TYPE *root; \
  4009. } TREE; \
  4010. \
  4011. void STB__(M,Insert)(TREE *tree, TYPE *item) \
  4012. { tree->root = STB__(N,insert)(tree->root, item); } \
  4013. void STB__(M,Remove)(TREE *tree, TYPE *item) \
  4014. { tree->root = STB__(N,remove)(tree->root, item); } \
  4015. TYPE *STB__(M,Next)(TREE *tree, TYPE *item) \
  4016. { return STB__(N,next)(tree->root, item); } \
  4017. TYPE *STB__(M,Prev)(TREE *tree, TYPE *item) \
  4018. { return STB__(N,prev)(tree->root, item); } \
  4019. TYPE *STB__(M,First)(TREE *tree) { return STB__(N,first)(tree->root); } \
  4020. TYPE *STB__(M,Last) (TREE *tree) { return STB__(N,last) (tree->root); } \
  4021. void STB__(M,Init)(TREE *tree) { tree->root = NULL; }
  4022. #define stb_bst_find(N,tree,fcompare) \
  4023. { \
  4024. int c; \
  4025. while (tree != NULL) { \
  4026. fcompare \
  4027. if (c == 0) return tree; \
  4028. if (c < 0) tree = tree->STB_(N,left); \
  4029. else tree = tree->STB_(N,right); \
  4030. } \
  4031. return NULL; \
  4032. }
  4033. #define stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,PAR) \
  4034. stb_bst_base(TYPE,N,TREE,M, \
  4035. VTYPE a = p->vfield; VTYPE b = q->vfield; return (compare);, PAR ) \
  4036. \
  4037. TYPE *STB__(N,find)(TYPE *tree, VTYPE a) \
  4038. stb_bst_find(N,tree,VTYPE b = tree->vfield; c = (compare);) \
  4039. TYPE *STB__(M,Find)(TREE *tree, VTYPE a) \
  4040. { return STB__(N,find)(tree->root, a); }
  4041. #define stb_bst(TYPE,N,TREE,M,vfield,VTYPE,compare) \
  4042. stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_noparent)
  4043. #define stb_bst_parent(TYPE,N,TREE,M,vfield,VTYPE,compare) \
  4044. stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_parent)
  4045. //////////////////////////////////////////////////////////////////////////////
  4046. //
  4047. // Pointer Nulling
  4048. //
  4049. // This lets you automatically NULL dangling pointers to "registered"
  4050. // objects. Note that you have to make sure you call the appropriate
  4051. // functions when you free or realloc blocks of memory that contain
  4052. // pointers or pointer targets. stb.h can automatically do this for
  4053. // stb_arr, or for all frees/reallocs if it's wrapping them.
  4054. //
  4055. #ifdef STB_NPTR
  4056. STB_EXTERN void stb_nptr_set(void *address_of_pointer, void *value_to_write);
  4057. STB_EXTERN void stb_nptr_didset(void *address_of_pointer);
  4058. STB_EXTERN void stb_nptr_didfree(void *address_being_freed, int len);
  4059. STB_EXTERN void stb_nptr_free(void *address_being_freed, int len);
  4060. STB_EXTERN void stb_nptr_didrealloc(void *new_address, void *old_address, int len);
  4061. STB_EXTERN void stb_nptr_recache(void); // recache all known pointers
  4062. // do this after pointer sets outside your control, slow
  4063. #ifdef STB_DEFINE
  4064. // for fast updating on free/realloc, we need to be able to find
  4065. // all the objects (pointers and targets) within a given block;
  4066. // this precludes hashing
  4067. // we use a three-level hierarchy of memory to minimize storage:
  4068. // level 1: 65536 pointers to stb__memory_node (always uses 256 KB)
  4069. // level 2: each stb__memory_node represents a 64K block of memory
  4070. // with 256 stb__memory_leafs (worst case 64MB)
  4071. // level 3: each stb__memory_leaf represents 256 bytes of memory
  4072. // using a list of target locations and a list of pointers
  4073. // (which are hopefully fairly short normally!)
  4074. // this approach won't work in 64-bit, which has a much larger address
  4075. // space. need to redesign
  4076. #define STB__NPTR_ROOT_LOG2 16
  4077. #define STB__NPTR_ROOT_NUM (1 << STB__NPTR_ROOT_LOG2)
  4078. #define STB__NPTR_ROOT_SHIFT (32 - STB__NPTR_ROOT_LOG2)
  4079. #define STB__NPTR_NODE_LOG2 5
  4080. #define STB__NPTR_NODE_NUM (1 << STB__NPTR_NODE_LOG2)
  4081. #define STB__NPTR_NODE_MASK (STB__NPTR_NODE_NUM-1)
  4082. #define STB__NPTR_NODE_SHIFT (STB__NPTR_ROOT_SHIFT - STB__NPTR_NODE_LOG2)
  4083. #define STB__NPTR_NODE_OFFSET(x) (((x) >> STB__NPTR_NODE_SHIFT) & STB__NPTR_NODE_MASK)
  4084. typedef struct stb__st_nptr
  4085. {
  4086. void *ptr; // address of actual pointer
  4087. struct stb__st_nptr *next; // next pointer with same target
  4088. struct stb__st_nptr **prev; // prev pointer with same target, address of 'next' field (or first)
  4089. struct stb__st_nptr *next_in_block;
  4090. } stb__nptr;
  4091. typedef struct stb__st_nptr_target
  4092. {
  4093. void *ptr; // address of target
  4094. stb__nptr *first; // address of first nptr pointing to this
  4095. struct stb__st_nptr_target *next_in_block;
  4096. } stb__nptr_target;
  4097. typedef struct
  4098. {
  4099. stb__nptr *pointers;
  4100. stb__nptr_target *targets;
  4101. } stb__memory_leaf;
  4102. typedef struct
  4103. {
  4104. stb__memory_leaf *children[STB__NPTR_NODE_NUM];
  4105. } stb__memory_node;
  4106. stb__memory_node *stb__memtab_root[STB__NPTR_ROOT_NUM];
  4107. static stb__memory_leaf *stb__nptr_find_leaf(void *mem)
  4108. {
  4109. stb_uint32 address = (stb_uint32) mem;
  4110. stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];
  4111. if (z)
  4112. return z->children[STB__NPTR_NODE_OFFSET(address)];
  4113. else
  4114. return NULL;
  4115. }
  4116. static void * stb__nptr_alloc(int size)
  4117. {
  4118. return stb__realloc_raw(0,size);
  4119. }
  4120. static void stb__nptr_free(void *p)
  4121. {
  4122. stb__realloc_raw(p,0);
  4123. }
  4124. static stb__memory_leaf *stb__nptr_make_leaf(void *mem)
  4125. {
  4126. stb_uint32 address = (stb_uint32) mem;
  4127. stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];
  4128. stb__memory_leaf *f;
  4129. if (!z) {
  4130. int i;
  4131. z = (stb__memory_node *) stb__nptr_alloc(sizeof(*stb__memtab_root[0]));
  4132. stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT] = z;
  4133. for (i=0; i < 256; ++i)
  4134. z->children[i] = 0;
  4135. }
  4136. f = (stb__memory_leaf *) stb__nptr_alloc(sizeof(*f));
  4137. z->children[STB__NPTR_NODE_OFFSET(address)] = f;
  4138. f->pointers = NULL;
  4139. f->targets = NULL;
  4140. return f;
  4141. }
  4142. static stb__nptr_target *stb__nptr_find_target(void *target, int force)
  4143. {
  4144. stb__memory_leaf *p = stb__nptr_find_leaf(target);
  4145. if (p) {
  4146. stb__nptr_target *t = p->targets;
  4147. while (t) {
  4148. if (t->ptr == target)
  4149. return t;
  4150. t = t->next_in_block;
  4151. }
  4152. }
  4153. if (force) {
  4154. stb__nptr_target *t = (stb__nptr_target*) stb__nptr_alloc(sizeof(*t));
  4155. if (!p) p = stb__nptr_make_leaf(target);
  4156. t->ptr = target;
  4157. t->first = NULL;
  4158. t->next_in_block = p->targets;
  4159. p->targets = t;
  4160. return t;
  4161. } else
  4162. return NULL;
  4163. }
  4164. static stb__nptr *stb__nptr_find_pointer(void *ptr, int force)
  4165. {
  4166. stb__memory_leaf *p = stb__nptr_find_leaf(ptr);
  4167. if (p) {
  4168. stb__nptr *t = p->pointers;
  4169. while (t) {
  4170. if (t->ptr == ptr)
  4171. return t;
  4172. t = t->next_in_block;
  4173. }
  4174. }
  4175. if (force) {
  4176. stb__nptr *t = (stb__nptr *) stb__nptr_alloc(sizeof(*t));
  4177. if (!p) p = stb__nptr_make_leaf(ptr);
  4178. t->ptr = ptr;
  4179. t->next = NULL;
  4180. t->prev = NULL;
  4181. t->next_in_block = p->pointers;
  4182. p->pointers = t;
  4183. return t;
  4184. } else
  4185. return NULL;
  4186. }
  4187. void stb_nptr_set(void *address_of_pointer, void *value_to_write)
  4188. {
  4189. if (*(void **)address_of_pointer != value_to_write) {
  4190. *(void **) address_of_pointer = value_to_write;
  4191. stb_nptr_didset(address_of_pointer);
  4192. }
  4193. }
  4194. void stb_nptr_didset(void *address_of_pointer)
  4195. {
  4196. // first unlink from old chain
  4197. void *new_address;
  4198. stb__nptr *p = stb__nptr_find_pointer(address_of_pointer, 1); // force building if doesn't exist
  4199. if (p->prev) { // if p->prev is NULL, we just built it, or it was NULL
  4200. *(p->prev) = p->next;
  4201. if (p->next) p->next->prev = p->prev;
  4202. }
  4203. // now add to new chain
  4204. new_address = *(void **)address_of_pointer;
  4205. if (new_address != NULL) {
  4206. stb__nptr_target *t = stb__nptr_find_target(new_address, 1);
  4207. p->next = t->first;
  4208. if (p->next) p->next->prev = &p->next;
  4209. p->prev = &t->first;
  4210. t->first = p;
  4211. } else {
  4212. p->prev = NULL;
  4213. p->next = NULL;
  4214. }
  4215. }
  4216. void stb__nptr_block(void *address, int len, void (*function)(stb__memory_leaf *f, int datum, void *start, void *end), int datum)
  4217. {
  4218. void *end_address = (void *) ((char *) address + len - 1);
  4219. stb__memory_node *n;
  4220. stb_uint32 start = (stb_uint32) address;
  4221. stb_uint32 end = start + len - 1;
  4222. int b0 = start >> STB__NPTR_ROOT_SHIFT;
  4223. int b1 = end >> STB__NPTR_ROOT_SHIFT;
  4224. int b=b0,i,e0,e1;
  4225. e0 = STB__NPTR_NODE_OFFSET(start);
  4226. if (datum <= 0) {
  4227. // first block
  4228. n = stb__memtab_root[b0];
  4229. if (n) {
  4230. if (b0 != b1)
  4231. e1 = STB__NPTR_NODE_NUM-1;
  4232. else
  4233. e1 = STB__NPTR_NODE_OFFSET(end);
  4234. for (i=e0; i <= e1; ++i)
  4235. if (n->children[i])
  4236. function(n->children[i], datum, address, end_address);
  4237. }
  4238. if (b1 > b0) {
  4239. // blocks other than the first and last block
  4240. for (b=b0+1; b < b1; ++b) {
  4241. n = stb__memtab_root[b];
  4242. if (n)
  4243. for (i=0; i <= STB__NPTR_NODE_NUM-1; ++i)
  4244. if (n->children[i])
  4245. function(n->children[i], datum, address, end_address);
  4246. }
  4247. // last block
  4248. n = stb__memtab_root[b1];
  4249. if (n) {
  4250. e1 = STB__NPTR_NODE_OFFSET(end);
  4251. for (i=0; i <= e1; ++i)
  4252. if (n->children[i])
  4253. function(n->children[i], datum, address, end_address);
  4254. }
  4255. }
  4256. } else {
  4257. if (b1 > b0) {
  4258. // last block
  4259. n = stb__memtab_root[b1];
  4260. if (n) {
  4261. e1 = STB__NPTR_NODE_OFFSET(end);
  4262. for (i=e1; i >= 0; --i)
  4263. if (n->children[i])
  4264. function(n->children[i], datum, address, end_address);
  4265. }
  4266. // blocks other than the first and last block
  4267. for (b=b1-1; b > b0; --b) {
  4268. n = stb__memtab_root[b];
  4269. if (n)
  4270. for (i=STB__NPTR_NODE_NUM-1; i >= 0; --i)
  4271. if (n->children[i])
  4272. function(n->children[i], datum, address, end_address);
  4273. }
  4274. }
  4275. // first block
  4276. n = stb__memtab_root[b0];
  4277. if (n) {
  4278. if (b0 != b1)
  4279. e1 = STB__NPTR_NODE_NUM-1;
  4280. else
  4281. e1 = STB__NPTR_NODE_OFFSET(end);
  4282. for (i=e1; i >= e0; --i)
  4283. if (n->children[i])
  4284. function(n->children[i], datum, address, end_address);
  4285. }
  4286. }
  4287. }
  4288. static void stb__nptr_delete_pointers(stb__memory_leaf *f, int offset, void *start, void *end)
  4289. {
  4290. stb__nptr **p = &f->pointers;
  4291. while (*p) {
  4292. stb__nptr *n = *p;
  4293. if (n->ptr >= start && n->ptr <= end) {
  4294. // unlink
  4295. if (n->prev) {
  4296. *(n->prev) = n->next;
  4297. if (n->next) n->next->prev = n->prev;
  4298. }
  4299. *p = n->next_in_block;
  4300. stb__nptr_free(n);
  4301. } else
  4302. p = &(n->next_in_block);
  4303. }
  4304. }
  4305. static void stb__nptr_delete_targets(stb__memory_leaf *f, int offset, void *start, void *end)
  4306. {
  4307. stb__nptr_target **p = &f->targets;
  4308. while (*p) {
  4309. stb__nptr_target *n = *p;
  4310. if (n->ptr >= start && n->ptr <= end) {
  4311. // null pointers
  4312. stb__nptr *z = n->first;
  4313. while (z) {
  4314. stb__nptr *y = z->next;
  4315. z->prev = NULL;
  4316. z->next = NULL;
  4317. *(void **) z->ptr = NULL;
  4318. z = y;
  4319. }
  4320. // unlink this target
  4321. *p = n->next_in_block;
  4322. stb__nptr_free(n);
  4323. } else
  4324. p = &(n->next_in_block);
  4325. }
  4326. }
  4327. void stb_nptr_didfree(void *address_being_freed, int len)
  4328. {
  4329. // step one: delete all pointers in this block
  4330. stb__nptr_block(address_being_freed, len, stb__nptr_delete_pointers, 0);
  4331. // step two: NULL all pointers to this block; do this second to avoid NULLing deleted pointers
  4332. stb__nptr_block(address_being_freed, len, stb__nptr_delete_targets, 0);
  4333. }
  4334. void stb_nptr_free(void *address_being_freed, int len)
  4335. {
  4336. free(address_being_freed);
  4337. stb_nptr_didfree(address_being_freed, len);
  4338. }
  4339. static void stb__nptr_move_targets(stb__memory_leaf *f, int offset, void *start, void *end)
  4340. {
  4341. stb__nptr_target **t = &f->targets;
  4342. while (*t) {
  4343. stb__nptr_target *n = *t;
  4344. if (n->ptr >= start && n->ptr <= end) {
  4345. stb__nptr *z;
  4346. stb__memory_leaf *f;
  4347. // unlink n
  4348. *t = n->next_in_block;
  4349. // update n to new address
  4350. n->ptr = (void *) ((char *) n->ptr + offset);
  4351. f = stb__nptr_find_leaf(n->ptr);
  4352. if (!f) f = stb__nptr_make_leaf(n->ptr);
  4353. n->next_in_block = f->targets;
  4354. f->targets = n;
  4355. // now go through all pointers and make them point here
  4356. z = n->first;
  4357. while (z) {
  4358. *(void**) z->ptr = n->ptr;
  4359. z = z->next;
  4360. }
  4361. } else
  4362. t = &(n->next_in_block);
  4363. }
  4364. }
  4365. static void stb__nptr_move_pointers(stb__memory_leaf *f, int offset, void *start, void *end)
  4366. {
  4367. stb__nptr **p = &f->pointers;
  4368. while (*p) {
  4369. stb__nptr *n = *p;
  4370. if (n->ptr >= start && n->ptr <= end) {
  4371. // unlink
  4372. *p = n->next_in_block;
  4373. n->ptr = (void *) ((int) n->ptr + offset);
  4374. // move to new block
  4375. f = stb__nptr_find_leaf(n->ptr);
  4376. if (!f) f = stb__nptr_make_leaf(n->ptr);
  4377. n->next_in_block = f->pointers;
  4378. f->pointers = n;
  4379. } else
  4380. p = &(n->next_in_block);
  4381. }
  4382. }
  4383. void stb_nptr_realloc(void *new_address, void *old_address, int len)
  4384. {
  4385. if (new_address == old_address) return;
  4386. // have to move the pointers first, because moving the targets
  4387. // requires writing to the pointers-to-the-targets, and if some of those moved too,
  4388. // we need to make sure we don't write to the old memory
  4389. // step one: move all pointers within the block
  4390. stb__nptr_block(old_address, len, stb__nptr_move_pointers, (char *) new_address - (char *) old_address);
  4391. // step two: move all targets within the block
  4392. stb__nptr_block(old_address, len, stb__nptr_move_targets, (char *) new_address - (char *) old_address);
  4393. }
  4394. void stb_nptr_move(void *new_address, void *old_address)
  4395. {
  4396. stb_nptr_realloc(new_address, old_address, 1);
  4397. }
  4398. void stb_nptr_recache(void)
  4399. {
  4400. int i,j;
  4401. for (i=0; i < STB__NPTR_ROOT_NUM; ++i)
  4402. if (stb__memtab_root[i])
  4403. for (j=0; j < STB__NPTR_NODE_NUM; ++j)
  4404. if (stb__memtab_root[i]->children[j]) {
  4405. stb__nptr *p = stb__memtab_root[i]->children[j]->pointers;
  4406. while (p) {
  4407. stb_nptr_didset(p->ptr);
  4408. p = p->next_in_block;
  4409. }
  4410. }
  4411. }
  4412. #endif // STB_DEFINE
  4413. #endif // STB_NPTR
  4414. //////////////////////////////////////////////////////////////////////////////
  4415. //
  4416. // File Processing
  4417. //
  4418. #ifdef _MSC_VER
  4419. #define stb_rename(x,y) _wrename((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))
  4420. #define stb_mktemp _mktemp
  4421. #else
  4422. #define stb_mktemp mktemp
  4423. #define stb_rename rename
  4424. #endif
  4425. STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v);
  4426. STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f);
  4427. STB_EXTERN int stb_size_varlen64(stb_uint64 v);
  4428. #define stb_filec (char *) stb_file
  4429. #define stb_fileu (unsigned char *) stb_file
  4430. STB_EXTERN void * stb_file(char *filename, size_t *length);
  4431. STB_EXTERN void * stb_file_max(char *filename, size_t *length);
  4432. STB_EXTERN size_t stb_filelen(FILE *f);
  4433. STB_EXTERN int stb_filewrite(char *filename, void *data, size_t length);
  4434. STB_EXTERN int stb_filewritestr(char *filename, char *data);
  4435. STB_EXTERN char ** stb_stringfile(char *filename, int *len);
  4436. STB_EXTERN char ** stb_stringfile_trimmed(char *name, int *len, char comm);
  4437. STB_EXTERN char * stb_fgets(char *buffer, int buflen, FILE *f);
  4438. STB_EXTERN char * stb_fgets_malloc(FILE *f);
  4439. STB_EXTERN int stb_fexists(char *filename);
  4440. STB_EXTERN int stb_fcmp(char *s1, char *s2);
  4441. STB_EXTERN int stb_feq(char *s1, char *s2);
  4442. STB_EXTERN time_t stb_ftimestamp(char *filename);
  4443. STB_EXTERN int stb_fullpath(char *abs, int abs_size, char *rel);
  4444. STB_EXTERN FILE * stb_fopen(char *filename, char *mode);
  4445. STB_EXTERN int stb_fclose(FILE *f, int keep);
  4446. enum
  4447. {
  4448. stb_keep_no = 0,
  4449. stb_keep_yes = 1,
  4450. stb_keep_if_different = 2,
  4451. };
  4452. STB_EXTERN int stb_copyfile(char *src, char *dest);
  4453. STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v);
  4454. STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f);
  4455. STB_EXTERN int stb_size_varlen64(stb_uint64 v);
  4456. STB_EXTERN void stb_fwrite32(FILE *f, stb_uint32 datum);
  4457. STB_EXTERN void stb_fput_varlen (FILE *f, int v);
  4458. STB_EXTERN void stb_fput_varlenu(FILE *f, unsigned int v);
  4459. STB_EXTERN int stb_fget_varlen (FILE *f);
  4460. STB_EXTERN stb_uint stb_fget_varlenu(FILE *f);
  4461. STB_EXTERN void stb_fput_ranged (FILE *f, int v, int b, stb_uint n);
  4462. STB_EXTERN int stb_fget_ranged (FILE *f, int b, stb_uint n);
  4463. STB_EXTERN int stb_size_varlen (int v);
  4464. STB_EXTERN int stb_size_varlenu(unsigned int v);
  4465. STB_EXTERN int stb_size_ranged (int b, stb_uint n);
  4466. STB_EXTERN int stb_fread(void *data, size_t len, size_t count, void *f);
  4467. STB_EXTERN int stb_fwrite(void *data, size_t len, size_t count, void *f);
  4468. #if 0
  4469. typedef struct
  4470. {
  4471. FILE *base_file;
  4472. char *buffer;
  4473. int buffer_size;
  4474. int buffer_off;
  4475. int buffer_left;
  4476. } STBF;
  4477. STB_EXTERN STBF *stb_tfopen(char *filename, char *mode);
  4478. STB_EXTERN int stb_tfread(void *data, size_t len, size_t count, STBF *f);
  4479. STB_EXTERN int stb_tfwrite(void *data, size_t len, size_t count, STBF *f);
  4480. #endif
  4481. #ifdef STB_DEFINE
  4482. #if 0
  4483. STBF *stb_tfopen(char *filename, char *mode)
  4484. {
  4485. STBF *z;
  4486. FILE *f = fopen(filename, mode);
  4487. if (!f) return NULL;
  4488. z = (STBF *) malloc(sizeof(*z));
  4489. if (!z) { fclose(f); return NULL; }
  4490. z->base_file = f;
  4491. if (!strcmp(mode, "rb") || !strcmp(mode, "wb")) {
  4492. z->buffer_size = 4096;
  4493. z->buffer_off = z->buffer_size;
  4494. z->buffer_left = 0;
  4495. z->buffer = malloc(z->buffer_size);
  4496. if (!z->buffer) { free(z); fclose(f); return NULL; }
  4497. } else {
  4498. z->buffer = 0;
  4499. z->buffer_size = 0;
  4500. z->buffer_left = 0;
  4501. }
  4502. return z;
  4503. }
  4504. int stb_tfread(void *data, size_t len, size_t count, STBF *f)
  4505. {
  4506. int total = len*count, done=0;
  4507. if (!total) return 0;
  4508. if (total <= z->buffer_left) {
  4509. memcpy(data, z->buffer + z->buffer_off, total);
  4510. z->buffer_off += total;
  4511. z->buffer_left -= total;
  4512. return count;
  4513. } else {
  4514. char *out = (char *) data;
  4515. // consume all buffered data
  4516. memcpy(data, z->buffer + z->buffer_off, z->buffer_left);
  4517. done = z->buffer_left;
  4518. out += z->buffer_left;
  4519. z->buffer_left=0;
  4520. if (total-done > (z->buffer_size >> 1)) {
  4521. done += fread(out
  4522. }
  4523. }
  4524. }
  4525. #endif
  4526. void stb_fwrite32(FILE *f, stb_uint32 x)
  4527. {
  4528. fwrite(&x, 4, 1, f);
  4529. }
  4530. #if defined(_MSC_VER) || defined(__MINGW32__)
  4531. #define stb__stat _stat
  4532. #else
  4533. #define stb__stat stat
  4534. #endif
  4535. int stb_fexists(char *filename)
  4536. {
  4537. struct stb__stat buf;
  4538. return stb__windows(
  4539. _wstat((const wchar_t *)stb__from_utf8(filename), &buf),
  4540. stat(filename,&buf)
  4541. ) == 0;
  4542. }
  4543. time_t stb_ftimestamp(char *filename)
  4544. {
  4545. struct stb__stat buf;
  4546. if (stb__windows(
  4547. _wstat((const wchar_t *)stb__from_utf8(filename), &buf),
  4548. stat(filename,&buf)
  4549. ) == 0)
  4550. {
  4551. return buf.st_mtime;
  4552. } else {
  4553. return 0;
  4554. }
  4555. }
  4556. size_t stb_filelen(FILE *f)
  4557. {
  4558. size_t len, pos;
  4559. pos = ftell(f);
  4560. fseek(f, 0, SEEK_END);
  4561. len = ftell(f);
  4562. fseek(f, pos, SEEK_SET);
  4563. return len;
  4564. }
  4565. void *stb_file(char *filename, size_t *length)
  4566. {
  4567. FILE *f = stb__fopen(filename, "rb");
  4568. char *buffer;
  4569. size_t len, len2;
  4570. if (!f) return NULL;
  4571. len = stb_filelen(f);
  4572. buffer = (char *) malloc(len+2); // nul + extra
  4573. len2 = fread(buffer, 1, len, f);
  4574. if (len2 == len) {
  4575. if (length) *length = len;
  4576. buffer[len] = 0;
  4577. } else {
  4578. free(buffer);
  4579. buffer = NULL;
  4580. }
  4581. fclose(f);
  4582. return buffer;
  4583. }
  4584. int stb_filewrite(char *filename, void *data, size_t length)
  4585. {
  4586. FILE *f = stb_fopen(filename, "wb");
  4587. if (f) {
  4588. unsigned char *data_ptr = (unsigned char *) data;
  4589. size_t remaining = length;
  4590. while (remaining > 0) {
  4591. size_t len2 = remaining > 65536 ? 65536 : remaining;
  4592. size_t len3 = fwrite(data_ptr, 1, len2, f);
  4593. if (len2 != len3) {
  4594. fprintf(stderr, "Failed while writing %s\n", filename);
  4595. break;
  4596. }
  4597. remaining -= len2;
  4598. data_ptr += len2;
  4599. }
  4600. stb_fclose(f, stb_keep_if_different);
  4601. }
  4602. return f != NULL;
  4603. }
  4604. int stb_filewritestr(char *filename, char *data)
  4605. {
  4606. return stb_filewrite(filename, data, strlen(data));
  4607. }
  4608. void * stb_file_max(char *filename, size_t *length)
  4609. {
  4610. FILE *f = stb__fopen(filename, "rb");
  4611. char *buffer;
  4612. size_t len, maxlen;
  4613. if (!f) return NULL;
  4614. maxlen = *length;
  4615. buffer = (char *) malloc(maxlen+1);
  4616. len = fread(buffer, 1, maxlen, f);
  4617. buffer[len] = 0;
  4618. fclose(f);
  4619. *length = len;
  4620. return buffer;
  4621. }
  4622. char ** stb_stringfile(char *filename, int *plen)
  4623. {
  4624. FILE *f = stb__fopen(filename, "rb");
  4625. char *buffer, **list=NULL, *s;
  4626. size_t len, count, i;
  4627. if (!f) return NULL;
  4628. len = stb_filelen(f);
  4629. buffer = (char *) malloc(len+1);
  4630. len = fread(buffer, 1, len, f);
  4631. buffer[len] = 0;
  4632. fclose(f);
  4633. // two passes through: first time count lines, second time set them
  4634. for (i=0; i < 2; ++i) {
  4635. s = buffer;
  4636. if (i == 1)
  4637. list[0] = s;
  4638. count = 1;
  4639. while (*s) {
  4640. if (*s == '\n' || *s == '\r') {
  4641. // detect if both cr & lf are together
  4642. int crlf = (s[0] + s[1]) == ('\n' + '\r');
  4643. if (i == 1) *s = 0;
  4644. if (crlf) ++s;
  4645. if (s[1]) { // it's not over yet
  4646. if (i == 1) list[count] = s+1;
  4647. ++count;
  4648. }
  4649. }
  4650. ++s;
  4651. }
  4652. if (i == 0) {
  4653. list = (char **) malloc(sizeof(*list) * (count+1) + len+1);
  4654. if (!list) return NULL;
  4655. list[count] = 0;
  4656. // recopy the file so there's just a single allocation to free
  4657. memcpy(&list[count+1], buffer, len+1);
  4658. free(buffer);
  4659. buffer = (char *) &list[count+1];
  4660. if (plen) *plen = count;
  4661. }
  4662. }
  4663. return list;
  4664. }
  4665. char ** stb_stringfile_trimmed(char *name, int *len, char comment)
  4666. {
  4667. int i,n,o=0;
  4668. char **s = stb_stringfile(name, &n);
  4669. if (s == NULL) return NULL;
  4670. for (i=0; i < n; ++i) {
  4671. char *p = stb_skipwhite(s[i]);
  4672. if (*p && *p != comment)
  4673. s[o++] = p;
  4674. }
  4675. s[o] = NULL;
  4676. if (len) *len = o;
  4677. return s;
  4678. }
  4679. char * stb_fgets(char *buffer, int buflen, FILE *f)
  4680. {
  4681. char *p;
  4682. buffer[0] = 0;
  4683. p = fgets(buffer, buflen, f);
  4684. if (p) {
  4685. int n = strlen(p)-1;
  4686. if (n >= 0)
  4687. if (p[n] == '\n')
  4688. p[n] = 0;
  4689. }
  4690. return p;
  4691. }
  4692. char * stb_fgets_malloc(FILE *f)
  4693. {
  4694. // avoid reallocing for small strings
  4695. char quick_buffer[800];
  4696. quick_buffer[sizeof(quick_buffer)-2] = 0;
  4697. if (!fgets(quick_buffer, sizeof(quick_buffer), f))
  4698. return NULL;
  4699. if (quick_buffer[sizeof(quick_buffer)-2] == 0) {
  4700. int n = strlen(quick_buffer);
  4701. if (n > 0 && quick_buffer[n-1] == '\n')
  4702. quick_buffer[n-1] = 0;
  4703. return strdup(quick_buffer);
  4704. } else {
  4705. char *p;
  4706. char *a = strdup(quick_buffer);
  4707. int len = sizeof(quick_buffer)-1;
  4708. while (!feof(f)) {
  4709. if (a[len-1] == '\n') break;
  4710. a = (char *) realloc(a, len*2);
  4711. p = &a[len];
  4712. p[len-2] = 0;
  4713. if (!fgets(p, len, f))
  4714. break;
  4715. if (p[len-2] == 0) {
  4716. len += strlen(p);
  4717. break;
  4718. }
  4719. len = len + (len-1);
  4720. }
  4721. if (a[len-1] == '\n')
  4722. a[len-1] = 0;
  4723. return a;
  4724. }
  4725. }
  4726. int stb_fullpath(char *abs, int abs_size, char *rel)
  4727. {
  4728. #ifdef _MSC_VER
  4729. return _fullpath(abs, rel, abs_size) != NULL;
  4730. #else
  4731. if (rel[0] == '/' || rel[0] == '~') {
  4732. if ((int) strlen(rel) >= abs_size)
  4733. return 0;
  4734. strcpy(abs,rel);
  4735. return STB_TRUE;
  4736. } else {
  4737. int n;
  4738. getcwd(abs, abs_size);
  4739. n = strlen(abs);
  4740. if (n+(int) strlen(rel)+2 <= abs_size) {
  4741. abs[n] = '/';
  4742. strcpy(abs+n+1, rel);
  4743. return STB_TRUE;
  4744. } else {
  4745. return STB_FALSE;
  4746. }
  4747. }
  4748. #endif
  4749. }
  4750. static int stb_fcmp_core(FILE *f, FILE *g)
  4751. {
  4752. char buf1[1024],buf2[1024];
  4753. int n1,n2, res=0;
  4754. while (1) {
  4755. n1 = fread(buf1, 1, sizeof(buf1), f);
  4756. n2 = fread(buf2, 1, sizeof(buf2), g);
  4757. res = memcmp(buf1,buf2,stb_min(n1,n2));
  4758. if (res)
  4759. break;
  4760. if (n1 != n2) {
  4761. res = n1 < n2 ? -1 : 1;
  4762. break;
  4763. }
  4764. if (n1 == 0)
  4765. break;
  4766. }
  4767. fclose(f);
  4768. fclose(g);
  4769. return res;
  4770. }
  4771. int stb_fcmp(char *s1, char *s2)
  4772. {
  4773. FILE *f = stb__fopen(s1, "rb");
  4774. FILE *g = stb__fopen(s2, "rb");
  4775. if (f == NULL || g == NULL) {
  4776. if (f) fclose(f);
  4777. if (g) {
  4778. fclose(g);
  4779. return STB_TRUE;
  4780. }
  4781. return f != NULL;
  4782. }
  4783. return stb_fcmp_core(f,g);
  4784. }
  4785. int stb_feq(char *s1, char *s2)
  4786. {
  4787. FILE *f = stb__fopen(s1, "rb");
  4788. FILE *g = stb__fopen(s2, "rb");
  4789. if (f == NULL || g == NULL) {
  4790. if (f) fclose(f);
  4791. if (g) fclose(g);
  4792. return f == g;
  4793. }
  4794. // feq is faster because it shortcuts if they're different length
  4795. if (stb_filelen(f) != stb_filelen(g)) {
  4796. fclose(f);
  4797. fclose(g);
  4798. return 0;
  4799. }
  4800. return !stb_fcmp_core(f,g);
  4801. }
  4802. static stb_ptrmap *stb__files;
  4803. typedef struct
  4804. {
  4805. char *temp_name;
  4806. char *name;
  4807. int errors;
  4808. } stb__file_data;
  4809. FILE * stb_fopen(char *filename, char *mode)
  4810. {
  4811. FILE *f;
  4812. char name_full[4096];
  4813. char temp_full[sizeof(name_full) + 12];
  4814. int p;
  4815. #ifdef _MSC_VER
  4816. int j;
  4817. #endif
  4818. if (mode[0] != 'w' && !strchr(mode, '+'))
  4819. return stb__fopen(filename, mode);
  4820. // save away the full path to the file so if the program
  4821. // changes the cwd everything still works right! unix has
  4822. // better ways to do this, but we have to work in windows
  4823. name_full[0] = '\0'; // stb_fullpath reads name_full[0]
  4824. if (stb_fullpath(name_full, sizeof(name_full), filename)==0)
  4825. return 0;
  4826. // try to generate a temporary file in the same directory
  4827. p = strlen(name_full)-1;
  4828. while (p > 0 && name_full[p] != '/' && name_full[p] != '\\'
  4829. && name_full[p] != ':' && name_full[p] != '~')
  4830. --p;
  4831. ++p;
  4832. memcpy(temp_full, name_full, p);
  4833. #ifdef _MSC_VER
  4834. // try multiple times to make a temp file... just in
  4835. // case some other process makes the name first
  4836. for (j=0; j < 32; ++j) {
  4837. strcpy(temp_full+p, "stmpXXXXXX");
  4838. if (stb_mktemp(temp_full) == NULL)
  4839. return 0;
  4840. f = fopen(temp_full, mode);
  4841. if (f != NULL)
  4842. break;
  4843. }
  4844. #else
  4845. {
  4846. strcpy(temp_full+p, "stmpXXXXXX");
  4847. #ifdef __MINGW32__
  4848. int fd = open(mktemp(temp_full), O_RDWR);
  4849. #else
  4850. int fd = mkstemp(temp_full);
  4851. #endif
  4852. if (fd == -1) return NULL;
  4853. f = fdopen(fd, mode);
  4854. if (f == NULL) {
  4855. unlink(temp_full);
  4856. close(fd);
  4857. return NULL;
  4858. }
  4859. }
  4860. #endif
  4861. if (f != NULL) {
  4862. stb__file_data *d = (stb__file_data *) malloc(sizeof(*d));
  4863. if (!d) { assert(0); /* NOTREACHED */fclose(f); return NULL; }
  4864. if (stb__files == NULL) stb__files = stb_ptrmap_create();
  4865. d->temp_name = strdup(temp_full);
  4866. d->name = strdup(name_full);
  4867. d->errors = 0;
  4868. stb_ptrmap_add(stb__files, f, d);
  4869. return f;
  4870. }
  4871. return NULL;
  4872. }
  4873. int stb_fclose(FILE *f, int keep)
  4874. {
  4875. stb__file_data *d;
  4876. int ok = STB_FALSE;
  4877. if (f == NULL) return 0;
  4878. if (ferror(f))
  4879. keep = stb_keep_no;
  4880. fclose(f);
  4881. if (stb__files && stb_ptrmap_remove(stb__files, f, (void **) &d)) {
  4882. if (stb__files->count == 0) {
  4883. stb_ptrmap_destroy(stb__files);
  4884. stb__files = NULL;
  4885. }
  4886. } else
  4887. return STB_TRUE; // not special
  4888. if (keep == stb_keep_if_different) {
  4889. // check if the files are identical
  4890. if (stb_feq(d->name, d->temp_name)) {
  4891. keep = stb_keep_no;
  4892. ok = STB_TRUE; // report success if no change
  4893. }
  4894. }
  4895. if (keep != stb_keep_no) {
  4896. if (stb_fexists(d->name) && remove(d->name)) {
  4897. // failed to delete old, so don't keep new
  4898. keep = stb_keep_no;
  4899. } else {
  4900. if (!stb_rename(d->temp_name, d->name))
  4901. ok = STB_TRUE;
  4902. else
  4903. keep=stb_keep_no;
  4904. }
  4905. }
  4906. if (keep == stb_keep_no)
  4907. remove(d->temp_name);
  4908. free(d->temp_name);
  4909. free(d->name);
  4910. free(d);
  4911. return ok;
  4912. }
  4913. int stb_copyfile(char *src, char *dest)
  4914. {
  4915. char raw_buffer[1024];
  4916. char *buffer;
  4917. int buf_size = 65536;
  4918. FILE *f, *g;
  4919. // if file already exists at destination, do nothing
  4920. if (stb_feq(src, dest)) return STB_TRUE;
  4921. // open file
  4922. f = stb__fopen(src, "rb");
  4923. if (f == NULL) return STB_FALSE;
  4924. // open file for writing
  4925. g = stb__fopen(dest, "wb");
  4926. if (g == NULL) {
  4927. fclose(f);
  4928. return STB_FALSE;
  4929. }
  4930. buffer = (char *) malloc(buf_size);
  4931. if (buffer == NULL) {
  4932. buffer = raw_buffer;
  4933. buf_size = sizeof(raw_buffer);
  4934. }
  4935. while (!feof(f)) {
  4936. int n = fread(buffer, 1, buf_size, f);
  4937. if (n != 0)
  4938. fwrite(buffer, 1, n, g);
  4939. }
  4940. fclose(f);
  4941. if (buffer != raw_buffer)
  4942. free(buffer);
  4943. fclose(g);
  4944. return STB_TRUE;
  4945. }
  4946. // varlen:
  4947. // v' = (v >> 31) + (v < 0 ? ~v : v)<<1; // small abs(v) => small v'
  4948. // output v as big endian v'+k for v' <= k:
  4949. // 1 byte : v' <= 0x00000080 ( -64 <= v < 64) 7 bits
  4950. // 2 bytes: v' <= 0x00004000 (-8192 <= v < 8192) 14 bits
  4951. // 3 bytes: v' <= 0x00200000 21 bits
  4952. // 4 bytes: v' <= 0x10000000 28 bits
  4953. // the number of most significant 1-bits in the first byte
  4954. // equals the number of bytes after the first
  4955. #define stb__varlen_xform(v) (v<0 ? (~v << 1)+1 : (v << 1))
  4956. int stb_size_varlen(int v) { return stb_size_varlenu(stb__varlen_xform(v)); }
  4957. int stb_size_varlenu(unsigned int v)
  4958. {
  4959. if (v < 0x00000080) return 1;
  4960. if (v < 0x00004000) return 2;
  4961. if (v < 0x00200000) return 3;
  4962. if (v < 0x10000000) return 4;
  4963. return 5;
  4964. }
  4965. void stb_fput_varlen(FILE *f, int v) { stb_fput_varlenu(f, stb__varlen_xform(v)); }
  4966. void stb_fput_varlenu(FILE *f, unsigned int z)
  4967. {
  4968. if (z >= 0x10000000) fputc(0xF0,f);
  4969. if (z >= 0x00200000) fputc((z < 0x10000000 ? 0xE0 : 0)+(z>>24),f);
  4970. if (z >= 0x00004000) fputc((z < 0x00200000 ? 0xC0 : 0)+(z>>16),f);
  4971. if (z >= 0x00000080) fputc((z < 0x00004000 ? 0x80 : 0)+(z>> 8),f);
  4972. fputc(z,f);
  4973. }
  4974. #define stb_fgetc(f) ((unsigned char) fgetc(f))
  4975. int stb_fget_varlen(FILE *f)
  4976. {
  4977. unsigned int z = stb_fget_varlenu(f);
  4978. return (z & 1) ? ~(z>>1) : (z>>1);
  4979. }
  4980. unsigned int stb_fget_varlenu(FILE *f)
  4981. {
  4982. unsigned int z;
  4983. unsigned char d;
  4984. d = stb_fgetc(f);
  4985. if (d >= 0x80) {
  4986. if (d >= 0xc0) {
  4987. if (d >= 0xe0) {
  4988. if (d == 0xf0) z = stb_fgetc(f) << 24;
  4989. else z = (d - 0xe0) << 24;
  4990. z += stb_fgetc(f) << 16;
  4991. }
  4992. else
  4993. z = (d - 0xc0) << 16;
  4994. z += stb_fgetc(f) << 8;
  4995. } else
  4996. z = (d - 0x80) << 8;
  4997. z += stb_fgetc(f);
  4998. } else
  4999. z = d;
  5000. return z;
  5001. }
  5002. stb_uint64 stb_fget_varlen64(FILE *f)
  5003. {
  5004. stb_uint64 z;
  5005. unsigned char d;
  5006. d = stb_fgetc(f);
  5007. if (d >= 0x80) {
  5008. if (d >= 0xc0) {
  5009. if (d >= 0xe0) {
  5010. if (d >= 0xf0) {
  5011. if (d >= 0xf8) {
  5012. if (d >= 0xfc) {
  5013. if (d >= 0xfe) {
  5014. if (d >= 0xff)
  5015. z = (stb_uint64) stb_fgetc(f) << 56;
  5016. else
  5017. z = (stb_uint64) (d - 0xfe) << 56;
  5018. z |= (stb_uint64) stb_fgetc(f) << 48;
  5019. } else z = (stb_uint64) (d - 0xfc) << 48;
  5020. z |= (stb_uint64) stb_fgetc(f) << 40;
  5021. } else z = (stb_uint64) (d - 0xf8) << 40;
  5022. z |= (stb_uint64) stb_fgetc(f) << 32;
  5023. } else z = (stb_uint64) (d - 0xf0) << 32;
  5024. z |= (stb_uint) stb_fgetc(f) << 24;
  5025. } else z = (stb_uint) (d - 0xe0) << 24;
  5026. z |= (stb_uint) stb_fgetc(f) << 16;
  5027. } else z = (stb_uint) (d - 0xc0) << 16;
  5028. z |= (stb_uint) stb_fgetc(f) << 8;
  5029. } else z = (stb_uint) (d - 0x80) << 8;
  5030. z |= stb_fgetc(f);
  5031. } else
  5032. z = d;
  5033. return (z & 1) ? ~(z >> 1) : (z >> 1);
  5034. }
  5035. int stb_size_varlen64(stb_uint64 v)
  5036. {
  5037. if (v < 0x00000080) return 1;
  5038. if (v < 0x00004000) return 2;
  5039. if (v < 0x00200000) return 3;
  5040. if (v < 0x10000000) return 4;
  5041. if (v < STB_IMM_UINT64(0x0000000800000000)) return 5;
  5042. if (v < STB_IMM_UINT64(0x0000040000000000)) return 6;
  5043. if (v < STB_IMM_UINT64(0x0002000000000000)) return 7;
  5044. if (v < STB_IMM_UINT64(0x0100000000000000)) return 8;
  5045. return 9;
  5046. }
  5047. void stb_fput_varlen64(FILE *f, stb_uint64 v)
  5048. {
  5049. stb_uint64 z = stb__varlen_xform(v);
  5050. int first=1;
  5051. if (z >= STB_IMM_UINT64(0x100000000000000)) {
  5052. fputc(0xff,f);
  5053. first=0;
  5054. }
  5055. if (z >= STB_IMM_UINT64(0x02000000000000)) fputc((first ? 0xFE : 0)+(char)(z>>56),f), first=0;
  5056. if (z >= STB_IMM_UINT64(0x00040000000000)) fputc((first ? 0xFC : 0)+(char)(z>>48),f), first=0;
  5057. if (z >= STB_IMM_UINT64(0x00000800000000)) fputc((first ? 0xF8 : 0)+(char)(z>>40),f), first=0;
  5058. if (z >= STB_IMM_UINT64(0x00000010000000)) fputc((first ? 0xF0 : 0)+(char)(z>>32),f), first=0;
  5059. if (z >= STB_IMM_UINT64(0x00000000200000)) fputc((first ? 0xE0 : 0)+(char)(z>>24),f), first=0;
  5060. if (z >= STB_IMM_UINT64(0x00000000004000)) fputc((first ? 0xC0 : 0)+(char)(z>>16),f), first=0;
  5061. if (z >= STB_IMM_UINT64(0x00000000000080)) fputc((first ? 0x80 : 0)+(char)(z>> 8),f), first=0;
  5062. fputc((char)z,f);
  5063. }
  5064. void stb_fput_ranged(FILE *f, int v, int b, stb_uint n)
  5065. {
  5066. v -= b;
  5067. if (n <= (1 << 31))
  5068. assert((stb_uint) v < n);
  5069. if (n > (1 << 24)) fputc(v >> 24, f);
  5070. if (n > (1 << 16)) fputc(v >> 16, f);
  5071. if (n > (1 << 8)) fputc(v >> 8, f);
  5072. fputc(v,f);
  5073. }
  5074. int stb_fget_ranged(FILE *f, int b, stb_uint n)
  5075. {
  5076. unsigned int v=0;
  5077. if (n > (1 << 24)) v += stb_fgetc(f) << 24;
  5078. if (n > (1 << 16)) v += stb_fgetc(f) << 16;
  5079. if (n > (1 << 8)) v += stb_fgetc(f) << 8;
  5080. v += stb_fgetc(f);
  5081. return b+v;
  5082. }
  5083. int stb_size_ranged(int b, stb_uint n)
  5084. {
  5085. if (n > (1 << 24)) return 4;
  5086. if (n > (1 << 16)) return 3;
  5087. if (n > (1 << 8)) return 2;
  5088. return 1;
  5089. }
  5090. void stb_fput_string(FILE *f, char *s)
  5091. {
  5092. int len = strlen(s);
  5093. stb_fput_varlenu(f, len);
  5094. fwrite(s, 1, len, f);
  5095. }
  5096. // inverse of the above algorithm
  5097. char *stb_fget_string(FILE *f, void *p)
  5098. {
  5099. char *s;
  5100. int len = stb_fget_varlenu(f);
  5101. if (len > 4096) return NULL;
  5102. s = p ? stb_malloc_string(p, len+1) : (char *) malloc(len+1);
  5103. fread(s, 1, len, f);
  5104. s[len] = 0;
  5105. return s;
  5106. }
  5107. char *stb_strdup(char *str, void *pool)
  5108. {
  5109. int len = strlen(str);
  5110. char *p = stb_malloc_string(pool, len+1);
  5111. strcpy(p, str);
  5112. return p;
  5113. }
  5114. // strip the trailing '/' or '\\' from a directory so we can refer to it
  5115. // as a file for _stat()
  5116. char *stb_strip_final_slash(char *t)
  5117. {
  5118. if (t[0]) {
  5119. char *z = t + strlen(t) - 1;
  5120. // *z is the last character
  5121. if (*z == '\\' || *z == '/')
  5122. if (z != t+2 || t[1] != ':') // but don't strip it if it's e.g. "c:/"
  5123. *z = 0;
  5124. if (*z == '\\')
  5125. *z = '/'; // canonicalize to make sure it matches db
  5126. }
  5127. return t;
  5128. }
  5129. char *stb_strip_final_slash_regardless(char *t)
  5130. {
  5131. if (t[0]) {
  5132. char *z = t + strlen(t) - 1;
  5133. // *z is the last character
  5134. if (*z == '\\' || *z == '/')
  5135. *z = 0;
  5136. if (*z == '\\')
  5137. *z = '/'; // canonicalize to make sure it matches db
  5138. }
  5139. return t;
  5140. }
  5141. #endif
  5142. //////////////////////////////////////////////////////////////////////////////
  5143. //
  5144. // Options parsing
  5145. //
  5146. STB_EXTERN char **stb_getopt_param(int *argc, char **argv, char *param);
  5147. STB_EXTERN char **stb_getopt(int *argc, char **argv);
  5148. STB_EXTERN void stb_getopt_free(char **opts);
  5149. #ifdef STB_DEFINE
  5150. void stb_getopt_free(char **opts)
  5151. {
  5152. int i;
  5153. char ** o2 = opts;
  5154. for (i=0; i < stb_arr_len(o2); ++i)
  5155. free(o2[i]);
  5156. stb_arr_free(o2);
  5157. }
  5158. char **stb_getopt(int *argc, char **argv)
  5159. {
  5160. return stb_getopt_param(argc, argv, "");
  5161. }
  5162. char **stb_getopt_param(int *argc, char **argv, char *param)
  5163. {
  5164. char ** opts=NULL;
  5165. int i,j=1;
  5166. for (i=1; i < *argc; ++i) {
  5167. if (argv[i][0] != '-') {
  5168. argv[j++] = argv[i];
  5169. } else {
  5170. if (argv[i][1] == 0) { // plain - == don't parse further options
  5171. ++i;
  5172. while (i < *argc)
  5173. argv[j++] = argv[i++];
  5174. break;
  5175. } else {
  5176. int k;
  5177. char *q = argv[i]; // traverse options list
  5178. for (k=1; q[k]; ++k) {
  5179. char *s;
  5180. if (strchr(param, q[k])) { // does it take a parameter?
  5181. char *t = &q[k+1], z = q[k];
  5182. int len=0;
  5183. if (*t == 0) {
  5184. if (i == *argc-1) { // takes a parameter, but none found
  5185. *argc = 0;
  5186. stb_getopt_free(opts);
  5187. return NULL;
  5188. }
  5189. t = argv[++i];
  5190. } else
  5191. k += strlen(t);
  5192. len = strlen(t);
  5193. s = (char *) malloc(len+2);
  5194. if (!s) return NULL;
  5195. s[0] = z;
  5196. strcpy(s+1, t);
  5197. } else {
  5198. // no parameter
  5199. s = (char *) malloc(2);
  5200. if (!s) return NULL;
  5201. s[0] = q[k];
  5202. s[1] = 0;
  5203. }
  5204. stb_arr_push(opts, s);
  5205. }
  5206. }
  5207. }
  5208. }
  5209. stb_arr_push(opts, NULL);
  5210. *argc = j;
  5211. return opts;
  5212. }
  5213. #endif
  5214. //////////////////////////////////////////////////////////////////////////////
  5215. //
  5216. // Portable directory reading
  5217. //
  5218. STB_EXTERN char **stb_readdir_files (char *dir);
  5219. STB_EXTERN char **stb_readdir_files_mask(char *dir, char *wild);
  5220. STB_EXTERN char **stb_readdir_subdirs(char *dir);
  5221. STB_EXTERN char **stb_readdir_subdirs_mask(char *dir, char *wild);
  5222. STB_EXTERN void stb_readdir_free (char **files);
  5223. STB_EXTERN char **stb_readdir_recursive(char *dir, char *filespec);
  5224. STB_EXTERN void stb_delete_directory_recursive(char *dir);
  5225. #ifdef STB_DEFINE
  5226. #ifdef _MSC_VER
  5227. #include <io.h>
  5228. #else
  5229. #include <unistd.h>
  5230. #include <dirent.h>
  5231. #endif
  5232. void stb_readdir_free(char **files)
  5233. {
  5234. char **f2 = files;
  5235. int i;
  5236. for (i=0; i < stb_arr_len(f2); ++i)
  5237. free(f2[i]);
  5238. stb_arr_free(f2);
  5239. }
  5240. static int isdotdirname(char *name)
  5241. {
  5242. if (name[0] == '.')
  5243. return (name[1] == '.') ? !name[2] : !name[1];
  5244. return 0;
  5245. }
  5246. STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);
  5247. static char **readdir_raw(char *dir, int return_subdirs, char *mask)
  5248. {
  5249. char **results = NULL;
  5250. char buffer[4096], with_slash[4096];
  5251. size_t n;
  5252. #ifdef _MSC_VER
  5253. stb__wchar *ws;
  5254. struct _wfinddata_t data;
  5255. #ifdef _WIN64
  5256. const intptr_t none = -1;
  5257. intptr_t z;
  5258. #else
  5259. const long none = -1;
  5260. long z;
  5261. #endif
  5262. #else // !_MSC_VER
  5263. const DIR *none = NULL;
  5264. DIR *z;
  5265. #endif
  5266. n = stb_strscpy(buffer,dir,sizeof(buffer));
  5267. if (!n || n >= sizeof(buffer))
  5268. return NULL;
  5269. stb_fixpath(buffer);
  5270. n--;
  5271. if (n > 0 && (buffer[n-1] != '/')) {
  5272. buffer[n++] = '/';
  5273. }
  5274. buffer[n] = 0;
  5275. if (!stb_strscpy(with_slash,buffer,sizeof(with_slash)))
  5276. return NULL;
  5277. #ifdef _MSC_VER
  5278. if (!stb_strscpy(buffer+n,"*.*",sizeof(buffer)-n))
  5279. return NULL;
  5280. ws = stb__from_utf8(buffer);
  5281. z = _wfindfirst((const wchar_t *)ws, &data);
  5282. #else
  5283. z = opendir(dir);
  5284. #endif
  5285. if (z != none) {
  5286. int nonempty = STB_TRUE;
  5287. #ifndef _MSC_VER
  5288. struct dirent *data = readdir(z);
  5289. nonempty = (data != NULL);
  5290. #endif
  5291. if (nonempty) {
  5292. do {
  5293. int is_subdir;
  5294. #ifdef _MSC_VER
  5295. char *name = stb__to_utf8((stb__wchar *)data.name);
  5296. if (name == NULL) {
  5297. fprintf(stderr, "%s to convert '%S' to %s!\n", "Unable", data.name, "utf8");
  5298. continue;
  5299. }
  5300. is_subdir = !!(data.attrib & _A_SUBDIR);
  5301. #else
  5302. char *name = data->d_name;
  5303. if (!stb_strscpy(buffer+n,name,sizeof(buffer)-n))
  5304. break;
  5305. // Could follow DT_LNK, but would need to check for recursive links.
  5306. is_subdir = !!(data->d_type & DT_DIR);
  5307. #endif
  5308. if (is_subdir == return_subdirs) {
  5309. if (!is_subdir || !isdotdirname(name)) {
  5310. if (!mask || stb_wildmatchi(mask, name)) {
  5311. char buffer[4096],*p=buffer;
  5312. if ( stb_snprintf(buffer, sizeof(buffer), "%s%s", with_slash, name) < 0 )
  5313. break;
  5314. if (buffer[0] == '.' && buffer[1] == '/')
  5315. p = buffer+2;
  5316. stb_arr_push(results, strdup(p));
  5317. }
  5318. }
  5319. }
  5320. }
  5321. #ifdef _MSC_VER
  5322. while (0 == _wfindnext(z, &data));
  5323. #else
  5324. while ((data = readdir(z)) != NULL);
  5325. #endif
  5326. }
  5327. #ifdef _MSC_VER
  5328. _findclose(z);
  5329. #else
  5330. closedir(z);
  5331. #endif
  5332. }
  5333. return results;
  5334. }
  5335. char **stb_readdir_files (char *dir) { return readdir_raw(dir, 0, NULL); }
  5336. char **stb_readdir_subdirs(char *dir) { return readdir_raw(dir, 1, NULL); }
  5337. char **stb_readdir_files_mask(char *dir, char *wild) { return readdir_raw(dir, 0, wild); }
  5338. char **stb_readdir_subdirs_mask(char *dir, char *wild) { return readdir_raw(dir, 1, wild); }
  5339. int stb__rec_max=0x7fffffff;
  5340. static char **stb_readdir_rec(char **sofar, char *dir, char *filespec)
  5341. {
  5342. char **files;
  5343. char ** dirs;
  5344. char **p;
  5345. if (stb_arr_len(sofar) >= stb__rec_max) return sofar;
  5346. files = stb_readdir_files_mask(dir, filespec);
  5347. stb_arr_for(p, files) {
  5348. stb_arr_push(sofar, strdup(*p));
  5349. if (stb_arr_len(sofar) >= stb__rec_max) break;
  5350. }
  5351. stb_readdir_free(files);
  5352. if (stb_arr_len(sofar) >= stb__rec_max) return sofar;
  5353. dirs = stb_readdir_subdirs(dir);
  5354. stb_arr_for(p, dirs)
  5355. sofar = stb_readdir_rec(sofar, *p, filespec);
  5356. stb_readdir_free(dirs);
  5357. return sofar;
  5358. }
  5359. char **stb_readdir_recursive(char *dir, char *filespec)
  5360. {
  5361. return stb_readdir_rec(NULL, dir, filespec);
  5362. }
  5363. void stb_delete_directory_recursive(char *dir)
  5364. {
  5365. char **list = stb_readdir_subdirs(dir);
  5366. int i;
  5367. for (i=0; i < stb_arr_len(list); ++i)
  5368. stb_delete_directory_recursive(list[i]);
  5369. stb_arr_free(list);
  5370. list = stb_readdir_files(dir);
  5371. for (i=0; i < stb_arr_len(list); ++i)
  5372. if (!remove(list[i])) {
  5373. // on windows, try again after making it writeable; don't ALWAYS
  5374. // do this first since that would be slow in the normal case
  5375. #ifdef _MSC_VER
  5376. _chmod(list[i], _S_IWRITE);
  5377. remove(list[i]);
  5378. #endif
  5379. }
  5380. stb_arr_free(list);
  5381. stb__windows(_rmdir,rmdir)(dir);
  5382. }
  5383. #endif
  5384. //////////////////////////////////////////////////////////////////////////////
  5385. //
  5386. // construct trees from filenames; useful for cmirror summaries
  5387. typedef struct stb_dirtree2 stb_dirtree2;
  5388. struct stb_dirtree2
  5389. {
  5390. stb_dirtree2 **subdirs;
  5391. // make convenient for stb_summarize_tree
  5392. int num_subdir;
  5393. float weight;
  5394. // actual data
  5395. char *fullpath;
  5396. char *relpath;
  5397. char **files;
  5398. };
  5399. STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count);
  5400. STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count);
  5401. STB_EXTERN int stb_dir_is_prefix(char *dir, int dirlen, char *file);
  5402. #ifdef STB_DEFINE
  5403. int stb_dir_is_prefix(char *dir, int dirlen, char *file)
  5404. {
  5405. if (dirlen == 0) return STB_TRUE;
  5406. if (stb_strnicmp(dir, file, dirlen)) return STB_FALSE;
  5407. if (file[dirlen] == '/' || file[dirlen] == '\\') return STB_TRUE;
  5408. return STB_FALSE;
  5409. }
  5410. stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count)
  5411. {
  5412. char buffer1[1024];
  5413. int i;
  5414. int dlen = strlen(src), elen;
  5415. stb_dirtree2 *d;
  5416. char ** descendents = NULL;
  5417. char ** files = NULL;
  5418. char *s;
  5419. if (!count) return NULL;
  5420. // first find all the ones that belong here... note this is will take O(NM) with N files and M subdirs
  5421. for (i=0; i < count; ++i) {
  5422. if (stb_dir_is_prefix(src, dlen, filelist[i])) {
  5423. stb_arr_push(descendents, filelist[i]);
  5424. }
  5425. }
  5426. if (descendents == NULL)
  5427. return NULL;
  5428. elen = dlen;
  5429. // skip a leading slash
  5430. if (elen == 0 && (descendents[0][0] == '/' || descendents[0][0] == '\\'))
  5431. ++elen;
  5432. else if (elen)
  5433. ++elen;
  5434. // now extract all the ones that have their root here
  5435. for (i=0; i < stb_arr_len(descendents);) {
  5436. if (!stb_strchr2(descendents[i]+elen, '/', '\\')) {
  5437. stb_arr_push(files, descendents[i]);
  5438. descendents[i] = descendents[stb_arr_len(descendents)-1];
  5439. stb_arr_pop(descendents);
  5440. } else
  5441. ++i;
  5442. }
  5443. // now create a record
  5444. d = (stb_dirtree2 *) malloc(sizeof(*d));
  5445. d->files = files;
  5446. d->subdirs = NULL;
  5447. d->fullpath = strdup(src);
  5448. s = stb_strrchr2(d->fullpath, '/', '\\');
  5449. if (s)
  5450. ++s;
  5451. else
  5452. s = d->fullpath;
  5453. d->relpath = s;
  5454. // now create the children
  5455. qsort(descendents, stb_arr_len(descendents), sizeof(char *), stb_qsort_stricmp(0));
  5456. buffer1[0] = 0;
  5457. for (i=0; i < stb_arr_len(descendents); ++i) {
  5458. char buffer2[1024];
  5459. char *s = descendents[i] + elen, *t;
  5460. t = stb_strchr2(s, '/', '\\');
  5461. assert(t);
  5462. stb_strncpy(buffer2, descendents[i], t-descendents[i]+1);
  5463. if (stb_stricmp(buffer1, buffer2)) {
  5464. stb_dirtree2 *t = stb_dirtree2_from_files_relative(buffer2, descendents, stb_arr_len(descendents));
  5465. assert(t != NULL);
  5466. strcpy(buffer1, buffer2);
  5467. stb_arr_push(d->subdirs, t);
  5468. }
  5469. }
  5470. d->num_subdir = stb_arr_len(d->subdirs);
  5471. d->weight = 0;
  5472. return d;
  5473. }
  5474. stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count)
  5475. {
  5476. return stb_dirtree2_from_files_relative("", filelist, count);
  5477. }
  5478. #endif
  5479. //////////////////////////////////////////////////////////////////////////////
  5480. //
  5481. // Checksums: CRC-32, ADLER32, SHA-1
  5482. //
  5483. // CRC-32 and ADLER32 allow streaming blocks
  5484. // SHA-1 requires either a complete buffer, max size 2^32 - 73
  5485. // or it can checksum directly from a file, max 2^61
  5486. #define STB_ADLER32_SEED 1
  5487. #define STB_CRC32_SEED 0 // note that we logical NOT this in the code
  5488. STB_EXTERN stb_uint
  5489. stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen);
  5490. STB_EXTERN stb_uint
  5491. stb_crc32_block(stb_uint crc32, stb_uchar *buffer, stb_uint len);
  5492. STB_EXTERN stb_uint stb_crc32(unsigned char *buffer, stb_uint len);
  5493. STB_EXTERN void stb_sha1(
  5494. unsigned char output[20], unsigned char *buffer, unsigned int len);
  5495. STB_EXTERN int stb_sha1_file(unsigned char output[20], char *file);
  5496. STB_EXTERN void stb_sha1_readable(char display[27], unsigned char sha[20]);
  5497. #ifdef STB_DEFINE
  5498. stb_uint stb_crc32_block(stb_uint crc, unsigned char *buffer, stb_uint len)
  5499. {
  5500. static stb_uint crc_table[256];
  5501. stb_uint i,j,s;
  5502. crc = ~crc;
  5503. if (crc_table[1] == 0)
  5504. for(i=0; i < 256; i++) {
  5505. for (s=i, j=0; j < 8; ++j)
  5506. s = (s >> 1) ^ (s & 1 ? 0xedb88320 : 0);
  5507. crc_table[i] = s;
  5508. }
  5509. for (i=0; i < len; ++i)
  5510. crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
  5511. return ~crc;
  5512. }
  5513. stb_uint stb_crc32(unsigned char *buffer, stb_uint len)
  5514. {
  5515. return stb_crc32_block(0, buffer, len);
  5516. }
  5517. stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)
  5518. {
  5519. const unsigned long ADLER_MOD = 65521;
  5520. unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;
  5521. unsigned long blocklen, i;
  5522. blocklen = buflen % 5552;
  5523. while (buflen) {
  5524. for (i=0; i + 7 < blocklen; i += 8) {
  5525. s1 += buffer[0], s2 += s1;
  5526. s1 += buffer[1], s2 += s1;
  5527. s1 += buffer[2], s2 += s1;
  5528. s1 += buffer[3], s2 += s1;
  5529. s1 += buffer[4], s2 += s1;
  5530. s1 += buffer[5], s2 += s1;
  5531. s1 += buffer[6], s2 += s1;
  5532. s1 += buffer[7], s2 += s1;
  5533. buffer += 8;
  5534. }
  5535. for (; i < blocklen; ++i)
  5536. s1 += *buffer++, s2 += s1;
  5537. s1 %= ADLER_MOD, s2 %= ADLER_MOD;
  5538. buflen -= blocklen;
  5539. blocklen = 5552;
  5540. }
  5541. return (s2 << 16) + s1;
  5542. }
  5543. static void stb__sha1(stb_uchar *chunk, stb_uint h[5])
  5544. {
  5545. int i;
  5546. stb_uint a,b,c,d,e;
  5547. stb_uint w[80];
  5548. for (i=0; i < 16; ++i)
  5549. w[i] = stb_big32(&chunk[i*4]);
  5550. for (i=16; i < 80; ++i) {
  5551. stb_uint t;
  5552. t = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];
  5553. w[i] = (t + t) | (t >> 31);
  5554. }
  5555. a = h[0];
  5556. b = h[1];
  5557. c = h[2];
  5558. d = h[3];
  5559. e = h[4];
  5560. #define STB__SHA1(k,f) \
  5561. { \
  5562. stb_uint temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i]; \
  5563. e = d; \
  5564. d = c; \
  5565. c = (b << 30) + (b >> 2); \
  5566. b = a; \
  5567. a = temp; \
  5568. }
  5569. i=0;
  5570. for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d)) );
  5571. for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d );
  5572. for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c)) );
  5573. for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d );
  5574. #undef STB__SHA1
  5575. h[0] += a;
  5576. h[1] += b;
  5577. h[2] += c;
  5578. h[3] += d;
  5579. h[4] += e;
  5580. }
  5581. void stb_sha1(stb_uchar output[20], stb_uchar *buffer, stb_uint len)
  5582. {
  5583. unsigned char final_block[128];
  5584. stb_uint end_start, final_len, j;
  5585. int i;
  5586. stb_uint h[5];
  5587. h[0] = 0x67452301;
  5588. h[1] = 0xefcdab89;
  5589. h[2] = 0x98badcfe;
  5590. h[3] = 0x10325476;
  5591. h[4] = 0xc3d2e1f0;
  5592. // we need to write padding to the last one or two
  5593. // blocks, so build those first into 'final_block'
  5594. // we have to write one special byte, plus the 8-byte length
  5595. // compute the block where the data runs out
  5596. end_start = len & ~63;
  5597. // compute the earliest we can encode the length
  5598. if (((len+9) & ~63) == end_start) {
  5599. // it all fits in one block, so fill a second-to-last block
  5600. end_start -= 64;
  5601. }
  5602. final_len = end_start + 128;
  5603. // now we need to copy the data in
  5604. assert(end_start + 128 >= len+9);
  5605. assert(end_start < len || len < 64-9);
  5606. j = 0;
  5607. if (end_start > len)
  5608. j = (stb_uint) - (int) end_start;
  5609. for (; end_start + j < len; ++j)
  5610. final_block[j] = buffer[end_start + j];
  5611. final_block[j++] = 0x80;
  5612. while (j < 128-5) // 5 byte length, so write 4 extra padding bytes
  5613. final_block[j++] = 0;
  5614. // big-endian size
  5615. final_block[j++] = len >> 29;
  5616. final_block[j++] = len >> 21;
  5617. final_block[j++] = len >> 13;
  5618. final_block[j++] = len >> 5;
  5619. final_block[j++] = len << 3;
  5620. assert(j == 128 && end_start + j == final_len);
  5621. for (j=0; j < final_len; j += 64) { // 512-bit chunks
  5622. if (j+64 >= end_start+64)
  5623. stb__sha1(&final_block[j - end_start], h);
  5624. else
  5625. stb__sha1(&buffer[j], h);
  5626. }
  5627. for (i=0; i < 5; ++i) {
  5628. output[i*4 + 0] = h[i] >> 24;
  5629. output[i*4 + 1] = h[i] >> 16;
  5630. output[i*4 + 2] = h[i] >> 8;
  5631. output[i*4 + 3] = h[i] >> 0;
  5632. }
  5633. }
  5634. #ifdef _MSC_VER
  5635. int stb_sha1_file(stb_uchar output[20], char *file)
  5636. {
  5637. int i;
  5638. stb_uint64 length=0;
  5639. unsigned char buffer[128];
  5640. FILE *f = stb__fopen(file, "rb");
  5641. stb_uint h[5];
  5642. if (f == NULL) return 0; // file not found
  5643. h[0] = 0x67452301;
  5644. h[1] = 0xefcdab89;
  5645. h[2] = 0x98badcfe;
  5646. h[3] = 0x10325476;
  5647. h[4] = 0xc3d2e1f0;
  5648. for(;;) {
  5649. int n = fread(buffer, 1, 64, f);
  5650. if (n == 64) {
  5651. stb__sha1(buffer, h);
  5652. length += n;
  5653. } else {
  5654. int block = 64;
  5655. length += n;
  5656. buffer[n++] = 0x80;
  5657. // if there isn't enough room for the length, double the block
  5658. if (n + 8 > 64)
  5659. block = 128;
  5660. // pad to end
  5661. memset(buffer+n, 0, block-8-n);
  5662. i = block - 8;
  5663. buffer[i++] = (stb_uchar) (length >> 53);
  5664. buffer[i++] = (stb_uchar) (length >> 45);
  5665. buffer[i++] = (stb_uchar) (length >> 37);
  5666. buffer[i++] = (stb_uchar) (length >> 29);
  5667. buffer[i++] = (stb_uchar) (length >> 21);
  5668. buffer[i++] = (stb_uchar) (length >> 13);
  5669. buffer[i++] = (stb_uchar) (length >> 5);
  5670. buffer[i++] = (stb_uchar) (length << 3);
  5671. assert(i == block);
  5672. stb__sha1(buffer, h);
  5673. if (block == 128)
  5674. stb__sha1(buffer+64, h);
  5675. else
  5676. assert(block == 64);
  5677. break;
  5678. }
  5679. }
  5680. fclose(f);
  5681. for (i=0; i < 5; ++i) {
  5682. output[i*4 + 0] = h[i] >> 24;
  5683. output[i*4 + 1] = h[i] >> 16;
  5684. output[i*4 + 2] = h[i] >> 8;
  5685. output[i*4 + 3] = h[i] >> 0;
  5686. }
  5687. return 1;
  5688. }
  5689. #endif // _MSC_VER
  5690. // client can truncate this wherever they like
  5691. void stb_sha1_readable(char display[27], unsigned char sha[20])
  5692. {
  5693. char encoding[65] = "0123456789abcdefghijklmnopqrstuv"
  5694. "wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%$";
  5695. int num_bits = 0, acc=0;
  5696. int i=0,o=0;
  5697. while (o < 26) {
  5698. int v;
  5699. // expand the accumulator
  5700. if (num_bits < 6) {
  5701. assert(i != 20);
  5702. acc += sha[i++] << num_bits;
  5703. num_bits += 8;
  5704. }
  5705. v = acc & ((1 << 6) - 1);
  5706. display[o++] = encoding[v];
  5707. acc >>= 6;
  5708. num_bits -= 6;
  5709. }
  5710. assert(num_bits == 20*8 - 26*6);
  5711. display[o++] = encoding[acc];
  5712. }
  5713. #endif // STB_DEFINE
  5714. ///////////////////////////////////////////////////////////
  5715. //
  5716. // simplified WINDOWS registry interface... hopefully
  5717. // we'll never actually use this?
  5718. #if defined(_WIN32)
  5719. STB_EXTERN void * stb_reg_open(char *mode, char *where); // mode: "rHKLM" or "rHKCU" or "w.."
  5720. STB_EXTERN void stb_reg_close(void *reg);
  5721. STB_EXTERN int stb_reg_read(void *zreg, char *str, void *data, unsigned long len);
  5722. STB_EXTERN int stb_reg_read_string(void *zreg, char *str, char *data, int len);
  5723. STB_EXTERN void stb_reg_write(void *zreg, char *str, void *data, unsigned long len);
  5724. STB_EXTERN void stb_reg_write_string(void *zreg, char *str, char *data);
  5725. #if defined(STB_DEFINE) && !defined(STB_NO_REGISTRY)
  5726. #define STB_HAS_REGISTRY
  5727. #ifndef _WINDOWS_
  5728. #define HKEY void *
  5729. STB_EXTERN __declspec(dllimport) long __stdcall RegCloseKey ( HKEY hKey );
  5730. STB_EXTERN __declspec(dllimport) long __stdcall RegCreateKeyExA ( HKEY hKey, const char * lpSubKey,
  5731. int Reserved, char * lpClass, int dwOptions,
  5732. int samDesired, void *lpSecurityAttributes, HKEY * phkResult, int * lpdwDisposition );
  5733. STB_EXTERN __declspec(dllimport) long __stdcall RegDeleteKeyA ( HKEY hKey, const char * lpSubKey );
  5734. STB_EXTERN __declspec(dllimport) long __stdcall RegQueryValueExA ( HKEY hKey, const char * lpValueName,
  5735. int * lpReserved, unsigned long * lpType, unsigned char * lpData, unsigned long * lpcbData );
  5736. STB_EXTERN __declspec(dllimport) long __stdcall RegSetValueExA ( HKEY hKey, const char * lpValueName,
  5737. int Reserved, int dwType, const unsigned char* lpData, int cbData );
  5738. STB_EXTERN __declspec(dllimport) long __stdcall RegOpenKeyExA ( HKEY hKey, const char * lpSubKey,
  5739. int ulOptions, int samDesired, HKEY * phkResult );
  5740. #endif // _WINDOWS_
  5741. #define STB__REG_OPTION_NON_VOLATILE 0
  5742. #define STB__REG_KEY_ALL_ACCESS 0x000f003f
  5743. #define STB__REG_KEY_READ 0x00020019
  5744. void *stb_reg_open(char *mode, char *where)
  5745. {
  5746. long res;
  5747. HKEY base;
  5748. HKEY zreg;
  5749. if (!stb_stricmp(mode+1, "cu") || !stb_stricmp(mode+1, "hkcu"))
  5750. base = (HKEY) 0x80000001; // HKCU
  5751. else if (!stb_stricmp(mode+1, "lm") || !stb_stricmp(mode+1, "hklm"))
  5752. base = (HKEY) 0x80000002; // HKLM
  5753. else
  5754. return NULL;
  5755. if (mode[0] == 'r')
  5756. res = RegOpenKeyExA(base, where, 0, STB__REG_KEY_READ, &zreg);
  5757. else if (mode[0] == 'w')
  5758. res = RegCreateKeyExA(base, where, 0, NULL, STB__REG_OPTION_NON_VOLATILE, STB__REG_KEY_ALL_ACCESS, NULL, &zreg, NULL);
  5759. else
  5760. return NULL;
  5761. return res ? NULL : zreg;
  5762. }
  5763. void stb_reg_close(void *reg)
  5764. {
  5765. RegCloseKey((HKEY) reg);
  5766. }
  5767. #define STB__REG_SZ 1
  5768. #define STB__REG_BINARY 3
  5769. #define STB__REG_DWORD 4
  5770. int stb_reg_read(void *zreg, char *str, void *data, unsigned long len)
  5771. {
  5772. unsigned long type;
  5773. unsigned long alen = len;
  5774. if (0 == RegQueryValueExA((HKEY) zreg, str, 0, &type, (unsigned char *) data, &len))
  5775. if (type == STB__REG_BINARY || type == STB__REG_SZ || type == STB__REG_DWORD) {
  5776. if (len < alen)
  5777. *((char *) data + len) = 0;
  5778. return 1;
  5779. }
  5780. return 0;
  5781. }
  5782. void stb_reg_write(void *zreg, char *str, void *data, unsigned long len)
  5783. {
  5784. if (zreg)
  5785. RegSetValueExA((HKEY) zreg, str, 0, STB__REG_BINARY, (const unsigned char *) data, len);
  5786. }
  5787. int stb_reg_read_string(void *zreg, char *str, char *data, int len)
  5788. {
  5789. if (!stb_reg_read(zreg, str, data, len)) return 0;
  5790. data[len-1] = 0; // force a 0 at the end of the string no matter what
  5791. return 1;
  5792. }
  5793. void stb_reg_write_string(void *zreg, char *str, char *data)
  5794. {
  5795. if (zreg)
  5796. RegSetValueExA((HKEY) zreg, str, 0, STB__REG_SZ, (const unsigned char *) data, strlen(data)+1);
  5797. }
  5798. #endif // STB_DEFINE
  5799. #endif // _WIN32
  5800. //////////////////////////////////////////////////////////////////////////////
  5801. //
  5802. // stb_cfg - This is like the registry, but the config info
  5803. // is all stored in plain old files where we can
  5804. // backup and restore them easily. The LOCATION of
  5805. // the config files is gotten from... the registry!
  5806. #ifndef STB_NO_STB_STRINGS
  5807. typedef struct stb_cfg_st stb_cfg;
  5808. STB_EXTERN stb_cfg * stb_cfg_open(char *config, char *mode); // mode = "r", "w"
  5809. STB_EXTERN void stb_cfg_close(stb_cfg *cfg);
  5810. STB_EXTERN int stb_cfg_read(stb_cfg *cfg, char *key, void *value, int len);
  5811. STB_EXTERN void stb_cfg_write(stb_cfg *cfg, char *key, void *value, int len);
  5812. STB_EXTERN int stb_cfg_read_string(stb_cfg *cfg, char *key, char *value, int len);
  5813. STB_EXTERN void stb_cfg_write_string(stb_cfg *cfg, char *key, char *value);
  5814. STB_EXTERN int stb_cfg_delete(stb_cfg *cfg, char *key);
  5815. STB_EXTERN void stb_cfg_set_directory(char *dir);
  5816. #ifdef STB_DEFINE
  5817. typedef struct
  5818. {
  5819. char *key;
  5820. void *value;
  5821. int value_len;
  5822. } stb__cfg_item;
  5823. struct stb_cfg_st
  5824. {
  5825. stb__cfg_item *data;
  5826. char *loaded_file; // this needs to be freed
  5827. FILE *f; // write the data to this file on close
  5828. };
  5829. static char *stb__cfg_sig = "sTbCoNfIg!\0\0";
  5830. static char stb__cfg_dir[512];
  5831. STB_EXTERN void stb_cfg_set_directory(char *dir)
  5832. {
  5833. strcpy(stb__cfg_dir, dir);
  5834. }
  5835. STB_EXTERN stb_cfg * stb_cfg_open(char *config, char *mode)
  5836. {
  5837. size_t len;
  5838. stb_cfg *z;
  5839. char file[512];
  5840. if (mode[0] != 'r' && mode[0] != 'w') return NULL;
  5841. if (!stb__cfg_dir[0]) {
  5842. #ifdef _WIN32
  5843. strcpy(stb__cfg_dir, "c:/stb");
  5844. #else
  5845. strcpy(stb__cfg_dir, "~/.stbconfig");
  5846. #endif
  5847. #ifdef STB_HAS_REGISTRY
  5848. {
  5849. void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");
  5850. if (reg) {
  5851. stb_reg_read_string(reg, "config_dir", stb__cfg_dir, sizeof(stb__cfg_dir));
  5852. stb_reg_close(reg);
  5853. }
  5854. }
  5855. #endif
  5856. }
  5857. sprintf(file, "%s/%s.cfg", stb__cfg_dir, config);
  5858. z = (stb_cfg *) stb_malloc(0, sizeof(*z));
  5859. z->data = NULL;
  5860. z->loaded_file = stb_filec(file, &len);
  5861. if (z->loaded_file) {
  5862. char *s = z->loaded_file;
  5863. if (!memcmp(s, stb__cfg_sig, 12)) {
  5864. char *s = z->loaded_file + 12;
  5865. while (s < z->loaded_file + len) {
  5866. stb__cfg_item a;
  5867. int n = *(stb_int16 *) s;
  5868. a.key = s+2;
  5869. s = s+2 + n;
  5870. a.value_len = *(int *) s;
  5871. s += 4;
  5872. a.value = s;
  5873. s += a.value_len;
  5874. stb_arr_push(z->data, a);
  5875. }
  5876. assert(s == z->loaded_file + len);
  5877. }
  5878. }
  5879. if (mode[0] == 'w')
  5880. z->f = fopen(file, "wb");
  5881. else
  5882. z->f = NULL;
  5883. return z;
  5884. }
  5885. void stb_cfg_close(stb_cfg *z)
  5886. {
  5887. if (z->f) {
  5888. int i;
  5889. // write the file out
  5890. fwrite(stb__cfg_sig, 12, 1, z->f);
  5891. for (i=0; i < stb_arr_len(z->data); ++i) {
  5892. stb_int16 n = strlen(z->data[i].key)+1;
  5893. fwrite(&n, 2, 1, z->f);
  5894. fwrite(z->data[i].key, n, 1, z->f);
  5895. fwrite(&z->data[i].value_len, 4, 1, z->f);
  5896. fwrite(z->data[i].value, z->data[i].value_len, 1, z->f);
  5897. }
  5898. fclose(z->f);
  5899. }
  5900. stb_arr_free(z->data);
  5901. stb_free(z);
  5902. }
  5903. int stb_cfg_read(stb_cfg *z, char *key, void *value, int len)
  5904. {
  5905. int i;
  5906. for (i=0; i < stb_arr_len(z->data); ++i) {
  5907. if (!stb_stricmp(z->data[i].key, key)) {
  5908. int n = stb_min(len, z->data[i].value_len);
  5909. memcpy(value, z->data[i].value, n);
  5910. if (n < len)
  5911. *((char *) value + n) = 0;
  5912. return 1;
  5913. }
  5914. }
  5915. return 0;
  5916. }
  5917. void stb_cfg_write(stb_cfg *z, char *key, void *value, int len)
  5918. {
  5919. int i;
  5920. for (i=0; i < stb_arr_len(z->data); ++i)
  5921. if (!stb_stricmp(z->data[i].key, key))
  5922. break;
  5923. if (i == stb_arr_len(z->data)) {
  5924. stb__cfg_item p;
  5925. p.key = stb_strdup(key, z);
  5926. p.value = NULL;
  5927. p.value_len = 0;
  5928. stb_arr_push(z->data, p);
  5929. }
  5930. z->data[i].value = stb_malloc(z, len);
  5931. z->data[i].value_len = len;
  5932. memcpy(z->data[i].value, value, len);
  5933. }
  5934. int stb_cfg_delete(stb_cfg *z, char *key)
  5935. {
  5936. int i;
  5937. for (i=0; i < stb_arr_len(z->data); ++i)
  5938. if (!stb_stricmp(z->data[i].key, key)) {
  5939. stb_arr_fastdelete(z->data, i);
  5940. return 1;
  5941. }
  5942. return 0;
  5943. }
  5944. int stb_cfg_read_string(stb_cfg *z, char *key, char *value, int len)
  5945. {
  5946. if (!stb_cfg_read(z, key, value, len)) return 0;
  5947. value[len-1] = 0;
  5948. return 1;
  5949. }
  5950. void stb_cfg_write_string(stb_cfg *z, char *key, char *value)
  5951. {
  5952. stb_cfg_write(z, key, value, strlen(value)+1);
  5953. }
  5954. #endif
  5955. //////////////////////////////////////////////////////////////////////////////
  5956. //
  5957. // stb_dirtree - load a description of a directory tree
  5958. // uses a cache and stat()s the directories for changes
  5959. // MUCH faster on NTFS, _wrong_ on FAT32, so should
  5960. // ignore the db on FAT32
  5961. #ifdef _WIN32
  5962. typedef struct
  5963. {
  5964. char * path; // full path from passed-in root
  5965. time_t last_modified;
  5966. int num_files;
  5967. int flag;
  5968. } stb_dirtree_dir;
  5969. typedef struct
  5970. {
  5971. char *name; // name relative to path
  5972. int dir; // index into dirs[] array
  5973. stb_int64 size; // size, max 4GB
  5974. time_t last_modified;
  5975. int flag;
  5976. } stb_dirtree_file;
  5977. typedef struct
  5978. {
  5979. stb_dirtree_dir *dirs;
  5980. stb_dirtree_file *files;
  5981. // internal use
  5982. void * string_pool; // used to free data en masse
  5983. } stb_dirtree;
  5984. extern void stb_dirtree_free ( stb_dirtree *d );
  5985. extern stb_dirtree *stb_dirtree_get ( char *dir);
  5986. extern stb_dirtree *stb_dirtree_get_dir ( char *dir, char *cache_dir);
  5987. extern stb_dirtree *stb_dirtree_get_with_file ( char *dir, char *cache_file);
  5988. // get a list of all the files recursively underneath 'dir'
  5989. //
  5990. // cache_file is used to store a copy of the directory tree to speed up
  5991. // later calls. It must be unique to 'dir' and the current working
  5992. // directory! Otherwise who knows what will happen (a good solution
  5993. // is to put it _in_ dir, but this API doesn't force that).
  5994. //
  5995. // Also, it might be possible to break this if you have two different processes
  5996. // do a call to stb_dirtree_get() with the same cache file at about the same
  5997. // time, but I _think_ it might just work.
  5998. // i needed to build an identical data structure representing the state of
  5999. // a mirrored copy WITHOUT bothering to rescan it (i.e. we're mirroring to
  6000. // it WITHOUT scanning it, e.g. it's over the net), so this requires access
  6001. // to all of the innards.
  6002. extern void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last);
  6003. extern void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last);
  6004. extern void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir);
  6005. extern void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir);
  6006. #ifdef STB_DEFINE
  6007. static void stb__dirtree_add_dir(char *path, time_t last, stb_dirtree *active)
  6008. {
  6009. stb_dirtree_dir d;
  6010. d.last_modified = last;
  6011. d.num_files = 0;
  6012. d.path = stb_strdup(path, active->string_pool);
  6013. stb_arr_push(active->dirs, d);
  6014. }
  6015. static void stb__dirtree_add_file(char *name, int dir, stb_int64 size, time_t last, stb_dirtree *active)
  6016. {
  6017. stb_dirtree_file f;
  6018. f.dir = dir;
  6019. f.size = size;
  6020. f.last_modified = last;
  6021. f.name = stb_strdup(name, active->string_pool);
  6022. ++active->dirs[dir].num_files;
  6023. stb_arr_push(active->files, f);
  6024. }
  6025. // version 02 supports > 4GB files
  6026. static char stb__signature[12] = { 's', 'T', 'b', 'D', 'i', 'R', 't', 'R', 'e', 'E', '0', '2' };
  6027. static void stb__dirtree_save_db(char *filename, stb_dirtree *data, char *root)
  6028. {
  6029. int i, num_dirs_final=0, num_files_final;
  6030. char *info = root ? root : "";
  6031. int *remap;
  6032. FILE *f = fopen(filename, "wb");
  6033. if (!f) return;
  6034. fwrite(stb__signature, sizeof(stb__signature), 1, f);
  6035. fwrite(info, strlen(info)+1, 1, f);
  6036. // need to be slightly tricky and not write out NULLed directories, nor the root
  6037. // build remapping table of all dirs we'll be writing out
  6038. remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(data->dirs));
  6039. for (i=0; i < stb_arr_len(data->dirs); ++i) {
  6040. if (data->dirs[i].path == NULL || (root && 0==stb_stricmp(data->dirs[i].path, root))) {
  6041. remap[i] = -1;
  6042. } else {
  6043. remap[i] = num_dirs_final++;
  6044. }
  6045. }
  6046. fwrite(&num_dirs_final, 4, 1, f);
  6047. for (i=0; i < stb_arr_len(data->dirs); ++i) {
  6048. if (remap[i] >= 0) {
  6049. fwrite(&data->dirs[i].last_modified, 4, 1, f);
  6050. stb_fput_string(f, data->dirs[i].path);
  6051. }
  6052. }
  6053. num_files_final = 0;
  6054. for (i=0; i < stb_arr_len(data->files); ++i)
  6055. if (remap[data->files[i].dir] >= 0 && data->files[i].name)
  6056. ++num_files_final;
  6057. fwrite(&num_files_final, 4, 1, f);
  6058. for (i=0; i < stb_arr_len(data->files); ++i) {
  6059. if (remap[data->files[i].dir] >= 0 && data->files[i].name) {
  6060. stb_fput_ranged(f, remap[data->files[i].dir], 0, num_dirs_final);
  6061. stb_fput_varlen64(f, data->files[i].size);
  6062. fwrite(&data->files[i].last_modified, 4, 1, f);
  6063. stb_fput_string(f, data->files[i].name);
  6064. }
  6065. }
  6066. fclose(f);
  6067. }
  6068. // note: stomps any existing data, rather than appending
  6069. static void stb__dirtree_load_db(char *filename, stb_dirtree *data, char *dir)
  6070. {
  6071. char sig[2048];
  6072. int i,n;
  6073. FILE *f = fopen(filename, "rb");
  6074. if (!f) return;
  6075. data->string_pool = stb_malloc(0,1);
  6076. fread(sig, sizeof(stb__signature), 1, f);
  6077. if (memcmp(stb__signature, sig, sizeof(stb__signature))) { fclose(f); return; }
  6078. if (!fread(sig, strlen(dir)+1, 1, f)) { fclose(f); return; }
  6079. if (stb_stricmp(sig,dir)) { fclose(f); return; }
  6080. // we can just read them straight in, because they're guaranteed to be valid
  6081. fread(&n, 4, 1, f);
  6082. stb_arr_setlen(data->dirs, n);
  6083. for(i=0; i < stb_arr_len(data->dirs); ++i) {
  6084. fread(&data->dirs[i].last_modified, 4, 1, f);
  6085. data->dirs[i].path = stb_fget_string(f, data->string_pool);
  6086. if (data->dirs[i].path == NULL) goto bail;
  6087. }
  6088. fread(&n, 4, 1, f);
  6089. stb_arr_setlen(data->files, n);
  6090. for (i=0; i < stb_arr_len(data->files); ++i) {
  6091. data->files[i].dir = stb_fget_ranged(f, 0, stb_arr_len(data->dirs));
  6092. data->files[i].size = stb_fget_varlen64(f);
  6093. fread(&data->files[i].last_modified, 4, 1, f);
  6094. data->files[i].name = stb_fget_string(f, data->string_pool);
  6095. if (data->files[i].name == NULL) goto bail;
  6096. }
  6097. if (0) {
  6098. bail:
  6099. stb_arr_free(data->dirs);
  6100. stb_arr_free(data->files);
  6101. }
  6102. fclose(f);
  6103. }
  6104. static int stb__dircount, stb__dircount_mask, stb__showfile;
  6105. static void stb__dirtree_scandir(char *path, time_t last_time, stb_dirtree *active)
  6106. {
  6107. // this is dumb depth first; theoretically it might be faster
  6108. // to fully traverse each directory before visiting its children,
  6109. // but it's complicated and didn't seem like a gain in the test app
  6110. int n;
  6111. struct _wfinddatai64_t c_file;
  6112. long hFile;
  6113. stb__wchar full_path[1024];
  6114. int has_slash;
  6115. if (stb__showfile) printf("<");
  6116. has_slash = (path[0] && path[strlen(path)-1] == '/');
  6117. // @TODO: do this concatenation without using swprintf to avoid this mess:
  6118. #if defined(_MSC_VER) && _MSC_VER < 1400
  6119. if (has_slash)
  6120. swprintf(full_path, L"%s*", stb__from_utf8(path));
  6121. else
  6122. swprintf(full_path, L"%s/*", stb__from_utf8(path));
  6123. #else
  6124. if (has_slash)
  6125. swprintf(full_path, 1024, L"%s*", stb__from_utf8(path));
  6126. else
  6127. swprintf(full_path, 1024, L"%s/*", stb__from_utf8(path));
  6128. #endif
  6129. // it's possible this directory is already present: that means it was in the
  6130. // cache, but its parent wasn't... in that case, we're done with it
  6131. if (stb__showfile) printf("C[%d]", stb_arr_len(active->dirs));
  6132. for (n=0; n < stb_arr_len(active->dirs); ++n)
  6133. if (0 == stb_stricmp(active->dirs[n].path, path)) {
  6134. if (stb__showfile) printf("D");
  6135. return;
  6136. }
  6137. if (stb__showfile) printf("E");
  6138. // otherwise, we need to add it
  6139. stb__dirtree_add_dir(path, last_time, active);
  6140. n = stb_arr_lastn(active->dirs);
  6141. if (stb__showfile) printf("[");
  6142. if( (hFile = _wfindfirsti64( full_path, &c_file )) != -1L ) {
  6143. do {
  6144. if (stb__showfile) printf(")");
  6145. if (c_file.attrib & _A_SUBDIR) {
  6146. // ignore subdirectories starting with '.', e.g. "." and ".."
  6147. if (c_file.name[0] != '.') {
  6148. char *new_path = (char *) full_path;
  6149. char *temp = stb__to_utf8(c_file.name);
  6150. if (has_slash)
  6151. sprintf(new_path, "%s%s", path, temp);
  6152. else
  6153. sprintf(new_path, "%s/%s", path, temp);
  6154. if (stb__dircount_mask) {
  6155. ++stb__dircount;
  6156. if (!(stb__dircount & stb__dircount_mask)) {
  6157. printf("%s\r", new_path);
  6158. }
  6159. }
  6160. stb__dirtree_scandir(new_path, c_file.time_write, active);
  6161. }
  6162. } else {
  6163. char *temp = stb__to_utf8(c_file.name);
  6164. stb__dirtree_add_file(temp, n, c_file.size, c_file.time_write, active);
  6165. }
  6166. if (stb__showfile) printf("(");
  6167. } while( _wfindnexti64( hFile, &c_file ) == 0 );
  6168. if (stb__showfile) printf("]");
  6169. _findclose( hFile );
  6170. }
  6171. if (stb__showfile) printf(">\n");
  6172. }
  6173. // scan the database and see if it's all valid
  6174. static int stb__dirtree_update_db(stb_dirtree *db, stb_dirtree *active)
  6175. {
  6176. int changes_detected = STB_FALSE;
  6177. int i;
  6178. int *remap;
  6179. int *rescan=NULL;
  6180. remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(db->dirs));
  6181. memset(remap, 0, sizeof(remap[0]) * stb_arr_len(db->dirs));
  6182. rescan = NULL;
  6183. for (i=0; i < stb_arr_len(db->dirs); ++i) {
  6184. struct _stat info;
  6185. if (stb__dircount_mask) {
  6186. ++stb__dircount;
  6187. if (!(stb__dircount & stb__dircount_mask)) {
  6188. printf(".");
  6189. }
  6190. }
  6191. if (0 == _stat(db->dirs[i].path, &info)) {
  6192. if (info.st_mode & _S_IFDIR) {
  6193. // it's still a directory, as expected
  6194. int n = abs(info.st_mtime - db->dirs[i].last_modified);
  6195. if (n > 1 && n != 3600) { // the 3600 is a hack because sometimes this jumps for no apparent reason, even when no time zone or DST issues are at play
  6196. // it's changed! force a rescan
  6197. // we don't want to scan it until we've stat()d its
  6198. // subdirs, though, so we queue it
  6199. if (stb__showfile) printf("Changed: %s - %08x:%08x\n", db->dirs[i].path, db->dirs[i].last_modified, info.st_mtime);
  6200. stb_arr_push(rescan, i);
  6201. // update the last_mod time
  6202. db->dirs[i].last_modified = info.st_mtime;
  6203. // ignore existing files in this dir
  6204. remap[i] = -1;
  6205. changes_detected = STB_TRUE;
  6206. } else {
  6207. // it hasn't changed, just copy it through unchanged
  6208. stb__dirtree_add_dir(db->dirs[i].path, db->dirs[i].last_modified, active);
  6209. remap[i] = stb_arr_lastn(active->dirs);
  6210. }
  6211. } else {
  6212. // this path used to refer to a directory, but now it's a file!
  6213. // assume that the parent directory is going to be forced to rescan anyway
  6214. goto delete_entry;
  6215. }
  6216. } else {
  6217. delete_entry:
  6218. // directory no longer exists, so don't copy it
  6219. // we don't free it because it's in the string pool now
  6220. db->dirs[i].path = NULL;
  6221. remap[i] = -1;
  6222. changes_detected = STB_TRUE;
  6223. }
  6224. }
  6225. // at this point, we have:
  6226. //
  6227. // <rescan> holds a list of directory indices that need to be scanned due to being out of date
  6228. // <remap> holds the directory index in <active> for each dir in <db>, if it exists; -1 if not
  6229. // directories in <rescan> are not in <active> yet
  6230. // so we can go ahead and remap all the known files right now
  6231. for (i=0; i < stb_arr_len(db->files); ++i) {
  6232. int dir = db->files[i].dir;
  6233. if (remap[dir] >= 0) {
  6234. stb__dirtree_add_file(db->files[i].name, remap[dir], db->files[i].size, db->files[i].last_modified, active);
  6235. }
  6236. }
  6237. // at this point we're done with db->files, and done with remap
  6238. free(remap);
  6239. // now scan those directories using the standard scan
  6240. for (i=0; i < stb_arr_len(rescan); ++i) {
  6241. int z = rescan[i];
  6242. stb__dirtree_scandir(db->dirs[z].path, db->dirs[z].last_modified, active);
  6243. }
  6244. stb_arr_free(rescan);
  6245. return changes_detected;
  6246. }
  6247. static void stb__dirtree_free_raw(stb_dirtree *d)
  6248. {
  6249. stb_free(d->string_pool);
  6250. stb_arr_free(d->dirs);
  6251. stb_arr_free(d->files);
  6252. }
  6253. stb_dirtree *stb_dirtree_get_with_file(char *dir, char *cache_file)
  6254. {
  6255. stb_dirtree *output = (stb_dirtree *) malloc(sizeof(*output));
  6256. stb_dirtree db,active;
  6257. int prev_dir_count, cache_mismatch;
  6258. char *stripped_dir; // store the directory name without a trailing '/' or '\\'
  6259. // load the database of last-known state on disk
  6260. db.string_pool = NULL;
  6261. db.files = NULL;
  6262. db.dirs = NULL;
  6263. stripped_dir = stb_strip_final_slash(strdup(dir));
  6264. if (cache_file != NULL)
  6265. stb__dirtree_load_db(cache_file, &db, stripped_dir);
  6266. else if (stb__showfile)
  6267. printf("No cache file\n");
  6268. active.files = NULL;
  6269. active.dirs = NULL;
  6270. active.string_pool = stb_malloc(0,1); // @TODO: share string pools between both?
  6271. // check all the directories in the database; make note if
  6272. // anything we scanned had changed, and rescan those things
  6273. cache_mismatch = stb__dirtree_update_db(&db, &active);
  6274. // check the root tree
  6275. prev_dir_count = stb_arr_len(active.dirs); // record how many directories we've seen
  6276. stb__dirtree_scandir(stripped_dir, 0, &active); // no last_modified time available for root
  6277. if (stb__dircount_mask)
  6278. printf(" \r");
  6279. // done with the DB; write it back out if any changes, i.e. either
  6280. // 1. any inconsistency found between cached information and actual disk
  6281. // or 2. if scanning the root found any new directories--which we detect because
  6282. // more than one directory got added to the active db during that scan
  6283. if (cache_mismatch || stb_arr_len(active.dirs) > prev_dir_count+1)
  6284. stb__dirtree_save_db(cache_file, &active, stripped_dir);
  6285. free(stripped_dir);
  6286. stb__dirtree_free_raw(&db);
  6287. *output = active;
  6288. return output;
  6289. }
  6290. stb_dirtree *stb_dirtree_get_dir(char *dir, char *cache_dir)
  6291. {
  6292. int i;
  6293. stb_uint8 sha[20];
  6294. char dir_lower[1024];
  6295. char cache_file[1024],*s;
  6296. if (cache_dir == NULL)
  6297. return stb_dirtree_get_with_file(dir, NULL);
  6298. strcpy(dir_lower, dir);
  6299. stb_tolower(dir_lower);
  6300. stb_sha1(sha, (unsigned char *) dir_lower, strlen(dir_lower));
  6301. strcpy(cache_file, cache_dir);
  6302. s = cache_file + strlen(cache_file);
  6303. if (s[-1] != '//' && s[-1] != '\\') *s++ = '/';
  6304. strcpy(s, "dirtree_");
  6305. s += strlen(s);
  6306. for (i=0; i < 8; ++i) {
  6307. char *hex = "0123456789abcdef";
  6308. stb_uint z = sha[i];
  6309. *s++ = hex[z >> 4];
  6310. *s++ = hex[z & 15];
  6311. }
  6312. strcpy(s, ".bin");
  6313. return stb_dirtree_get_with_file(dir, cache_file);
  6314. }
  6315. stb_dirtree *stb_dirtree_get(char *dir)
  6316. {
  6317. char cache_dir[256];
  6318. strcpy(cache_dir, "c:/stb");
  6319. #ifdef STB_HAS_REGISTRY
  6320. {
  6321. void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");
  6322. if (reg) {
  6323. stb_reg_read(reg, "dirtree", cache_dir, sizeof(cache_dir));
  6324. stb_reg_close(reg);
  6325. }
  6326. }
  6327. #endif
  6328. return stb_dirtree_get_dir(dir, cache_dir);
  6329. }
  6330. void stb_dirtree_free(stb_dirtree *d)
  6331. {
  6332. stb__dirtree_free_raw(d);
  6333. free(d);
  6334. }
  6335. void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last)
  6336. {
  6337. stb__dirtree_add_dir(path, last, active);
  6338. }
  6339. void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last)
  6340. {
  6341. stb__dirtree_add_file(name, dir, size, last, active);
  6342. }
  6343. void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir)
  6344. {
  6345. char *s = stb_strip_final_slash(strdup(dir));
  6346. target->dirs = 0;
  6347. target->files = 0;
  6348. target->string_pool = 0;
  6349. stb__dirtree_load_db(filename, target, s);
  6350. free(s);
  6351. }
  6352. void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir)
  6353. {
  6354. stb__dirtree_save_db(filename, target, 0); // don't strip out any directories
  6355. }
  6356. #endif // STB_DEFINE
  6357. #endif // _WIN32
  6358. #endif // STB_NO_STB_STRINGS
  6359. //////////////////////////////////////////////////////////////////////////////
  6360. //
  6361. // STB_MALLOC_WRAPPER
  6362. //
  6363. // you can use the wrapper functions with your own malloc wrapper,
  6364. // or define STB_MALLOC_WRAPPER project-wide to have
  6365. // malloc/free/realloc/strdup all get vectored to it
  6366. // this has too many very specific error messages you could google for and find in stb.h,
  6367. // so don't use it if they don't want any stb.h-identifiable strings
  6368. #if defined(STB_DEFINE) && !defined(STB_NO_STB_STRINGS)
  6369. typedef struct
  6370. {
  6371. void *p;
  6372. char *file;
  6373. int line;
  6374. int size;
  6375. } stb_malloc_record;
  6376. #ifndef STB_MALLOC_HISTORY_COUNT
  6377. #define STB_MALLOC_HISTORY_COUNT 50 // 800 bytes
  6378. #endif
  6379. stb_malloc_record *stb__allocations;
  6380. static int stb__alloc_size, stb__alloc_limit, stb__alloc_mask;
  6381. int stb__alloc_count;
  6382. stb_malloc_record stb__alloc_history[STB_MALLOC_HISTORY_COUNT];
  6383. int stb__history_pos;
  6384. static int stb__hashfind(void *p)
  6385. {
  6386. stb_uint32 h = stb_hashptr(p);
  6387. int s,n = h & stb__alloc_mask;
  6388. if (stb__allocations[n].p == p)
  6389. return n;
  6390. s = stb_rehash(h)|1;
  6391. for(;;) {
  6392. if (stb__allocations[n].p == NULL)
  6393. return -1;
  6394. n = (n+s) & stb__alloc_mask;
  6395. if (stb__allocations[n].p == p)
  6396. return n;
  6397. }
  6398. }
  6399. int stb_wrapper_allocsize(void *p)
  6400. {
  6401. int n = stb__hashfind(p);
  6402. if (n < 0) return 0;
  6403. return stb__allocations[n].size;
  6404. }
  6405. static int stb__historyfind(void *p)
  6406. {
  6407. int n = stb__history_pos;
  6408. int i;
  6409. for (i=0; i < STB_MALLOC_HISTORY_COUNT; ++i) {
  6410. if (--n < 0) n = STB_MALLOC_HISTORY_COUNT-1;
  6411. if (stb__alloc_history[n].p == p)
  6412. return n;
  6413. }
  6414. return -1;
  6415. }
  6416. static void stb__add_alloc(void *p, int sz, char *file, int line);
  6417. static void stb__grow_alloc(void)
  6418. {
  6419. int i,old_num = stb__alloc_size;
  6420. stb_malloc_record *old = stb__allocations;
  6421. if (stb__alloc_size == 0)
  6422. stb__alloc_size = 64;
  6423. else
  6424. stb__alloc_size *= 2;
  6425. stb__allocations = (stb_malloc_record *) stb__realloc_raw(NULL, stb__alloc_size * sizeof(stb__allocations[0]));
  6426. if (stb__allocations == NULL)
  6427. stb_fatal("Internal error: couldn't grow malloc wrapper table");
  6428. memset(stb__allocations, 0, stb__alloc_size * sizeof(stb__allocations[0]));
  6429. stb__alloc_limit = (stb__alloc_size*3)>>2;
  6430. stb__alloc_mask = stb__alloc_size-1;
  6431. stb__alloc_count = 0;
  6432. for (i=0; i < old_num; ++i)
  6433. if (old[i].p > STB_DEL) {
  6434. stb__add_alloc(old[i].p, old[i].size, old[i].file, old[i].line);
  6435. assert(stb__hashfind(old[i].p) >= 0);
  6436. }
  6437. for (i=0; i < old_num; ++i)
  6438. if (old[i].p > STB_DEL)
  6439. assert(stb__hashfind(old[i].p) >= 0);
  6440. stb__realloc_raw(old, 0);
  6441. }
  6442. static void stb__add_alloc(void *p, int sz, char *file, int line)
  6443. {
  6444. stb_uint32 h;
  6445. int n;
  6446. if (stb__alloc_count >= stb__alloc_limit)
  6447. stb__grow_alloc();
  6448. h = stb_hashptr(p);
  6449. n = h & stb__alloc_mask;
  6450. if (stb__allocations[n].p > STB_DEL) {
  6451. int s = stb_rehash(h)|1;
  6452. do {
  6453. n = (n+s) & stb__alloc_mask;
  6454. } while (stb__allocations[n].p > STB_DEL);
  6455. }
  6456. assert(stb__allocations[n].p == NULL || stb__allocations[n].p == STB_DEL);
  6457. stb__allocations[n].p = p;
  6458. stb__allocations[n].size = sz;
  6459. stb__allocations[n].line = line;
  6460. stb__allocations[n].file = file;
  6461. ++stb__alloc_count;
  6462. }
  6463. static void stb__remove_alloc(int n, char *file, int line)
  6464. {
  6465. stb__alloc_history[stb__history_pos] = stb__allocations[n];
  6466. stb__alloc_history[stb__history_pos].file = file;
  6467. stb__alloc_history[stb__history_pos].line = line;
  6468. if (++stb__history_pos == STB_MALLOC_HISTORY_COUNT)
  6469. stb__history_pos = 0;
  6470. stb__allocations[n].p = STB_DEL;
  6471. --stb__alloc_count;
  6472. }
  6473. void stb_wrapper_malloc(void *p, int sz, char *file, int line)
  6474. {
  6475. if (!p) return;
  6476. stb__add_alloc(p,sz,file,line);
  6477. }
  6478. void stb_wrapper_free(void *p, char *file, int line)
  6479. {
  6480. int n;
  6481. if (p == NULL) return;
  6482. n = stb__hashfind(p);
  6483. if (n >= 0)
  6484. stb__remove_alloc(n, file, line);
  6485. else {
  6486. // tried to free something we hadn't allocated!
  6487. n = stb__historyfind(p);
  6488. assert(0); /* NOTREACHED */
  6489. if (n >= 0)
  6490. stb_fatal("Attempted to free %d-byte block %p at %s:%d previously freed/realloced at %s:%d",
  6491. stb__alloc_history[n].size, p,
  6492. file, line,
  6493. stb__alloc_history[n].file, stb__alloc_history[n].line);
  6494. else
  6495. stb_fatal("Attempted to free unknown block %p at %s:%d", p, file,line);
  6496. }
  6497. }
  6498. void stb_wrapper_check(void *p)
  6499. {
  6500. int n;
  6501. if (p == NULL) return;
  6502. n = stb__hashfind(p);
  6503. if (n >= 0) return;
  6504. for (n=0; n < stb__alloc_size; ++n)
  6505. if (stb__allocations[n].p == p)
  6506. stb_fatal("Internal error: pointer %p was allocated, but hash search failed", p);
  6507. // tried to free something that wasn't allocated!
  6508. n = stb__historyfind(p);
  6509. if (n >= 0)
  6510. stb_fatal("Checked %d-byte block %p previously freed/realloced at %s:%d",
  6511. stb__alloc_history[n].size, p,
  6512. stb__alloc_history[n].file, stb__alloc_history[n].line);
  6513. stb_fatal("Checked unknown block %p");
  6514. }
  6515. void stb_wrapper_realloc(void *p, void *q, int sz, char *file, int line)
  6516. {
  6517. int n;
  6518. if (p == NULL) { stb_wrapper_malloc(q, sz, file, line); return; }
  6519. if (q == NULL) return; // nothing happened
  6520. n = stb__hashfind(p);
  6521. if (n == -1) {
  6522. // tried to free something we hadn't allocated!
  6523. // this is weird, though, because we got past the realloc!
  6524. n = stb__historyfind(p);
  6525. assert(0); /* NOTREACHED */
  6526. if (n >= 0)
  6527. stb_fatal("Attempted to realloc %d-byte block %p at %s:%d previously freed/realloced at %s:%d",
  6528. stb__alloc_history[n].size, p,
  6529. file, line,
  6530. stb__alloc_history[n].file, stb__alloc_history[n].line);
  6531. else
  6532. stb_fatal("Attempted to realloc unknown block %p at %s:%d", p, file,line);
  6533. } else {
  6534. if (q == p) {
  6535. stb__allocations[n].size = sz;
  6536. stb__allocations[n].file = file;
  6537. stb__allocations[n].line = line;
  6538. } else {
  6539. stb__remove_alloc(n, file, line);
  6540. stb__add_alloc(q,sz,file,line);
  6541. }
  6542. }
  6543. }
  6544. void stb_wrapper_listall(void (*func)(void *ptr, int sz, char *file, int line))
  6545. {
  6546. int i;
  6547. for (i=0; i < stb__alloc_size; ++i)
  6548. if (stb__allocations[i].p > STB_DEL)
  6549. func(stb__allocations[i].p , stb__allocations[i].size,
  6550. stb__allocations[i].file, stb__allocations[i].line);
  6551. }
  6552. void stb_wrapper_dump(char *filename)
  6553. {
  6554. int i;
  6555. FILE *f = fopen(filename, "w");
  6556. if (!f) return;
  6557. for (i=0; i < stb__alloc_size; ++i)
  6558. if (stb__allocations[i].p > STB_DEL)
  6559. fprintf(f, "%p %7d - %4d %s\n",
  6560. stb__allocations[i].p , stb__allocations[i].size,
  6561. stb__allocations[i].line, stb__allocations[i].file);
  6562. }
  6563. #endif // STB_DEFINE
  6564. //////////////////////////////////////////////////////////////////////////////
  6565. //
  6566. // stb_pointer_set
  6567. //
  6568. //
  6569. // For data structures that support querying by key, data structure
  6570. // classes always hand-wave away the issue of what to do if two entries
  6571. // have the same key: basically, store a linked list of all the nodes
  6572. // which have the same key (a LISP-style list).
  6573. //
  6574. // The thing is, it's not that trivial. If you have an O(log n)
  6575. // lookup data structure, but then n/4 items have the same value,
  6576. // you don't want to spend O(n) time scanning that list when
  6577. // deleting an item if you already have a pointer to the item.
  6578. // (You have to spend O(n) time enumerating all the items with
  6579. // a given key, sure, and you can't accelerate deleting a particular
  6580. // item if you only have the key, not a pointer to the item.)
  6581. //
  6582. // I'm going to call this data structure, whatever it turns out to
  6583. // be, a "pointer set", because we don't store any associated data for
  6584. // items in this data structure, we just answer the question of
  6585. // whether an item is in it or not (it's effectively one bit per pointer).
  6586. // Technically they don't have to be pointers; you could cast ints
  6587. // to (void *) if you want, but you can't store 0 or 1 because of the
  6588. // hash table.
  6589. //
  6590. // Since the fastest data structure we might want to add support for
  6591. // identical-keys to is a hash table with O(1)-ish lookup time,
  6592. // that means that the conceptual "linked list of all items with
  6593. // the same indexed value" that we build needs to have the same
  6594. // performance; that way when we index a table we think is arbitrary
  6595. // ints, but in fact half of them are 0, we don't get screwed.
  6596. //
  6597. // Therefore, it needs to be a hash table, at least when it gets
  6598. // large. On the other hand, when the data has totally arbitrary ints
  6599. // or floats, there won't be many collisions, and we'll have tons of
  6600. // 1-item bitmaps. That will be grossly inefficient as hash tables;
  6601. // trade-off; the hash table is reasonably efficient per-item when
  6602. // it's large, but not when it's small. So we need to do something
  6603. // Judy-like and use different strategies depending on the size.
  6604. //
  6605. // Like Judy, we'll use the bottom bit to encode the strategy:
  6606. //
  6607. // bottom bits:
  6608. // 00 - direct pointer
  6609. // 01 - 4-item bucket (16 bytes, no length, NULLs)
  6610. // 10 - N-item array
  6611. // 11 - hash table
  6612. typedef struct stb_ps stb_ps;
  6613. STB_EXTERN int stb_ps_find (stb_ps *ps, void *value);
  6614. STB_EXTERN stb_ps * stb_ps_add (stb_ps *ps, void *value);
  6615. STB_EXTERN stb_ps * stb_ps_remove(stb_ps *ps, void *value);
  6616. STB_EXTERN stb_ps * stb_ps_remove_any(stb_ps *ps, void **value);
  6617. STB_EXTERN void stb_ps_delete(stb_ps *ps);
  6618. STB_EXTERN int stb_ps_count (stb_ps *ps);
  6619. STB_EXTERN stb_ps * stb_ps_copy (stb_ps *ps);
  6620. STB_EXTERN int stb_ps_subset(stb_ps *bigger, stb_ps *smaller);
  6621. STB_EXTERN int stb_ps_eq (stb_ps *p0, stb_ps *p1);
  6622. STB_EXTERN void ** stb_ps_getlist (stb_ps *ps, int *count);
  6623. STB_EXTERN int stb_ps_writelist(stb_ps *ps, void **list, int size );
  6624. // enum and fastlist don't allocate storage, but you must consume the
  6625. // list before there's any chance the data structure gets screwed up;
  6626. STB_EXTERN int stb_ps_enum (stb_ps *ps, void *data,
  6627. int (*func)(void *value, void*data) );
  6628. STB_EXTERN void ** stb_ps_fastlist(stb_ps *ps, int *count);
  6629. // result:
  6630. // returns a list, *count is the length of that list,
  6631. // but some entries of the list may be invalid;
  6632. // test with 'stb_ps_fastlist_valid(x)'
  6633. #define stb_ps_fastlist_valid(x) ((stb_uinta) (x) > 1)
  6634. #ifdef STB_DEFINE
  6635. enum
  6636. {
  6637. STB_ps_direct = 0,
  6638. STB_ps_bucket = 1,
  6639. STB_ps_array = 2,
  6640. STB_ps_hash = 3,
  6641. };
  6642. #define STB_BUCKET_SIZE 4
  6643. typedef struct
  6644. {
  6645. void *p[STB_BUCKET_SIZE];
  6646. } stb_ps_bucket;
  6647. #define GetBucket(p) ((stb_ps_bucket *) ((char *) (p) - STB_ps_bucket))
  6648. #define EncodeBucket(p) ((stb_ps *) ((char *) (p) + STB_ps_bucket))
  6649. static void stb_bucket_free(stb_ps_bucket *b)
  6650. {
  6651. free(b);
  6652. }
  6653. static stb_ps_bucket *stb_bucket_create2(void *v0, void *v1)
  6654. {
  6655. stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));
  6656. b->p[0] = v0;
  6657. b->p[1] = v1;
  6658. b->p[2] = NULL;
  6659. b->p[3] = NULL;
  6660. return b;
  6661. }
  6662. static stb_ps_bucket * stb_bucket_create3(void **v)
  6663. {
  6664. stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));
  6665. b->p[0] = v[0];
  6666. b->p[1] = v[1];
  6667. b->p[2] = v[2];
  6668. b->p[3] = NULL;
  6669. return b;
  6670. }
  6671. // could use stb_arr, but this will save us memory
  6672. typedef struct
  6673. {
  6674. int count;
  6675. void *p[1];
  6676. } stb_ps_array;
  6677. #define GetArray(p) ((stb_ps_array *) ((char *) (p) - STB_ps_array))
  6678. #define EncodeArray(p) ((stb_ps *) ((char *) (p) + STB_ps_array))
  6679. static int stb_ps_array_max = 13;
  6680. typedef struct
  6681. {
  6682. int size, mask;
  6683. int count, count_deletes;
  6684. int grow_threshhold;
  6685. int shrink_threshhold;
  6686. int rehash_threshhold;
  6687. int any_offset;
  6688. void *table[1];
  6689. } stb_ps_hash;
  6690. #define GetHash(p) ((stb_ps_hash *) ((char *) (p) - STB_ps_hash))
  6691. #define EncodeHash(p) ((stb_ps *) ((char *) (p) + STB_ps_hash))
  6692. #define stb_ps_empty(v) (((stb_uint32) v) <= 1)
  6693. static stb_ps_hash *stb_ps_makehash(int size, int old_size, void **old_data)
  6694. {
  6695. int i;
  6696. stb_ps_hash *h = (stb_ps_hash *) malloc(sizeof(*h) + (size-1) * sizeof(h->table[0]));
  6697. assert(stb_is_pow2(size));
  6698. h->size = size;
  6699. h->mask = size-1;
  6700. h->shrink_threshhold = (int) (0.3f * size);
  6701. h-> grow_threshhold = (int) (0.8f * size);
  6702. h->rehash_threshhold = (int) (0.9f * size);
  6703. h->count = 0;
  6704. h->count_deletes = 0;
  6705. h->any_offset = 0;
  6706. memset(h->table, 0, size * sizeof(h->table[0]));
  6707. for (i=0; i < old_size; ++i)
  6708. if (!stb_ps_empty(old_data[i]))
  6709. stb_ps_add(EncodeHash(h), old_data[i]);
  6710. return h;
  6711. }
  6712. void stb_ps_delete(stb_ps *ps)
  6713. {
  6714. switch (3 & (int) ps) {
  6715. case STB_ps_direct: break;
  6716. case STB_ps_bucket: stb_bucket_free(GetBucket(ps)); break;
  6717. case STB_ps_array : free(GetArray(ps)); break;
  6718. case STB_ps_hash : free(GetHash(ps)); break;
  6719. }
  6720. }
  6721. stb_ps *stb_ps_copy(stb_ps *ps)
  6722. {
  6723. int i;
  6724. // not a switch: order based on expected performance/power-law distribution
  6725. switch (3 & (int) ps) {
  6726. case STB_ps_direct: return ps;
  6727. case STB_ps_bucket: {
  6728. stb_ps_bucket *n = (stb_ps_bucket *) malloc(sizeof(*n));
  6729. *n = *GetBucket(ps);
  6730. return EncodeBucket(n);
  6731. }
  6732. case STB_ps_array: {
  6733. stb_ps_array *a = GetArray(ps);
  6734. stb_ps_array *n = (stb_ps_array *) malloc(sizeof(*n) + stb_ps_array_max * sizeof(n->p[0]));
  6735. n->count = a->count;
  6736. for (i=0; i < a->count; ++i)
  6737. n->p[i] = a->p[i];
  6738. return EncodeArray(n);
  6739. }
  6740. case STB_ps_hash: {
  6741. stb_ps_hash *h = GetHash(ps);
  6742. stb_ps_hash *n = stb_ps_makehash(h->size, h->size, h->table);
  6743. return EncodeHash(n);
  6744. }
  6745. }
  6746. assert(0); /* NOTREACHED */
  6747. return NULL;
  6748. }
  6749. int stb_ps_find(stb_ps *ps, void *value)
  6750. {
  6751. int i, code = 3 & (int) ps;
  6752. assert((3 & (int) value) == STB_ps_direct);
  6753. assert(stb_ps_fastlist_valid(value));
  6754. // not a switch: order based on expected performance/power-law distribution
  6755. if (code == STB_ps_direct)
  6756. return value == ps;
  6757. if (code == STB_ps_bucket) {
  6758. stb_ps_bucket *b = GetBucket(ps);
  6759. assert(STB_BUCKET_SIZE == 4);
  6760. if (b->p[0] == value || b->p[1] == value ||
  6761. b->p[2] == value || b->p[3] == value)
  6762. return STB_TRUE;
  6763. return STB_FALSE;
  6764. }
  6765. if (code == STB_ps_array) {
  6766. stb_ps_array *a = GetArray(ps);
  6767. for (i=0; i < a->count; ++i)
  6768. if (a->p[i] == value)
  6769. return STB_TRUE;
  6770. return STB_FALSE;
  6771. } else {
  6772. stb_ps_hash *h = GetHash(ps);
  6773. stb_uint32 hash = stb_hashptr(value);
  6774. stb_uint32 s, n = hash & h->mask;
  6775. void **t = h->table;
  6776. if (t[n] == value) return STB_TRUE;
  6777. if (t[n] == NULL) return STB_FALSE;
  6778. s = stb_rehash(hash) | 1;
  6779. do {
  6780. n = (n + s) & h->mask;
  6781. if (t[n] == value) return STB_TRUE;
  6782. } while (t[n] != NULL);
  6783. return STB_FALSE;
  6784. }
  6785. }
  6786. stb_ps * stb_ps_add (stb_ps *ps, void *value)
  6787. {
  6788. #ifdef STB_DEBUG
  6789. assert(!stb_ps_find(ps,value));
  6790. #endif
  6791. if (value == NULL) return ps; // ignore NULL adds to avoid bad breakage
  6792. assert((3 & (int) value) == STB_ps_direct);
  6793. assert(stb_ps_fastlist_valid(value));
  6794. assert(value != STB_DEL); // STB_DEL is less likely
  6795. switch (3 & (int) ps) {
  6796. case STB_ps_direct:
  6797. if (ps == NULL) return (stb_ps *) value;
  6798. return EncodeBucket(stb_bucket_create2(ps,value));
  6799. case STB_ps_bucket: {
  6800. stb_ps_bucket *b = GetBucket(ps);
  6801. stb_ps_array *a;
  6802. assert(STB_BUCKET_SIZE == 4);
  6803. if (b->p[0] == NULL) { b->p[0] = value; return ps; }
  6804. if (b->p[1] == NULL) { b->p[1] = value; return ps; }
  6805. if (b->p[2] == NULL) { b->p[2] = value; return ps; }
  6806. if (b->p[3] == NULL) { b->p[3] = value; return ps; }
  6807. a = (stb_ps_array *) malloc(sizeof(*a) + 7 * sizeof(a->p[0])); // 8 slots, must be 2^k
  6808. memcpy(a->p, b, sizeof(*b));
  6809. a->p[4] = value;
  6810. a->count = 5;
  6811. stb_bucket_free(b);
  6812. return EncodeArray(a);
  6813. }
  6814. case STB_ps_array: {
  6815. stb_ps_array *a = GetArray(ps);
  6816. if (a->count == stb_ps_array_max) {
  6817. // promote from array to hash
  6818. stb_ps_hash *h = stb_ps_makehash(2 << stb_log2_ceil(a->count), a->count, a->p);
  6819. free(a);
  6820. return stb_ps_add(EncodeHash(h), value);
  6821. }
  6822. // do we need to resize the array? the array doubles in size when it
  6823. // crosses a power-of-two
  6824. if ((a->count & (a->count-1))==0) {
  6825. int newsize = a->count*2;
  6826. // clamp newsize to max if:
  6827. // 1. it's larger than max
  6828. // 2. newsize*1.5 is larger than max (to avoid extra resizing)
  6829. if (newsize + a->count > stb_ps_array_max)
  6830. newsize = stb_ps_array_max;
  6831. a = (stb_ps_array *) realloc(a, sizeof(*a) + (newsize-1) * sizeof(a->p[0]));
  6832. }
  6833. a->p[a->count++] = value;
  6834. return EncodeArray(a);
  6835. }
  6836. case STB_ps_hash: {
  6837. stb_ps_hash *h = GetHash(ps);
  6838. stb_uint32 hash = stb_hashptr(value);
  6839. stb_uint32 n = hash & h->mask;
  6840. void **t = h->table;
  6841. // find first NULL or STB_DEL entry
  6842. if (!stb_ps_empty(t[n])) {
  6843. stb_uint32 s = stb_rehash(hash) | 1;
  6844. do {
  6845. n = (n + s) & h->mask;
  6846. } while (!stb_ps_empty(t[n]));
  6847. }
  6848. if (t[n] == STB_DEL)
  6849. -- h->count_deletes;
  6850. t[n] = value;
  6851. ++ h->count;
  6852. if (h->count == h->grow_threshhold) {
  6853. stb_ps_hash *h2 = stb_ps_makehash(h->size*2, h->size, t);
  6854. free(h);
  6855. return EncodeHash(h2);
  6856. }
  6857. if (h->count + h->count_deletes == h->rehash_threshhold) {
  6858. stb_ps_hash *h2 = stb_ps_makehash(h->size, h->size, t);
  6859. free(h);
  6860. return EncodeHash(h2);
  6861. }
  6862. return ps;
  6863. }
  6864. }
  6865. return NULL; /* NOTREACHED */
  6866. }
  6867. stb_ps *stb_ps_remove(stb_ps *ps, void *value)
  6868. {
  6869. #ifdef STB_DEBUG
  6870. assert(stb_ps_find(ps, value));
  6871. #endif
  6872. assert((3 & (int) value) == STB_ps_direct);
  6873. if (value == NULL) return ps; // ignore NULL removes to avoid bad breakage
  6874. switch (3 & (int) ps) {
  6875. case STB_ps_direct:
  6876. return ps == value ? NULL : ps;
  6877. case STB_ps_bucket: {
  6878. stb_ps_bucket *b = GetBucket(ps);
  6879. int count=0;
  6880. assert(STB_BUCKET_SIZE == 4);
  6881. if (b->p[0] == value) b->p[0] = NULL; else count += (b->p[0] != NULL);
  6882. if (b->p[1] == value) b->p[1] = NULL; else count += (b->p[1] != NULL);
  6883. if (b->p[2] == value) b->p[2] = NULL; else count += (b->p[2] != NULL);
  6884. if (b->p[3] == value) b->p[3] = NULL; else count += (b->p[3] != NULL);
  6885. if (count == 1) { // shrink bucket at size 1
  6886. value = b->p[0];
  6887. if (value == NULL) value = b->p[1];
  6888. if (value == NULL) value = b->p[2];
  6889. if (value == NULL) value = b->p[3];
  6890. assert(value != NULL);
  6891. stb_bucket_free(b);
  6892. return (stb_ps *) value; // return STB_ps_direct of value
  6893. }
  6894. return ps;
  6895. }
  6896. case STB_ps_array: {
  6897. stb_ps_array *a = GetArray(ps);
  6898. int i;
  6899. for (i=0; i < a->count; ++i) {
  6900. if (a->p[i] == value) {
  6901. a->p[i] = a->p[--a->count];
  6902. if (a->count == 3) { // shrink to bucket!
  6903. stb_ps_bucket *b = stb_bucket_create3(a->p);
  6904. free(a);
  6905. return EncodeBucket(b);
  6906. }
  6907. return ps;
  6908. }
  6909. }
  6910. return ps;
  6911. }
  6912. case STB_ps_hash: {
  6913. stb_ps_hash *h = GetHash(ps);
  6914. stb_uint32 hash = stb_hashptr(value);
  6915. stb_uint32 s, n = hash & h->mask;
  6916. void **t = h->table;
  6917. if (t[n] != value) {
  6918. s = stb_rehash(hash) | 1;
  6919. do {
  6920. n = (n + s) & h->mask;
  6921. } while (t[n] != value);
  6922. }
  6923. t[n] = STB_DEL;
  6924. -- h->count;
  6925. ++ h->count_deletes;
  6926. // should we shrink down to an array?
  6927. if (h->count < stb_ps_array_max) {
  6928. int n = 1 << stb_log2_floor(stb_ps_array_max);
  6929. if (h->count < n) {
  6930. stb_ps_array *a = (stb_ps_array *) malloc(sizeof(*a) + (n-1) * sizeof(a->p[0]));
  6931. int i,j=0;
  6932. for (i=0; i < h->size; ++i)
  6933. if (!stb_ps_empty(t[i]))
  6934. a->p[j++] = t[i];
  6935. assert(j == h->count);
  6936. a->count = j;
  6937. free(h);
  6938. return EncodeArray(a);
  6939. }
  6940. }
  6941. if (h->count == h->shrink_threshhold) {
  6942. stb_ps_hash *h2 = stb_ps_makehash(h->size >> 1, h->size, t);
  6943. free(h);
  6944. return EncodeHash(h2);
  6945. }
  6946. return ps;
  6947. }
  6948. }
  6949. return ps; /* NOTREACHED */
  6950. }
  6951. stb_ps *stb_ps_remove_any(stb_ps *ps, void **value)
  6952. {
  6953. assert(ps != NULL);
  6954. switch (3 & (int) ps) {
  6955. case STB_ps_direct:
  6956. *value = ps;
  6957. return NULL;
  6958. case STB_ps_bucket: {
  6959. stb_ps_bucket *b = GetBucket(ps);
  6960. int count=0, slast=0, last=0;
  6961. assert(STB_BUCKET_SIZE == 4);
  6962. if (b->p[0]) { ++count; last = 0; }
  6963. if (b->p[1]) { ++count; slast = last; last = 1; }
  6964. if (b->p[2]) { ++count; slast = last; last = 2; }
  6965. if (b->p[3]) { ++count; slast = last; last = 3; }
  6966. *value = b->p[last];
  6967. b->p[last] = 0;
  6968. if (count == 2) {
  6969. void *leftover = b->p[slast]; // second to last
  6970. stb_bucket_free(b);
  6971. return (stb_ps *) leftover;
  6972. }
  6973. return ps;
  6974. }
  6975. case STB_ps_array: {
  6976. stb_ps_array *a = GetArray(ps);
  6977. *value = a->p[a->count-1];
  6978. if (a->count == 4)
  6979. return stb_ps_remove(ps, *value);
  6980. --a->count;
  6981. return ps;
  6982. }
  6983. case STB_ps_hash: {
  6984. stb_ps_hash *h = GetHash(ps);
  6985. void **t = h->table;
  6986. stb_uint32 n = h->any_offset;
  6987. while (stb_ps_empty(t[n]))
  6988. n = (n + 1) & h->mask;
  6989. *value = t[n];
  6990. h->any_offset = (n+1) & h->mask;
  6991. // check if we need to skip down to the previous type
  6992. if (h->count-1 < stb_ps_array_max || h->count-1 == h->shrink_threshhold)
  6993. return stb_ps_remove(ps, *value);
  6994. t[n] = STB_DEL;
  6995. -- h->count;
  6996. ++ h->count_deletes;
  6997. return ps;
  6998. }
  6999. }
  7000. return ps; /* NOTREACHED */
  7001. }
  7002. void ** stb_ps_getlist(stb_ps *ps, int *count)
  7003. {
  7004. int i,n=0;
  7005. void **p = NULL;
  7006. switch (3 & (int) ps) {
  7007. case STB_ps_direct:
  7008. if (ps == NULL) { *count = 0; return NULL; }
  7009. p = (void **) malloc(sizeof(*p) * 1);
  7010. p[0] = ps;
  7011. *count = 1;
  7012. return p;
  7013. case STB_ps_bucket: {
  7014. stb_ps_bucket *b = GetBucket(ps);
  7015. p = (void **) malloc(sizeof(*p) * STB_BUCKET_SIZE);
  7016. for (i=0; i < STB_BUCKET_SIZE; ++i)
  7017. if (b->p[i] != NULL)
  7018. p[n++] = b->p[i];
  7019. break;
  7020. }
  7021. case STB_ps_array: {
  7022. stb_ps_array *a = GetArray(ps);
  7023. p = (void **) malloc(sizeof(*p) * a->count);
  7024. memcpy(p, a->p, sizeof(*p) * a->count);
  7025. *count = a->count;
  7026. return p;
  7027. }
  7028. case STB_ps_hash: {
  7029. stb_ps_hash *h = GetHash(ps);
  7030. p = (void **) malloc(sizeof(*p) * h->count);
  7031. for (i=0; i < h->size; ++i)
  7032. if (!stb_ps_empty(h->table[i]))
  7033. p[n++] = h->table[i];
  7034. break;
  7035. }
  7036. }
  7037. *count = n;
  7038. return p;
  7039. }
  7040. int stb_ps_writelist(stb_ps *ps, void **list, int size )
  7041. {
  7042. int i,n=0;
  7043. switch (3 & (int) ps) {
  7044. case STB_ps_direct:
  7045. if (ps == NULL || size <= 0) return 0;
  7046. list[0] = ps;
  7047. return 1;
  7048. case STB_ps_bucket: {
  7049. stb_ps_bucket *b = GetBucket(ps);
  7050. for (i=0; i < STB_BUCKET_SIZE; ++i)
  7051. if (b->p[i] != NULL && n < size)
  7052. list[n++] = b->p[i];
  7053. return n;
  7054. }
  7055. case STB_ps_array: {
  7056. stb_ps_array *a = GetArray(ps);
  7057. n = stb_min(size, a->count);
  7058. memcpy(list, a->p, sizeof(*list) * n);
  7059. return n;
  7060. }
  7061. case STB_ps_hash: {
  7062. stb_ps_hash *h = GetHash(ps);
  7063. if (size <= 0) return 0;
  7064. for (i=0; i < h->count; ++i) {
  7065. if (!stb_ps_empty(h->table[i])) {
  7066. list[n++] = h->table[i];
  7067. if (n == size) break;
  7068. }
  7069. }
  7070. return n;
  7071. }
  7072. }
  7073. return 0; /* NOTREACHED */
  7074. }
  7075. int stb_ps_enum(stb_ps *ps, void *data, int (*func)(void *value, void *data))
  7076. {
  7077. int i;
  7078. switch (3 & (int) ps) {
  7079. case STB_ps_direct:
  7080. if (ps == NULL) return STB_TRUE;
  7081. return func(ps, data);
  7082. case STB_ps_bucket: {
  7083. stb_ps_bucket *b = GetBucket(ps);
  7084. for (i=0; i < STB_BUCKET_SIZE; ++i)
  7085. if (b->p[i] != NULL)
  7086. if (!func(b->p[i], data))
  7087. return STB_FALSE;
  7088. return STB_TRUE;
  7089. }
  7090. case STB_ps_array: {
  7091. stb_ps_array *a = GetArray(ps);
  7092. for (i=0; i < a->count; ++i)
  7093. if (!func(a->p[i], data))
  7094. return STB_FALSE;
  7095. return STB_TRUE;
  7096. }
  7097. case STB_ps_hash: {
  7098. stb_ps_hash *h = GetHash(ps);
  7099. for (i=0; i < h->count; ++i)
  7100. if (!stb_ps_empty(h->table[i]))
  7101. if (!func(h->table[i], data))
  7102. return STB_FALSE;
  7103. return STB_TRUE;
  7104. }
  7105. }
  7106. return STB_TRUE; /* NOTREACHED */
  7107. }
  7108. int stb_ps_count (stb_ps *ps)
  7109. {
  7110. switch (3 & (int) ps) {
  7111. case STB_ps_direct:
  7112. return ps != NULL;
  7113. case STB_ps_bucket: {
  7114. stb_ps_bucket *b = GetBucket(ps);
  7115. return (b->p[0] != NULL) + (b->p[1] != NULL) +
  7116. (b->p[2] != NULL) + (b->p[3] != NULL);
  7117. }
  7118. case STB_ps_array: {
  7119. stb_ps_array *a = GetArray(ps);
  7120. return a->count;
  7121. }
  7122. case STB_ps_hash: {
  7123. stb_ps_hash *h = GetHash(ps);
  7124. return h->count;
  7125. }
  7126. }
  7127. return 0;
  7128. }
  7129. void ** stb_ps_fastlist(stb_ps *ps, int *count)
  7130. {
  7131. static void *storage;
  7132. switch (3 & (int) ps) {
  7133. case STB_ps_direct:
  7134. if (ps == NULL) { *count = 0; return NULL; }
  7135. storage = ps;
  7136. *count = 1;
  7137. return &storage;
  7138. case STB_ps_bucket: {
  7139. stb_ps_bucket *b = GetBucket(ps);
  7140. *count = STB_BUCKET_SIZE;
  7141. return b->p;
  7142. }
  7143. case STB_ps_array: {
  7144. stb_ps_array *a = GetArray(ps);
  7145. *count = a->count;
  7146. return a->p;
  7147. }
  7148. case STB_ps_hash: {
  7149. stb_ps_hash *h = GetHash(ps);
  7150. *count = h->size;
  7151. return h->table;
  7152. }
  7153. }
  7154. return NULL; /* NOTREACHED */
  7155. }
  7156. int stb_ps_subset(stb_ps *bigger, stb_ps *smaller)
  7157. {
  7158. int i, listlen;
  7159. void **list = stb_ps_fastlist(smaller, &listlen);
  7160. for(i=0; i < listlen; ++i)
  7161. if (stb_ps_fastlist_valid(list[i]))
  7162. if (!stb_ps_find(bigger, list[i]))
  7163. return 0;
  7164. return 1;
  7165. }
  7166. int stb_ps_eq(stb_ps *p0, stb_ps *p1)
  7167. {
  7168. if (stb_ps_count(p0) != stb_ps_count(p1))
  7169. return 0;
  7170. return stb_ps_subset(p0, p1);
  7171. }
  7172. #undef GetBucket
  7173. #undef GetArray
  7174. #undef GetHash
  7175. #undef EncodeBucket
  7176. #undef EncodeArray
  7177. #undef EncodeHash
  7178. #endif
  7179. //////////////////////////////////////////////////////////////////////////////
  7180. //
  7181. // Random Numbers via Meresenne Twister or LCG
  7182. //
  7183. STB_EXTERN unsigned long stb_srandLCG(unsigned long seed);
  7184. STB_EXTERN unsigned long stb_randLCG(void);
  7185. STB_EXTERN double stb_frandLCG(void);
  7186. STB_EXTERN void stb_srand(unsigned long seed);
  7187. STB_EXTERN unsigned long stb_rand(void);
  7188. STB_EXTERN double stb_frand(void);
  7189. STB_EXTERN void stb_shuffle(void *p, size_t n, size_t sz,
  7190. unsigned long seed);
  7191. STB_EXTERN void stb_reverse(void *p, size_t n, size_t sz);
  7192. STB_EXTERN unsigned long stb_randLCG_explicit(unsigned long seed);
  7193. #define stb_rand_define(x,y) \
  7194. \
  7195. unsigned long x(void) \
  7196. { \
  7197. static unsigned long stb__rand = y; \
  7198. stb__rand = stb__rand * 2147001325 + 715136305; /* BCPL */ \
  7199. return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16)); \
  7200. }
  7201. #ifdef STB_DEFINE
  7202. unsigned long stb_randLCG_explicit(unsigned long seed)
  7203. {
  7204. return seed * 2147001325 + 715136305;
  7205. }
  7206. static unsigned long stb__rand_seed=0;
  7207. unsigned long stb_srandLCG(unsigned long seed)
  7208. {
  7209. unsigned long previous = stb__rand_seed;
  7210. stb__rand_seed = seed;
  7211. return previous;
  7212. }
  7213. unsigned long stb_randLCG(void)
  7214. {
  7215. stb__rand_seed = stb__rand_seed * 2147001325 + 715136305; // BCPL generator
  7216. // shuffle non-random bits to the middle, and xor to decorrelate with seed
  7217. return 0x31415926 ^ ((stb__rand_seed >> 16) + (stb__rand_seed << 16));
  7218. }
  7219. double stb_frandLCG(void)
  7220. {
  7221. return stb_randLCG() / ((double) (1 << 16) * (1 << 16));
  7222. }
  7223. void stb_shuffle(void *p, size_t n, size_t sz, unsigned long seed)
  7224. {
  7225. char *a;
  7226. unsigned long old_seed;
  7227. int i;
  7228. if (seed)
  7229. old_seed = stb_srandLCG(seed);
  7230. a = (char *) p + (n-1) * sz;
  7231. for (i=n; i > 1; --i) {
  7232. int j = stb_randLCG() % i;
  7233. stb_swap(a, (char *) p + j * sz, sz);
  7234. a -= sz;
  7235. }
  7236. if (seed)
  7237. stb_srandLCG(old_seed);
  7238. }
  7239. void stb_reverse(void *p, size_t n, size_t sz)
  7240. {
  7241. int i,j = n-1;
  7242. for (i=0; i < j; ++i,--j) {
  7243. stb_swap((char *) p + i * sz, (char *) p + j * sz, sz);
  7244. }
  7245. }
  7246. // public domain Mersenne Twister by Michael Brundage
  7247. #define STB__MT_LEN 624
  7248. int stb__mt_index = STB__MT_LEN*sizeof(unsigned long)+1;
  7249. unsigned long stb__mt_buffer[STB__MT_LEN];
  7250. void stb_srand(unsigned long seed)
  7251. {
  7252. int i;
  7253. unsigned long old = stb_srandLCG(seed);
  7254. for (i = 0; i < STB__MT_LEN; i++)
  7255. stb__mt_buffer[i] = stb_randLCG();
  7256. stb_srandLCG(old);
  7257. stb__mt_index = STB__MT_LEN*sizeof(unsigned long);
  7258. }
  7259. #define STB__MT_IA 397
  7260. #define STB__MT_IB (STB__MT_LEN - STB__MT_IA)
  7261. #define STB__UPPER_MASK 0x80000000
  7262. #define STB__LOWER_MASK 0x7FFFFFFF
  7263. #define STB__MATRIX_A 0x9908B0DF
  7264. #define STB__TWIST(b,i,j) ((b)[i] & STB__UPPER_MASK) | ((b)[j] & STB__LOWER_MASK)
  7265. #define STB__MAGIC(s) (((s)&1)*STB__MATRIX_A)
  7266. unsigned long stb_rand()
  7267. {
  7268. unsigned long * b = stb__mt_buffer;
  7269. int idx = stb__mt_index;
  7270. unsigned long s,r;
  7271. int i;
  7272. if (idx >= STB__MT_LEN*sizeof(unsigned long)) {
  7273. if (idx > STB__MT_LEN*sizeof(unsigned long))
  7274. stb_srand(0);
  7275. idx = 0;
  7276. i = 0;
  7277. for (; i < STB__MT_IB; i++) {
  7278. s = STB__TWIST(b, i, i+1);
  7279. b[i] = b[i + STB__MT_IA] ^ (s >> 1) ^ STB__MAGIC(s);
  7280. }
  7281. for (; i < STB__MT_LEN-1; i++) {
  7282. s = STB__TWIST(b, i, i+1);
  7283. b[i] = b[i - STB__MT_IB] ^ (s >> 1) ^ STB__MAGIC(s);
  7284. }
  7285. s = STB__TWIST(b, STB__MT_LEN-1, 0);
  7286. b[STB__MT_LEN-1] = b[STB__MT_IA-1] ^ (s >> 1) ^ STB__MAGIC(s);
  7287. }
  7288. stb__mt_index = idx + sizeof(unsigned long);
  7289. r = *(unsigned long *)((unsigned char *)b + idx);
  7290. r ^= (r >> 11);
  7291. r ^= (r << 7) & 0x9D2C5680;
  7292. r ^= (r << 15) & 0xEFC60000;
  7293. r ^= (r >> 18);
  7294. return r;
  7295. }
  7296. double stb_frand(void)
  7297. {
  7298. return stb_rand() / ((double) (1 << 16) * (1 << 16));
  7299. }
  7300. #endif
  7301. //////////////////////////////////////////////////////////////////////////////
  7302. //
  7303. // stb_dupe
  7304. //
  7305. // stb_dupe is a duplicate-finding system for very, very large data
  7306. // structures--large enough that sorting is too slow, but not so large
  7307. // that we can't keep all the data in memory. using it works as follows:
  7308. //
  7309. // 1. create an stb_dupe:
  7310. // provide a hash function
  7311. // provide an equality function
  7312. // provide an estimate for the size
  7313. // optionally provide a comparison function
  7314. //
  7315. // 2. traverse your data, 'adding' pointers to the stb_dupe
  7316. //
  7317. // 3. finish and ask for duplicates
  7318. //
  7319. // the stb_dupe will discard its intermediate data and build
  7320. // a collection of sorted lists of duplicates, with non-duplicate
  7321. // entries omitted entirely
  7322. //
  7323. //
  7324. // Implementation strategy:
  7325. //
  7326. // while collecting the N items, we keep a hash table of approximate
  7327. // size sqrt(N). (if you tell use the N up front, the hash table is
  7328. // just that size exactly)
  7329. //
  7330. // each entry in the hash table is just an stb__arr of pointers (no need
  7331. // to use stb_ps, because we don't need to delete from these)
  7332. //
  7333. // for step 3, for each entry in the hash table, we apply stb_dupe to it
  7334. // recursively. once the size gets small enough (or doesn't decrease
  7335. // significantly), we switch to either using qsort() on the comparison
  7336. // function, or else we just do the icky N^2 gather
  7337. typedef struct stb_dupe stb_dupe;
  7338. typedef int (*stb_compare_func)(void *a, void *b);
  7339. typedef int (*stb_hash_func)(void *a, unsigned int seed);
  7340. STB_EXTERN void stb_dupe_free(stb_dupe *sd);
  7341. STB_EXTERN stb_dupe *stb_dupe_create(stb_hash_func hash,
  7342. stb_compare_func eq, int size, stb_compare_func ineq);
  7343. STB_EXTERN void stb_dupe_add(stb_dupe *sd, void *item);
  7344. STB_EXTERN void stb_dupe_finish(stb_dupe *sd);
  7345. STB_EXTERN int stb_dupe_numsets(stb_dupe *sd);
  7346. STB_EXTERN void **stb_dupe_set(stb_dupe *sd, int num);
  7347. STB_EXTERN int stb_dupe_set_count(stb_dupe *sd, int num);
  7348. struct stb_dupe
  7349. {
  7350. void ***hash_table;
  7351. int hash_size;
  7352. int size_log2;
  7353. int population;
  7354. int hash_shift;
  7355. stb_hash_func hash;
  7356. stb_compare_func eq;
  7357. stb_compare_func ineq;
  7358. void ***dupes;
  7359. };
  7360. #ifdef STB_DEFINE
  7361. int stb_dupe_numsets(stb_dupe *sd)
  7362. {
  7363. assert(sd->hash_table == NULL);
  7364. return stb_arr_len(sd->dupes);
  7365. }
  7366. void **stb_dupe_set(stb_dupe *sd, int num)
  7367. {
  7368. assert(sd->hash_table == NULL);
  7369. return sd->dupes[num];
  7370. }
  7371. int stb_dupe_set_count(stb_dupe *sd, int num)
  7372. {
  7373. assert(sd->hash_table == NULL);
  7374. return stb_arr_len(sd->dupes[num]);
  7375. }
  7376. stb_dupe *stb_dupe_create(stb_hash_func hash, stb_compare_func eq, int size,
  7377. stb_compare_func ineq)
  7378. {
  7379. int i, hsize;
  7380. stb_dupe *sd = (stb_dupe *) malloc(sizeof(*sd));
  7381. sd->size_log2 = 4;
  7382. hsize = 1 << sd->size_log2;
  7383. while (hsize * hsize < size) {
  7384. ++sd->size_log2;
  7385. hsize *= 2;
  7386. }
  7387. sd->hash = hash;
  7388. sd->eq = eq;
  7389. sd->ineq = ineq;
  7390. sd->hash_shift = 0;
  7391. sd->population = 0;
  7392. sd->hash_size = hsize;
  7393. sd->hash_table = (void ***) malloc(sizeof(*sd->hash_table) * hsize);
  7394. for (i=0; i < hsize; ++i)
  7395. sd->hash_table[i] = NULL;
  7396. sd->dupes = NULL;
  7397. return sd;
  7398. }
  7399. void stb_dupe_add(stb_dupe *sd, void *item)
  7400. {
  7401. stb_uint32 hash = sd->hash(item, sd->hash_shift);
  7402. int z = hash & (sd->hash_size-1);
  7403. stb_arr_push(sd->hash_table[z], item);
  7404. ++sd->population;
  7405. }
  7406. void stb_dupe_free(stb_dupe *sd)
  7407. {
  7408. int i;
  7409. for (i=0; i < stb_arr_len(sd->dupes); ++i)
  7410. if (sd->dupes[i])
  7411. stb_arr_free(sd->dupes[i]);
  7412. stb_arr_free(sd->dupes);
  7413. free(sd);
  7414. }
  7415. static stb_compare_func stb__compare;
  7416. static int stb__dupe_compare(const void *a, const void *b)
  7417. {
  7418. void *p = *(void **) a;
  7419. void *q = *(void **) b;
  7420. return stb__compare(p,q);
  7421. }
  7422. void stb_dupe_finish(stb_dupe *sd)
  7423. {
  7424. int i,j,k;
  7425. assert(sd->dupes == NULL);
  7426. for (i=0; i < sd->hash_size; ++i) {
  7427. void ** list = sd->hash_table[i];
  7428. if (list != NULL) {
  7429. int n = stb_arr_len(list);
  7430. // @TODO: measure to find good numbers instead of just making them up!
  7431. int thresh = (sd->ineq ? 200 : 20);
  7432. // if n is large enough to be worth it, and n is smaller than
  7433. // before (so we can guarantee we'll use a smaller hash table);
  7434. // and there are enough hash bits left, assuming full 32-bit hash
  7435. if (n > thresh && n < (sd->population >> 3) && sd->hash_shift + sd->size_log2*2 < 32) {
  7436. // recursively process this row using stb_dupe, O(N log log N)
  7437. stb_dupe *d = stb_dupe_create(sd->hash, sd->eq, n, sd->ineq);
  7438. d->hash_shift = stb_randLCG_explicit(sd->hash_shift);
  7439. for (j=0; j < n; ++j)
  7440. stb_dupe_add(d, list[j]);
  7441. stb_arr_free(sd->hash_table[i]);
  7442. stb_dupe_finish(d);
  7443. for (j=0; j < stb_arr_len(d->dupes); ++j) {
  7444. stb_arr_push(sd->dupes, d->dupes[j]);
  7445. d->dupes[j] = NULL; // take over ownership
  7446. }
  7447. stb_dupe_free(d);
  7448. } else if (sd->ineq) {
  7449. // process this row using qsort(), O(N log N)
  7450. stb__compare = sd->ineq;
  7451. qsort(list, n, sizeof(list[0]), stb__dupe_compare);
  7452. // find equal subsequences of the list
  7453. for (j=0; j < n-1; ) {
  7454. // find a subsequence from j..k
  7455. for (k=j; k < n; ++k)
  7456. // only use ineq so eq can be left undefined
  7457. if (sd->ineq(list[j], list[k]))
  7458. break;
  7459. // k is the first one not in the subsequence
  7460. if (k-j > 1) {
  7461. void **mylist = NULL;
  7462. stb_arr_setlen(mylist, k-j);
  7463. memcpy(mylist, list+j, sizeof(list[j]) * (k-j));
  7464. stb_arr_push(sd->dupes, mylist);
  7465. }
  7466. j = k;
  7467. }
  7468. stb_arr_free(sd->hash_table[i]);
  7469. } else {
  7470. // process this row using eq(), O(N^2)
  7471. for (j=0; j < n; ++j) {
  7472. if (list[j] != NULL) {
  7473. void **output = NULL;
  7474. for (k=j+1; k < n; ++k) {
  7475. if (sd->eq(list[j], list[k])) {
  7476. if (output == NULL)
  7477. stb_arr_push(output, list[j]);
  7478. stb_arr_push(output, list[k]);
  7479. list[k] = NULL;
  7480. }
  7481. }
  7482. list[j] = NULL;
  7483. if (output)
  7484. stb_arr_push(sd->dupes, output);
  7485. }
  7486. }
  7487. stb_arr_free(sd->hash_table[i]);
  7488. }
  7489. }
  7490. }
  7491. free(sd->hash_table);
  7492. sd->hash_table = NULL;
  7493. }
  7494. #endif
  7495. //////////////////////////////////////////////////////////////////////////////
  7496. //
  7497. // templatized Sort routine
  7498. //
  7499. // This is an attempt to implement a templated sorting algorithm.
  7500. // To use it, you have to explicitly instantiate it as a _function_,
  7501. // then you call that function. This allows the comparison to be inlined,
  7502. // giving the sort similar performance to C++ sorts.
  7503. //
  7504. // It implements quicksort with three-way-median partitioning (generally
  7505. // well-behaved), with a final insertion sort pass.
  7506. //
  7507. // When you define the compare expression, you should assume you have
  7508. // elements of your array pointed to by 'a' and 'b', and perform the comparison
  7509. // on those. OR you can use one or more statements; first say '0;', then
  7510. // write whatever code you want, and compute the result into a variable 'c'.
  7511. #define stb_declare_sort(FUNCNAME, TYPE) \
  7512. void FUNCNAME(TYPE *p, int n)
  7513. #define stb_define_sort(FUNCNAME,TYPE,COMPARE) \
  7514. stb__define_sort( void, FUNCNAME,TYPE,COMPARE)
  7515. #define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \
  7516. stb__define_sort(static void, FUNCNAME,TYPE,COMPARE)
  7517. #define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE) \
  7518. \
  7519. static void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n) \
  7520. { \
  7521. int i,j; \
  7522. for (i=1; i < n; ++i) { \
  7523. TYPE t = p[i], *a = &t; \
  7524. j = i; \
  7525. while (j > 0) { \
  7526. TYPE *b = &p[j-1]; \
  7527. int c = COMPARE; \
  7528. if (!c) break; \
  7529. p[j] = p[j-1]; \
  7530. --j; \
  7531. } \
  7532. if (i != j) \
  7533. p[j] = t; \
  7534. } \
  7535. } \
  7536. \
  7537. static void STB_(FUNCNAME,_quicksort)(TYPE *p, int n) \
  7538. { \
  7539. /* threshhold for transitioning to insertion sort */ \
  7540. while (n > 12) { \
  7541. TYPE *a,*b,t; \
  7542. int c01,c12,c,m,i,j; \
  7543. \
  7544. /* compute median of three */ \
  7545. m = n >> 1; \
  7546. a = &p[0]; \
  7547. b = &p[m]; \
  7548. c = COMPARE; \
  7549. c01 = c; \
  7550. a = &p[m]; \
  7551. b = &p[n-1]; \
  7552. c = COMPARE; \
  7553. c12 = c; \
  7554. /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ \
  7555. if (c01 != c12) { \
  7556. /* otherwise, we'll need to swap something else to middle */ \
  7557. int z; \
  7558. a = &p[0]; \
  7559. b = &p[n-1]; \
  7560. c = COMPARE; \
  7561. /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ \
  7562. /* 0<mid && mid>n: 0>n => 0; 0<n => n */ \
  7563. z = (c == c12) ? 0 : n-1; \
  7564. t = p[z]; \
  7565. p[z] = p[m]; \
  7566. p[m] = t; \
  7567. } \
  7568. /* now p[m] is the median-of-three */ \
  7569. /* swap it to the beginning so it won't move around */ \
  7570. t = p[0]; \
  7571. p[0] = p[m]; \
  7572. p[m] = t; \
  7573. \
  7574. /* partition loop */ \
  7575. i=1; \
  7576. j=n-1; \
  7577. for(;;) { \
  7578. /* handling of equality is crucial here */ \
  7579. /* for sentinels & efficiency with duplicates */ \
  7580. b = &p[0]; \
  7581. for (;;++i) { \
  7582. a=&p[i]; \
  7583. c = COMPARE; \
  7584. if (!c) break; \
  7585. } \
  7586. a = &p[0]; \
  7587. for (;;--j) { \
  7588. b=&p[j]; \
  7589. c = COMPARE; \
  7590. if (!c) break; \
  7591. } \
  7592. /* make sure we haven't crossed */ \
  7593. if (i >= j) break; \
  7594. t = p[i]; \
  7595. p[i] = p[j]; \
  7596. p[j] = t; \
  7597. \
  7598. ++i; \
  7599. --j; \
  7600. } \
  7601. /* recurse on smaller side, iterate on larger */ \
  7602. if (j < (n-i)) { \
  7603. STB_(FUNCNAME,_quicksort)(p,j); \
  7604. p = p+i; \
  7605. n = n-i; \
  7606. } else { \
  7607. STB_(FUNCNAME,_quicksort)(p+i, n-i); \
  7608. n = j; \
  7609. } \
  7610. } \
  7611. } \
  7612. \
  7613. MODE FUNCNAME(TYPE *p, int n) \
  7614. { \
  7615. STB_(FUNCNAME, _quicksort)(p, n); \
  7616. STB_(FUNCNAME, _ins_sort)(p, n); \
  7617. } \
  7618. //////////////////////////////////////////////////////////////////////////////
  7619. //
  7620. // stb_bitset an array of booleans indexed by integers
  7621. //
  7622. typedef stb_uint32 stb_bitset;
  7623. STB_EXTERN stb_bitset *stb_bitset_new(int value, int len);
  7624. #define stb_bitset_clearall(arr,len) (memset(arr, 0, 4 * (len)))
  7625. #define stb_bitset_setall(arr,len) (memset(arr, 255, 4 * (len)))
  7626. #define stb_bitset_setbit(arr,n) ((arr)[(n) >> 5] |= (1 << (n & 31)))
  7627. #define stb_bitset_clearbit(arr,n) ((arr)[(n) >> 5] &= ~(1 << (n & 31)))
  7628. #define stb_bitset_testbit(arr,n) ((arr)[(n) >> 5] & (1 << (n & 31)))
  7629. STB_EXTERN stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len);
  7630. STB_EXTERN int *stb_bitset_getlist(stb_bitset *out, int start, int end);
  7631. STB_EXTERN int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len);
  7632. STB_EXTERN int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len);
  7633. STB_EXTERN int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len);
  7634. STB_EXTERN int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len);
  7635. STB_EXTERN int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len);
  7636. #ifdef STB_DEFINE
  7637. int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len)
  7638. {
  7639. int i;
  7640. for (i=0; i < len; ++i)
  7641. if (p0[i] != p1[i]) return 0;
  7642. return 1;
  7643. }
  7644. int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len)
  7645. {
  7646. int i;
  7647. for (i=0; i < len; ++i)
  7648. if (p0[i] & p1[i]) return 0;
  7649. return 1;
  7650. }
  7651. int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len)
  7652. {
  7653. int i;
  7654. for (i=0; i < len; ++i)
  7655. if ((p0[i] | p1[i]) != 0xffffffff) return 0;
  7656. return 1;
  7657. }
  7658. int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len)
  7659. {
  7660. int i;
  7661. for (i=0; i < len; ++i)
  7662. if ((bigger[i] & smaller[i]) != smaller[i]) return 0;
  7663. return 1;
  7664. }
  7665. stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len)
  7666. {
  7667. int i;
  7668. stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);
  7669. for (i=0; i < len; ++i) d[i] = p0[i] | p1[i];
  7670. return d;
  7671. }
  7672. int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len)
  7673. {
  7674. int i, changed=0;
  7675. for (i=0; i < len; ++i) {
  7676. stb_bitset d = p0[i] | p1[i];
  7677. if (d != p0[i]) {
  7678. p0[i] = d;
  7679. changed = 1;
  7680. }
  7681. }
  7682. return changed;
  7683. }
  7684. stb_bitset *stb_bitset_new(int value, int len)
  7685. {
  7686. int i;
  7687. stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);
  7688. if (value) value = 0xffffffff;
  7689. for (i=0; i < len; ++i) d[i] = value;
  7690. return d;
  7691. }
  7692. int *stb_bitset_getlist(stb_bitset *out, int start, int end)
  7693. {
  7694. int *list = NULL;
  7695. int i;
  7696. for (i=start; i < end; ++i)
  7697. if (stb_bitset_testbit(out, i))
  7698. stb_arr_push(list, i);
  7699. return list;
  7700. }
  7701. #endif
  7702. //////////////////////////////////////////////////////////////////////////////
  7703. //
  7704. // stb_wordwrap quality word-wrapping for fixed-width fonts
  7705. //
  7706. STB_EXTERN int stb_wordwrap(int *pairs, int pair_max, int count, char *str);
  7707. STB_EXTERN int *stb_wordwrapalloc(int count, char *str);
  7708. #ifdef STB_DEFINE
  7709. int stb_wordwrap(int *pairs, int pair_max, int count, char *str)
  7710. {
  7711. int n=0,i=0, start=0,nonwhite=0;
  7712. if (pairs == NULL) pair_max = 0x7ffffff0;
  7713. else pair_max *= 2;
  7714. // parse
  7715. for(;;) {
  7716. int s=i; // first whitespace char; last nonwhite+1
  7717. int w; // word start
  7718. // accept whitespace
  7719. while (isspace(str[i])) {
  7720. if (str[i] == '\n' || str[i] == '\r') {
  7721. if (str[i] + str[i+1] == '\n' + '\r') ++i;
  7722. if (n >= pair_max) return -1;
  7723. if (pairs) pairs[n] = start, pairs[n+1] = s-start;
  7724. n += 2;
  7725. nonwhite=0;
  7726. start = i+1;
  7727. s = start;
  7728. }
  7729. ++i;
  7730. }
  7731. if (i >= start+count) {
  7732. // we've gone off the end using whitespace
  7733. if (nonwhite) {
  7734. if (n >= pair_max) return -1;
  7735. if (pairs) pairs[n] = start, pairs[n+1] = s-start;
  7736. n += 2;
  7737. start = s = i;
  7738. nonwhite=0;
  7739. } else {
  7740. // output all the whitespace
  7741. while (i >= start+count) {
  7742. if (n >= pair_max) return -1;
  7743. if (pairs) pairs[n] = start, pairs[n+1] = count;
  7744. n += 2;
  7745. start += count;
  7746. }
  7747. s = start;
  7748. }
  7749. }
  7750. if (str[i] == 0) break;
  7751. // now scan out a word and see if it fits
  7752. w = i;
  7753. while (str[i] && !isspace(str[i])) {
  7754. ++i;
  7755. }
  7756. // wrapped?
  7757. if (i > start + count) {
  7758. // huge?
  7759. if (i-s <= count) {
  7760. if (n >= pair_max) return -1;
  7761. if (pairs) pairs[n] = start, pairs[n+1] = s-start;
  7762. n += 2;
  7763. start = w;
  7764. } else {
  7765. // This word is longer than one line. If we wrap it onto N lines
  7766. // there are leftover chars. do those chars fit on the cur line?
  7767. // But if we have leading whitespace, we force it to start here.
  7768. if ((w-start) + ((i-w) % count) <= count || !nonwhite) {
  7769. // output a full line
  7770. if (n >= pair_max) return -1;
  7771. if (pairs) pairs[n] = start, pairs[n+1] = count;
  7772. n += 2;
  7773. start += count;
  7774. w = start;
  7775. } else {
  7776. // output a partial line, trimming trailing whitespace
  7777. if (s != start) {
  7778. if (n >= pair_max) return -1;
  7779. if (pairs) pairs[n] = start, pairs[n+1] = s-start;
  7780. n += 2;
  7781. start = w;
  7782. }
  7783. }
  7784. // now output full lines as needed
  7785. while (start + count <= i) {
  7786. if (n >= pair_max) return -1;
  7787. if (pairs) pairs[n] = start, pairs[n+1] = count;
  7788. n += 2;
  7789. start += count;
  7790. }
  7791. }
  7792. }
  7793. nonwhite=1;
  7794. }
  7795. if (start < i) {
  7796. if (n >= pair_max) return -1;
  7797. if (pairs) pairs[n] = start, pairs[n+1] = i-start;
  7798. n += 2;
  7799. }
  7800. return n>>1;
  7801. }
  7802. int *stb_wordwrapalloc(int count, char *str)
  7803. {
  7804. int n = stb_wordwrap(NULL,0,count,str);
  7805. int *z = NULL;
  7806. stb_arr_setlen(z, n*2);
  7807. stb_wordwrap(z, n, count, str);
  7808. return z;
  7809. }
  7810. #endif
  7811. //////////////////////////////////////////////////////////////////////////////
  7812. //
  7813. // stb_match: wildcards and regexping
  7814. //
  7815. STB_EXTERN int stb_wildmatch (char *expr, char *candidate);
  7816. STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);
  7817. STB_EXTERN int stb_wildfind (char *expr, char *candidate);
  7818. STB_EXTERN int stb_wildfindi (char *expr, char *candidate);
  7819. STB_EXTERN int stb_regex(char *regex, char *candidate);
  7820. typedef struct stb_matcher stb_matcher;
  7821. STB_EXTERN stb_matcher *stb_regex_matcher(char *regex);
  7822. STB_EXTERN int stb_matcher_match(stb_matcher *m, char *str);
  7823. STB_EXTERN int stb_matcher_find(stb_matcher *m, char *str);
  7824. STB_EXTERN void stb_matcher_free(stb_matcher *f);
  7825. STB_EXTERN stb_matcher *stb_lex_matcher(void);
  7826. STB_EXTERN int stb_lex_item(stb_matcher *m, char *str, int result);
  7827. STB_EXTERN int stb_lex_item_wild(stb_matcher *matcher, char *regex, int result);
  7828. STB_EXTERN int stb_lex(stb_matcher *m, char *str, int *len);
  7829. #ifdef STB_DEFINE
  7830. static int stb__match_qstring(char *candidate, char *qstring, int qlen, int insensitive)
  7831. {
  7832. int i;
  7833. if (insensitive) {
  7834. for (i=0; i < qlen; ++i)
  7835. if (qstring[i] == '?') {
  7836. if (!candidate[i]) return 0;
  7837. } else
  7838. if (tolower(qstring[i]) != tolower(candidate[i]))
  7839. return 0;
  7840. } else {
  7841. for (i=0; i < qlen; ++i)
  7842. if (qstring[i] == '?') {
  7843. if (!candidate[i]) return 0;
  7844. } else
  7845. if (qstring[i] != candidate[i])
  7846. return 0;
  7847. }
  7848. return 1;
  7849. }
  7850. static int stb__find_qstring(char *candidate, char *qstring, int qlen, int insensitive)
  7851. {
  7852. char c;
  7853. int offset=0;
  7854. while (*qstring == '?') {
  7855. ++qstring;
  7856. --qlen;
  7857. ++candidate;
  7858. if (qlen == 0) return 0;
  7859. if (*candidate == 0) return -1;
  7860. }
  7861. c = *qstring++;
  7862. --qlen;
  7863. if (insensitive) c = tolower(c);
  7864. while (candidate[offset]) {
  7865. if (c == (insensitive ? tolower(candidate[offset]) : candidate[offset]))
  7866. if (stb__match_qstring(candidate+offset+1, qstring, qlen, insensitive))
  7867. return offset;
  7868. ++offset;
  7869. }
  7870. return -1;
  7871. }
  7872. int stb__wildmatch_raw2(char *expr, char *candidate, int search, int insensitive)
  7873. {
  7874. int where=0;
  7875. int start = -1;
  7876. if (!search) {
  7877. // parse to first '*'
  7878. if (*expr != '*')
  7879. start = 0;
  7880. while (*expr != '*') {
  7881. if (!*expr)
  7882. return *candidate == 0 ? 0 : -1;
  7883. if (*expr == '?') {
  7884. if (!*candidate) return -1;
  7885. } else {
  7886. if (insensitive) {
  7887. if (tolower(*candidate) != tolower(*expr))
  7888. return -1;
  7889. } else
  7890. if (*candidate != *expr)
  7891. return -1;
  7892. }
  7893. ++candidate, ++expr, ++where;
  7894. }
  7895. } else {
  7896. // 0-length search string
  7897. if (!*expr)
  7898. return 0;
  7899. }
  7900. assert(search || *expr == '*');
  7901. if (!search)
  7902. ++expr;
  7903. // implicit '*' at this point
  7904. while (*expr) {
  7905. int o=0;
  7906. // combine redundant * characters
  7907. while (expr[0] == '*') ++expr;
  7908. // ok, at this point, expr[-1] == '*',
  7909. // and expr[0] != '*'
  7910. if (!expr[0]) return start >= 0 ? start : 0;
  7911. // now find next '*'
  7912. o = 0;
  7913. while (expr[o] != '*') {
  7914. if (expr[o] == 0)
  7915. break;
  7916. ++o;
  7917. }
  7918. // if no '*', scan to end, then match at end
  7919. if (expr[o] == 0 && !search) {
  7920. int z;
  7921. for (z=0; z < o; ++z)
  7922. if (candidate[z] == 0)
  7923. return -1;
  7924. while (candidate[z])
  7925. ++z;
  7926. // ok, now check if they match
  7927. if (stb__match_qstring(candidate+z-o, expr, o, insensitive))
  7928. return start >= 0 ? start : 0;
  7929. return -1;
  7930. } else {
  7931. // if yes '*', then do stb__find_qmatch on the intervening chars
  7932. int n = stb__find_qstring(candidate, expr, o, insensitive);
  7933. if (n < 0)
  7934. return -1;
  7935. if (start < 0)
  7936. start = where + n;
  7937. expr += o;
  7938. candidate += n+o;
  7939. }
  7940. if (*expr == 0) {
  7941. assert(search);
  7942. return start;
  7943. }
  7944. assert(*expr == '*');
  7945. ++expr;
  7946. }
  7947. return start >= 0 ? start : 0;
  7948. }
  7949. int stb__wildmatch_raw(char *expr, char *candidate, int search, int insensitive)
  7950. {
  7951. char buffer[256];
  7952. // handle multiple search strings
  7953. char *s = strchr(expr, ';');
  7954. char *last = expr;
  7955. while (s) {
  7956. int z;
  7957. // need to allow for non-writeable strings... assume they're small
  7958. if (s - last < 256) {
  7959. stb_strncpy(buffer, last, s-last+1);
  7960. z = stb__wildmatch_raw2(buffer, candidate, search, insensitive);
  7961. } else {
  7962. *s = 0;
  7963. z = stb__wildmatch_raw2(last, candidate, search, insensitive);
  7964. *s = ';';
  7965. }
  7966. if (z >= 0) return z;
  7967. last = s+1;
  7968. s = strchr(last, ';');
  7969. }
  7970. return stb__wildmatch_raw2(last, candidate, search, insensitive);
  7971. }
  7972. int stb_wildmatch(char *expr, char *candidate)
  7973. {
  7974. return stb__wildmatch_raw(expr, candidate, 0,0) >= 0;
  7975. }
  7976. int stb_wildmatchi(char *expr, char *candidate)
  7977. {
  7978. return stb__wildmatch_raw(expr, candidate, 0,1) >= 0;
  7979. }
  7980. int stb_wildfind(char *expr, char *candidate)
  7981. {
  7982. return stb__wildmatch_raw(expr, candidate, 1,0);
  7983. }
  7984. int stb_wildfindi(char *expr, char *candidate)
  7985. {
  7986. return stb__wildmatch_raw(expr, candidate, 1,1);
  7987. }
  7988. typedef struct
  7989. {
  7990. stb_int16 transition[256];
  7991. } stb_dfa;
  7992. // an NFA node represents a state you're in; it then has
  7993. // an arbitrary number of edges dangling off of it
  7994. // note this isn't utf8-y
  7995. typedef struct
  7996. {
  7997. stb_int16 match; // character/set to match
  7998. stb_uint16 node; // output node to go to
  7999. } stb_nfa_edge;
  8000. typedef struct
  8001. {
  8002. stb_int16 goal; // does reaching this win the prize?
  8003. stb_uint8 active; // is this in the active list
  8004. stb_nfa_edge *out;
  8005. stb_uint16 *eps; // list of epsilon closures
  8006. } stb_nfa_node;
  8007. #define STB__DFA_UNDEF -1
  8008. #define STB__DFA_GOAL -2
  8009. #define STB__DFA_END -3
  8010. #define STB__DFA_MGOAL -4
  8011. #define STB__DFA_VALID 0
  8012. #define STB__NFA_STOP_GOAL -1
  8013. // compiled regexp
  8014. struct stb_matcher
  8015. {
  8016. stb_uint16 start_node;
  8017. stb_int16 dfa_start;
  8018. stb_uint32 *charset;
  8019. int num_charset;
  8020. int match_start;
  8021. stb_nfa_node *nodes;
  8022. int does_lex;
  8023. // dfa matcher
  8024. stb_dfa * dfa;
  8025. stb_uint32 * dfa_mapping;
  8026. stb_int16 * dfa_result;
  8027. int num_words_per_dfa;
  8028. };
  8029. static int stb__add_node(stb_matcher *matcher)
  8030. {
  8031. stb_nfa_node z;
  8032. z.active = 0;
  8033. z.eps = 0;
  8034. z.goal = 0;
  8035. z.out = 0;
  8036. stb_arr_push(matcher->nodes, z);
  8037. return stb_arr_len(matcher->nodes)-1;
  8038. }
  8039. static void stb__add_epsilon(stb_matcher *matcher, int from, int to)
  8040. {
  8041. assert(from != to);
  8042. if (matcher->nodes[from].eps == NULL)
  8043. stb_arr_malloc((void **) &matcher->nodes[from].eps, matcher);
  8044. stb_arr_push(matcher->nodes[from].eps, to);
  8045. }
  8046. static void stb__add_edge(stb_matcher *matcher, int from, int to, int type)
  8047. {
  8048. stb_nfa_edge z = { type, to };
  8049. if (matcher->nodes[from].out == NULL)
  8050. stb_arr_malloc((void **) &matcher->nodes[from].out, matcher);
  8051. stb_arr_push(matcher->nodes[from].out, z);
  8052. }
  8053. static char *stb__reg_parse_alt(stb_matcher *m, int s, char *r, stb_uint16 *e);
  8054. static char *stb__reg_parse(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)
  8055. {
  8056. int n;
  8057. int last_start = -1;
  8058. stb_uint16 last_end = start;
  8059. while (*regex) {
  8060. switch (*regex) {
  8061. case '(':
  8062. last_start = last_end;
  8063. regex = stb__reg_parse_alt(matcher, last_end, regex+1, &last_end);
  8064. if (regex == NULL || *regex != ')')
  8065. return NULL;
  8066. ++regex;
  8067. break;
  8068. case '|':
  8069. case ')':
  8070. *end = last_end;
  8071. return regex;
  8072. case '?':
  8073. if (last_start < 0) return NULL;
  8074. stb__add_epsilon(matcher, last_start, last_end);
  8075. ++regex;
  8076. break;
  8077. case '*':
  8078. if (last_start < 0) return NULL;
  8079. stb__add_epsilon(matcher, last_start, last_end);
  8080. // fall through
  8081. case '+':
  8082. if (last_start < 0) return NULL;
  8083. stb__add_epsilon(matcher, last_end, last_start);
  8084. // prevent links back to last_end from chaining to last_start
  8085. n = stb__add_node(matcher);
  8086. stb__add_epsilon(matcher, last_end, n);
  8087. last_end = n;
  8088. ++regex;
  8089. break;
  8090. case '{': // not supported!
  8091. // @TODO: given {n,m}, clone last_start to last_end m times,
  8092. // and include epsilons from start to first m-n blocks
  8093. return NULL;
  8094. case '\\':
  8095. ++regex;
  8096. if (!*regex) return NULL;
  8097. // fallthrough
  8098. default: // match exactly this character
  8099. n = stb__add_node(matcher);
  8100. stb__add_edge(matcher, last_end, n, *regex);
  8101. last_start = last_end;
  8102. last_end = n;
  8103. ++regex;
  8104. break;
  8105. case '$':
  8106. n = stb__add_node(matcher);
  8107. stb__add_edge(matcher, last_end, n, '\n');
  8108. last_start = last_end;
  8109. last_end = n;
  8110. ++regex;
  8111. break;
  8112. case '.':
  8113. n = stb__add_node(matcher);
  8114. stb__add_edge(matcher, last_end, n, -1);
  8115. last_start = last_end;
  8116. last_end = n;
  8117. ++regex;
  8118. break;
  8119. case '[': {
  8120. stb_uint8 flags[256];
  8121. int invert = 0,z;
  8122. ++regex;
  8123. if (matcher->num_charset == 0) {
  8124. matcher->charset = (stb_uint *) stb_malloc(matcher, sizeof(*matcher->charset) * 256);
  8125. memset(matcher->charset, 0, sizeof(*matcher->charset) * 256);
  8126. }
  8127. memset(flags,0,sizeof(flags));
  8128. // leading ^ is special
  8129. if (*regex == '^')
  8130. ++regex, invert = 1;
  8131. // leading ] is special
  8132. if (*regex == ']') {
  8133. flags[']'] = 1;
  8134. ++regex;
  8135. }
  8136. while (*regex != ']') {
  8137. stb_uint a;
  8138. if (!*regex) return NULL;
  8139. a = *regex++;
  8140. if (regex[0] == '-' && regex[1] != ']') {
  8141. stb_uint i,b = regex[1];
  8142. regex += 2;
  8143. if (b == 0) return NULL;
  8144. if (a > b) return NULL;
  8145. for (i=a; i <= b; ++i)
  8146. flags[i] = 1;
  8147. } else
  8148. flags[a] = 1;
  8149. }
  8150. ++regex;
  8151. if (invert) {
  8152. int i;
  8153. for (i=0; i < 256; ++i)
  8154. flags[i] = 1-flags[i];
  8155. }
  8156. // now check if any existing charset matches
  8157. for (z=0; z < matcher->num_charset; ++z) {
  8158. int i, k[2] = { 0, 1 << z};
  8159. for (i=0; i < 256; ++i) {
  8160. unsigned int f = k[flags[i]];
  8161. if ((matcher->charset[i] & k[1]) != f)
  8162. break;
  8163. }
  8164. if (i == 256) break;
  8165. }
  8166. if (z == matcher->num_charset) {
  8167. int i;
  8168. ++matcher->num_charset;
  8169. if (matcher->num_charset > 32) {
  8170. assert(0); /* NOTREACHED */
  8171. return NULL; // too many charsets, oops
  8172. }
  8173. for (i=0; i < 256; ++i)
  8174. if (flags[i])
  8175. matcher->charset[i] |= (1 << z);
  8176. }
  8177. n = stb__add_node(matcher);
  8178. stb__add_edge(matcher, last_end, n, -2 - z);
  8179. last_start = last_end;
  8180. last_end = n;
  8181. break;
  8182. }
  8183. }
  8184. }
  8185. *end = last_end;
  8186. return regex;
  8187. }
  8188. static char *stb__reg_parse_alt(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)
  8189. {
  8190. stb_uint16 last_end = start;
  8191. stb_uint16 main_end;
  8192. int head, tail;
  8193. head = stb__add_node(matcher);
  8194. stb__add_epsilon(matcher, start, head);
  8195. regex = stb__reg_parse(matcher, head, regex, &last_end);
  8196. if (regex == NULL) return NULL;
  8197. if (*regex == 0 || *regex == ')') {
  8198. *end = last_end;
  8199. return regex;
  8200. }
  8201. main_end = last_end;
  8202. tail = stb__add_node(matcher);
  8203. stb__add_epsilon(matcher, last_end, tail);
  8204. // start alternatives from the same starting node; use epsilon
  8205. // transitions to combine their endings
  8206. while(*regex && *regex != ')') {
  8207. assert(*regex == '|');
  8208. head = stb__add_node(matcher);
  8209. stb__add_epsilon(matcher, start, head);
  8210. regex = stb__reg_parse(matcher, head, regex+1, &last_end);
  8211. if (regex == NULL)
  8212. return NULL;
  8213. stb__add_epsilon(matcher, last_end, tail);
  8214. }
  8215. *end = tail;
  8216. return regex;
  8217. }
  8218. static char *stb__wild_parse(stb_matcher *matcher, int start, char *str, stb_uint16 *end)
  8219. {
  8220. int n;
  8221. stb_uint16 last_end;
  8222. last_end = stb__add_node(matcher);
  8223. stb__add_epsilon(matcher, start, last_end);
  8224. while (*str) {
  8225. switch (*str) {
  8226. // fallthrough
  8227. default: // match exactly this character
  8228. n = stb__add_node(matcher);
  8229. if (toupper(*str) == tolower(*str)) {
  8230. stb__add_edge(matcher, last_end, n, *str);
  8231. } else {
  8232. stb__add_edge(matcher, last_end, n, tolower(*str));
  8233. stb__add_edge(matcher, last_end, n, toupper(*str));
  8234. }
  8235. last_end = n;
  8236. ++str;
  8237. break;
  8238. case '?':
  8239. n = stb__add_node(matcher);
  8240. stb__add_edge(matcher, last_end, n, -1);
  8241. last_end = n;
  8242. ++str;
  8243. break;
  8244. case '*':
  8245. n = stb__add_node(matcher);
  8246. stb__add_edge(matcher, last_end, n, -1);
  8247. stb__add_epsilon(matcher, last_end, n);
  8248. stb__add_epsilon(matcher, n, last_end);
  8249. last_end = n;
  8250. ++str;
  8251. break;
  8252. }
  8253. }
  8254. // now require end of string to match
  8255. n = stb__add_node(matcher);
  8256. stb__add_edge(matcher, last_end, n, 0);
  8257. last_end = n;
  8258. *end = last_end;
  8259. return str;
  8260. }
  8261. static int stb__opt(stb_matcher *m, int n)
  8262. {
  8263. for(;;) {
  8264. stb_nfa_node *p = &m->nodes[n];
  8265. if (p->goal) return n;
  8266. if (stb_arr_len(p->out)) return n;
  8267. if (stb_arr_len(p->eps) != 1) return n;
  8268. n = p->eps[0];
  8269. }
  8270. }
  8271. static void stb__optimize(stb_matcher *m)
  8272. {
  8273. // if the target of any edge is a node with exactly
  8274. // one out-epsilon, shorten it
  8275. int i,j;
  8276. for (i=0; i < stb_arr_len(m->nodes); ++i) {
  8277. stb_nfa_node *p = &m->nodes[i];
  8278. for (j=0; j < stb_arr_len(p->out); ++j)
  8279. p->out[j].node = stb__opt(m,p->out[j].node);
  8280. for (j=0; j < stb_arr_len(p->eps); ++j)
  8281. p->eps[j] = stb__opt(m,p->eps[j] );
  8282. }
  8283. m->start_node = stb__opt(m,m->start_node);
  8284. }
  8285. void stb_matcher_free(stb_matcher *f)
  8286. {
  8287. stb_free(f);
  8288. }
  8289. static stb_matcher *stb__alloc_matcher(void)
  8290. {
  8291. stb_matcher *matcher = (stb_matcher *) stb_malloc(0,sizeof(*matcher));
  8292. matcher->start_node = 0;
  8293. stb_arr_malloc((void **) &matcher->nodes, matcher);
  8294. matcher->num_charset = 0;
  8295. matcher->match_start = 0;
  8296. matcher->does_lex = 0;
  8297. matcher->dfa_start = STB__DFA_UNDEF;
  8298. stb_arr_malloc((void **) &matcher->dfa, matcher);
  8299. stb_arr_malloc((void **) &matcher->dfa_mapping, matcher);
  8300. stb_arr_malloc((void **) &matcher->dfa_result, matcher);
  8301. stb__add_node(matcher);
  8302. return matcher;
  8303. }
  8304. static void stb__lex_reset(stb_matcher *matcher)
  8305. {
  8306. // flush cached dfa data
  8307. stb_arr_setlen(matcher->dfa, 0);
  8308. stb_arr_setlen(matcher->dfa_mapping, 0);
  8309. stb_arr_setlen(matcher->dfa_result, 0);
  8310. matcher->dfa_start = STB__DFA_UNDEF;
  8311. }
  8312. stb_matcher *stb_regex_matcher(char *regex)
  8313. {
  8314. char *z;
  8315. stb_uint16 end;
  8316. stb_matcher *matcher = stb__alloc_matcher();
  8317. if (*regex == '^') {
  8318. matcher->match_start = 1;
  8319. ++regex;
  8320. }
  8321. z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end);
  8322. if (!z || *z) {
  8323. stb_free(matcher);
  8324. return NULL;
  8325. }
  8326. ((matcher->nodes)[(int) end]).goal = STB__NFA_STOP_GOAL;
  8327. return matcher;
  8328. }
  8329. stb_matcher *stb_lex_matcher(void)
  8330. {
  8331. stb_matcher *matcher = stb__alloc_matcher();
  8332. matcher->match_start = 1;
  8333. matcher->does_lex = 1;
  8334. return matcher;
  8335. }
  8336. int stb_lex_item(stb_matcher *matcher, char *regex, int result)
  8337. {
  8338. char *z;
  8339. stb_uint16 end;
  8340. z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end);
  8341. if (z == NULL)
  8342. return 0;
  8343. stb__lex_reset(matcher);
  8344. matcher->nodes[(int) end].goal = result;
  8345. return 1;
  8346. }
  8347. int stb_lex_item_wild(stb_matcher *matcher, char *regex, int result)
  8348. {
  8349. char *z;
  8350. stb_uint16 end;
  8351. z = stb__wild_parse(matcher, matcher->start_node, regex, &end);
  8352. if (z == NULL)
  8353. return 0;
  8354. stb__lex_reset(matcher);
  8355. matcher->nodes[(int) end].goal = result;
  8356. return 1;
  8357. }
  8358. static void stb__clear(stb_matcher *m, stb_uint16 *list)
  8359. {
  8360. int i;
  8361. for (i=0; i < stb_arr_len(list); ++i)
  8362. m->nodes[(int) list[i]].active = 0;
  8363. }
  8364. static int stb__clear_goalcheck(stb_matcher *m, stb_uint16 *list)
  8365. {
  8366. int i, t=0;
  8367. for (i=0; i < stb_arr_len(list); ++i) {
  8368. t += m->nodes[(int) list[i]].goal;
  8369. m->nodes[(int) list[i]].active = 0;
  8370. }
  8371. return t;
  8372. }
  8373. static stb_uint16 * stb__add_if_inactive(stb_matcher *m, stb_uint16 *list, int n)
  8374. {
  8375. if (!m->nodes[n].active) {
  8376. stb_arr_push(list, n);
  8377. m->nodes[n].active = 1;
  8378. }
  8379. return list;
  8380. }
  8381. static stb_uint16 * stb__eps_closure(stb_matcher *m, stb_uint16 *list)
  8382. {
  8383. int i,n = stb_arr_len(list);
  8384. for(i=0; i < n; ++i) {
  8385. stb_uint16 *e = m->nodes[(int) list[i]].eps;
  8386. if (e) {
  8387. int j,k = stb_arr_len(e);
  8388. for (j=0; j < k; ++j)
  8389. list = stb__add_if_inactive(m, list, e[j]);
  8390. n = stb_arr_len(list);
  8391. }
  8392. }
  8393. return list;
  8394. }
  8395. int stb_matcher_match(stb_matcher *m, char *str)
  8396. {
  8397. int result = 0;
  8398. int i,j,y,z;
  8399. stb_uint16 *previous = NULL;
  8400. stb_uint16 *current = NULL;
  8401. stb_uint16 *temp;
  8402. stb_arr_setsize(previous, 4);
  8403. stb_arr_setsize(current, 4);
  8404. previous = stb__add_if_inactive(m, previous, m->start_node);
  8405. previous = stb__eps_closure(m,previous);
  8406. stb__clear(m, previous);
  8407. while (*str && stb_arr_len(previous)) {
  8408. y = stb_arr_len(previous);
  8409. for (i=0; i < y; ++i) {
  8410. stb_nfa_node *n = &m->nodes[(int) previous[i]];
  8411. z = stb_arr_len(n->out);
  8412. for (j=0; j < z; ++j) {
  8413. if (n->out[j].match >= 0) {
  8414. if (n->out[j].match == *str)
  8415. current = stb__add_if_inactive(m, current, n->out[j].node);
  8416. } else if (n->out[j].match == -1) {
  8417. if (*str != '\n')
  8418. current = stb__add_if_inactive(m, current, n->out[j].node);
  8419. } else if (n->out[j].match < -1) {
  8420. int z = -n->out[j].match - 2;
  8421. if (m->charset[(stb_uint8) *str] & (1 << z))
  8422. current = stb__add_if_inactive(m, current, n->out[j].node);
  8423. }
  8424. }
  8425. }
  8426. stb_arr_setlen(previous, 0);
  8427. temp = previous;
  8428. previous = current;
  8429. current = temp;
  8430. previous = stb__eps_closure(m,previous);
  8431. stb__clear(m, previous);
  8432. ++str;
  8433. }
  8434. // transition to pick up a '$' at the end
  8435. y = stb_arr_len(previous);
  8436. for (i=0; i < y; ++i)
  8437. m->nodes[(int) previous[i]].active = 1;
  8438. for (i=0; i < y; ++i) {
  8439. stb_nfa_node *n = &m->nodes[(int) previous[i]];
  8440. z = stb_arr_len(n->out);
  8441. for (j=0; j < z; ++j) {
  8442. if (n->out[j].match == '\n')
  8443. current = stb__add_if_inactive(m, current, n->out[j].node);
  8444. }
  8445. }
  8446. previous = stb__eps_closure(m,previous);
  8447. stb__clear(m, previous);
  8448. y = stb_arr_len(previous);
  8449. for (i=0; i < y; ++i)
  8450. if (m->nodes[(int) previous[i]].goal)
  8451. result = 1;
  8452. stb_arr_free(previous);
  8453. stb_arr_free(current);
  8454. return result && *str == 0;
  8455. }
  8456. stb_int16 stb__get_dfa_node(stb_matcher *m, stb_uint16 *list)
  8457. {
  8458. stb_uint16 node;
  8459. stb_uint32 data[8], *state, *newstate;
  8460. int i,j,n;
  8461. state = (stb_uint32 *) stb_temp(data, m->num_words_per_dfa * 4);
  8462. memset(state, 0, m->num_words_per_dfa*4);
  8463. n = stb_arr_len(list);
  8464. for (i=0; i < n; ++i) {
  8465. int x = list[i];
  8466. state[x >> 5] |= 1 << (x & 31);
  8467. }
  8468. // @TODO use a hash table
  8469. n = stb_arr_len(m->dfa_mapping);
  8470. i=j=0;
  8471. for(; j < n; ++i, j += m->num_words_per_dfa) {
  8472. // @TODO special case for <= 32
  8473. if (!memcmp(state, m->dfa_mapping + j, m->num_words_per_dfa*4)) {
  8474. node = i;
  8475. goto done;
  8476. }
  8477. }
  8478. assert(stb_arr_len(m->dfa) == i);
  8479. node = i;
  8480. newstate = stb_arr_addn(m->dfa_mapping, m->num_words_per_dfa);
  8481. memcpy(newstate, state, m->num_words_per_dfa*4);
  8482. // set all transitions to 'unknown'
  8483. stb_arr_add(m->dfa);
  8484. memset(m->dfa[i].transition, -1, sizeof(m->dfa[i].transition));
  8485. if (m->does_lex) {
  8486. int result = -1;
  8487. n = stb_arr_len(list);
  8488. for (i=0; i < n; ++i) {
  8489. if (m->nodes[(int) list[i]].goal > result)
  8490. result = m->nodes[(int) list[i]].goal;
  8491. }
  8492. stb_arr_push(m->dfa_result, result);
  8493. }
  8494. done:
  8495. stb_tempfree(data, state);
  8496. return node;
  8497. }
  8498. static int stb__matcher_dfa(stb_matcher *m, char *str_c, int *len)
  8499. {
  8500. stb_uint8 *str = (stb_uint8 *) str_c;
  8501. stb_int16 node,prevnode;
  8502. stb_dfa *trans;
  8503. int match_length = 0;
  8504. stb_int16 match_result=0;
  8505. if (m->dfa_start == STB__DFA_UNDEF) {
  8506. stb_uint16 *list;
  8507. m->num_words_per_dfa = (stb_arr_len(m->nodes)+31) >> 5;
  8508. stb__optimize(m);
  8509. list = stb__add_if_inactive(m, NULL, m->start_node);
  8510. list = stb__eps_closure(m,list);
  8511. if (m->does_lex) {
  8512. m->dfa_start = stb__get_dfa_node(m,list);
  8513. stb__clear(m, list);
  8514. // DON'T allow start state to be a goal state!
  8515. // this allows people to specify regexes that can match 0
  8516. // characters without them actually matching (also we don't
  8517. // check _before_ advancing anyway
  8518. if (m->dfa_start <= STB__DFA_MGOAL)
  8519. m->dfa_start = -(m->dfa_start - STB__DFA_MGOAL);
  8520. } else {
  8521. if (stb__clear_goalcheck(m, list))
  8522. m->dfa_start = STB__DFA_GOAL;
  8523. else
  8524. m->dfa_start = stb__get_dfa_node(m,list);
  8525. }
  8526. stb_arr_free(list);
  8527. }
  8528. prevnode = STB__DFA_UNDEF;
  8529. node = m->dfa_start;
  8530. trans = m->dfa;
  8531. if (m->dfa_start == STB__DFA_GOAL)
  8532. return 1;
  8533. for(;;) {
  8534. assert(node >= STB__DFA_VALID);
  8535. // fast inner DFA loop; especially if STB__DFA_VALID is 0
  8536. do {
  8537. prevnode = node;
  8538. node = trans[node].transition[*str++];
  8539. } while (node >= STB__DFA_VALID);
  8540. assert(node >= STB__DFA_MGOAL - stb_arr_len(m->dfa));
  8541. assert(node < stb_arr_len(m->dfa));
  8542. // special case for lex: need _longest_ match, so notice goal
  8543. // state without stopping
  8544. if (node <= STB__DFA_MGOAL) {
  8545. match_length = str - (stb_uint8 *) str_c;
  8546. node = -(node - STB__DFA_MGOAL);
  8547. match_result = node;
  8548. continue;
  8549. }
  8550. // slow NFA->DFA conversion
  8551. // or we hit the goal or the end of the string, but those
  8552. // can only happen once per search...
  8553. if (node == STB__DFA_UNDEF) {
  8554. // build a list -- @TODO special case <= 32 states
  8555. // heck, use a more compact data structure for <= 16 and <= 8 ?!
  8556. // @TODO keep states/newstates around instead of reallocating them
  8557. stb_uint16 *states = NULL;
  8558. stb_uint16 *newstates = NULL;
  8559. int i,j,y,z;
  8560. stb_uint32 *flags = &m->dfa_mapping[prevnode * m->num_words_per_dfa];
  8561. assert(prevnode != STB__DFA_UNDEF);
  8562. stb_arr_setsize(states, 4);
  8563. stb_arr_setsize(newstates,4);
  8564. for (j=0; j < m->num_words_per_dfa; ++j) {
  8565. for (i=0; i < 32; ++i) {
  8566. if (*flags & (1 << i))
  8567. stb_arr_push(states, j*32+i);
  8568. }
  8569. ++flags;
  8570. }
  8571. // states is now the states we were in in the previous node;
  8572. // so now we can compute what node it transitions to on str[-1]
  8573. y = stb_arr_len(states);
  8574. for (i=0; i < y; ++i) {
  8575. stb_nfa_node *n = &m->nodes[(int) states[i]];
  8576. z = stb_arr_len(n->out);
  8577. for (j=0; j < z; ++j) {
  8578. if (n->out[j].match >= 0) {
  8579. if (n->out[j].match == str[-1] || (str[-1] == 0 && n->out[j].match == '\n'))
  8580. newstates = stb__add_if_inactive(m, newstates, n->out[j].node);
  8581. } else if (n->out[j].match == -1) {
  8582. if (str[-1] != '\n' && str[-1])
  8583. newstates = stb__add_if_inactive(m, newstates, n->out[j].node);
  8584. } else if (n->out[j].match < -1) {
  8585. int z = -n->out[j].match - 2;
  8586. if (m->charset[str[-1]] & (1 << z))
  8587. newstates = stb__add_if_inactive(m, newstates, n->out[j].node);
  8588. }
  8589. }
  8590. }
  8591. // AND add in the start state!
  8592. if (!m->match_start || (str[-1] == '\n' && !m->does_lex))
  8593. newstates = stb__add_if_inactive(m, newstates, m->start_node);
  8594. // AND epsilon close it
  8595. newstates = stb__eps_closure(m, newstates);
  8596. // if it's a goal state, then that's all there is to it
  8597. if (stb__clear_goalcheck(m, newstates)) {
  8598. if (m->does_lex) {
  8599. match_length = str - (stb_uint8 *) str_c;
  8600. node = stb__get_dfa_node(m,newstates);
  8601. match_result = node;
  8602. node = -node + STB__DFA_MGOAL;
  8603. trans = m->dfa; // could have gotten realloc()ed
  8604. } else
  8605. node = STB__DFA_GOAL;
  8606. } else if (str[-1] == 0 || stb_arr_len(newstates) == 0) {
  8607. node = STB__DFA_END;
  8608. } else {
  8609. node = stb__get_dfa_node(m,newstates);
  8610. trans = m->dfa; // could have gotten realloc()ed
  8611. }
  8612. trans[prevnode].transition[str[-1]] = node;
  8613. if (node <= STB__DFA_MGOAL)
  8614. node = -(node - STB__DFA_MGOAL);
  8615. stb_arr_free(newstates);
  8616. stb_arr_free(states);
  8617. }
  8618. if (node == STB__DFA_GOAL) {
  8619. return 1;
  8620. }
  8621. if (node == STB__DFA_END) {
  8622. if (m->does_lex) {
  8623. if (match_result) {
  8624. if (len) *len = match_length;
  8625. return m->dfa_result[(int) match_result];
  8626. }
  8627. }
  8628. return 0;
  8629. }
  8630. assert(node != STB__DFA_UNDEF);
  8631. }
  8632. }
  8633. int stb_matcher_find(stb_matcher *m, char *str)
  8634. {
  8635. assert(m->does_lex == 0);
  8636. return stb__matcher_dfa(m, str, NULL);
  8637. }
  8638. int stb_lex(stb_matcher *m, char *str, int *len)
  8639. {
  8640. assert(m->does_lex);
  8641. return stb__matcher_dfa(m, str, len);
  8642. }
  8643. int stb_regex(char *regex, char *str)
  8644. {
  8645. static stb_perfect p;
  8646. static stb_matcher ** matchers;
  8647. static char ** regexps;
  8648. static char ** regexp_cache;
  8649. static unsigned short *mapping;
  8650. int z = stb_perfect_hash(&p, (int) regex);
  8651. if (z >= 0) {
  8652. if (strcmp(regex, regexp_cache[(int) mapping[z]])) {
  8653. int i = mapping[z];
  8654. stb_matcher_free(matchers[i]);
  8655. free(regexp_cache[i]);
  8656. regexps[i] = regex;
  8657. regexp_cache[i] = strdup(regex);
  8658. matchers[i] = stb_regex_matcher(regex);
  8659. }
  8660. } else {
  8661. int i,n;
  8662. if (regex == NULL) {
  8663. for (i=0; i < stb_arr_len(matchers); ++i) {
  8664. stb_matcher_free(matchers[i]);
  8665. free(regexp_cache[i]);
  8666. }
  8667. stb_arr_free(matchers);
  8668. stb_arr_free(regexps);
  8669. stb_arr_free(regexp_cache);
  8670. stb_perfect_destroy(&p);
  8671. free(mapping); mapping = NULL;
  8672. return -1;
  8673. }
  8674. stb_arr_push(regexps, regex);
  8675. stb_arr_push(regexp_cache, strdup(regex));
  8676. stb_arr_push(matchers, stb_regex_matcher(regex));
  8677. stb_perfect_destroy(&p);
  8678. n = stb_perfect_create(&p, (unsigned int *) (char **) regexps, stb_arr_len(regexps));
  8679. mapping = (unsigned short *) realloc(mapping, n * sizeof(*mapping));
  8680. for (i=0; i < stb_arr_len(regexps); ++i)
  8681. mapping[stb_perfect_hash(&p, (int) regexps[i])] = i;
  8682. z = stb_perfect_hash(&p, (int) regex);
  8683. }
  8684. return stb_matcher_find(matchers[(int) mapping[z]], str);
  8685. }
  8686. #endif // STB_DEFINE
  8687. #if 0
  8688. //////////////////////////////////////////////////////////////////////////////
  8689. //
  8690. // C source-code introspection
  8691. //
  8692. // runtime structure
  8693. typedef struct
  8694. {
  8695. char *name;
  8696. char *type; // base type
  8697. char *comment; // content of comment field
  8698. int size; // size of base type
  8699. int offset; // field offset
  8700. int arrcount[8]; // array sizes; -1 = pointer indirection; 0 = end of list
  8701. } stb_info_field;
  8702. typedef struct
  8703. {
  8704. char *structname;
  8705. int size;
  8706. int num_fields;
  8707. stb_info_field *fields;
  8708. } stb_info_struct;
  8709. extern stb_info_struct stb_introspect_output[];
  8710. //
  8711. STB_EXTERN void stb_introspect_precompiled(stb_info_struct *compiled);
  8712. STB_EXTERN void stb__introspect(char *path, char *file);
  8713. #define stb_introspect_ship() stb__introspect(NULL, NULL, stb__introspect_output)
  8714. #ifdef STB_SHIP
  8715. #define stb_introspect() stb_introspect_ship()
  8716. #define stb_introspect_path(p) stb_introspect_ship()
  8717. #else
  8718. // bootstrapping: define stb_introspect() (or 'path') the first time
  8719. #define stb_introspect() stb__introspect(NULL, __FILE__, NULL)
  8720. #define stb_introspect_auto() stb__introspect(NULL, __FILE__, stb__introspect_output)
  8721. #define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL)
  8722. #define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL)
  8723. #endif
  8724. #ifdef STB_DEFINE
  8725. #ifndef STB_INTROSPECT_CPP
  8726. #ifdef __cplusplus
  8727. #define STB_INTROSPECT_CPP 1
  8728. #else
  8729. #define STB_INTROSPECT_CPP 0
  8730. #endif
  8731. #endif
  8732. void stb_introspect_precompiled(stb_info_struct *compiled)
  8733. {
  8734. }
  8735. static void stb__introspect_filename(char *buffer, char *path)
  8736. {
  8737. #if STB_INTROSPECT_CPP
  8738. sprintf(buffer, "%s/stb_introspect.cpp", path);
  8739. #else
  8740. sprintf(buffer, "%s/stb_introspect.c", path);
  8741. #endif
  8742. }
  8743. static void stb__introspect_compute(char *path, char *file)
  8744. {
  8745. int i;
  8746. char ** include_list = NULL;
  8747. char ** introspect_list = NULL;
  8748. FILE *f;
  8749. f = fopen(file, "w");
  8750. if (!f) return;
  8751. fputs("// if you get compiler errors, change the following 0 to a 1:\n", f);
  8752. fputs("#define STB_INTROSPECT_INVALID 0\n\n", f);
  8753. fputs("// this will force the code to compile, and force the introspector\n", f);
  8754. fputs("// to run and then exit, allowing you to recompile\n\n\n", f);
  8755. fputs("#include \"stb.h\"\n\n",f );
  8756. fputs("#if STB_INTROSPECT_INVALID\n", f);
  8757. fputs(" stb_info_struct stb__introspect_output[] = { (void *) 1 }\n", f);
  8758. fputs("#else\n\n", f);
  8759. for (i=0; i < stb_arr_len(include_list); ++i)
  8760. fprintf(f, " #include \"%s\"\n", include_list[i]);
  8761. fputs(" stb_info_struct stb__introspect_output[] =\n{\n", f);
  8762. for (i=0; i < stb_arr_len(introspect_list); ++i)
  8763. fprintf(f, " stb_introspect_%s,\n", introspect_list[i]);
  8764. fputs(" };\n", f);
  8765. fputs("#endif\n", f);
  8766. fclose(f);
  8767. }
  8768. static stb_info_struct *stb__introspect_info;
  8769. #ifndef STB_SHIP
  8770. #endif
  8771. void stb__introspect(char *path, char *file, stb_info_struct *compiled)
  8772. {
  8773. static int first=1;
  8774. if (!first) return;
  8775. first=0;
  8776. stb__introspect_info = compiled;
  8777. #ifndef STB_SHIP
  8778. if (path || file) {
  8779. int bail_flag = compiled && compiled[0].structname == (void *) 1;
  8780. int needs_building = bail_flag;
  8781. struct stb__stat st;
  8782. char buffer[1024], buffer2[1024];
  8783. if (!path) {
  8784. stb_splitpath(buffer, file, STB_PATH);
  8785. path = buffer;
  8786. }
  8787. // bail if the source path doesn't exist
  8788. if (!stb_fexists(path)) return;
  8789. stb__introspect_filename(buffer2, path);
  8790. // get source/include files timestamps, compare to output-file timestamp;
  8791. // if mismatched, regenerate
  8792. if (stb__stat(buffer2, &st))
  8793. needs_building = STB_TRUE;
  8794. {
  8795. // find any file that contains an introspection command and is newer
  8796. // if needs_building is already true, we don't need to do this test,
  8797. // but we still need these arrays, so go ahead and get them
  8798. char **all[3];
  8799. all[0] = stb_readdir_files_mask(path, "*.h");
  8800. all[1] = stb_readdir_files_mask(path, "*.c");
  8801. all[2] = stb_readdir_files_mask(path, "*.cpp");
  8802. int i,j;
  8803. if (needs_building) {
  8804. for (j=0; j < 3; ++j) {
  8805. for (i=0; i < stb_arr_len(all[j]); ++i) {
  8806. struct stb__stat st2;
  8807. if (!stb__stat(all[j][i], &st2)) {
  8808. if (st.st_mtime < st2.st_mtime) {
  8809. char *z = stb_filec(all[j][i], NULL);
  8810. int found=STB_FALSE;
  8811. while (y) {
  8812. y = strstr(y, "//si");
  8813. if (y && isspace(y[4])) {
  8814. found = STB_TRUE;
  8815. break;
  8816. }
  8817. }
  8818. needs_building = STB_TRUE;
  8819. goto done;
  8820. }
  8821. }
  8822. }
  8823. }
  8824. done:;
  8825. }
  8826. char *z = stb_filec(all[i], NULL), *y = z;
  8827. int found=STB_FALSE;
  8828. while (y) {
  8829. y = strstr(y, "//si");
  8830. if (y && isspace(y[4])) {
  8831. found = STB_TRUE;
  8832. break;
  8833. }
  8834. }
  8835. if (found)
  8836. stb_arr_push(introspect_h, strdup(all[i]));
  8837. free(z);
  8838. }
  8839. }
  8840. stb_readdir_free(all);
  8841. if (!needs_building) {
  8842. for (i=0; i < stb_arr_len(introspect_h); ++i) {
  8843. struct stb__stat st2;
  8844. if (!stb__stat(introspect_h[i], &st2))
  8845. if (st.st_mtime < st2.st_mtime)
  8846. needs_building = STB_TRUE;
  8847. }
  8848. }
  8849. if (needs_building) {
  8850. stb__introspect_compute(path, buffer2);
  8851. }
  8852. }
  8853. }
  8854. #endif
  8855. }
  8856. #endif
  8857. #endif
  8858. #ifdef STB_INTROSPECT
  8859. // compile-time code-generator
  8860. #define INTROSPECT(x) int main(int argc, char **argv) { stb__introspect(__FILE__); return 0; }
  8861. #define FILE(x)
  8862. void stb__introspect(char *filename)
  8863. {
  8864. char *file = stb_file(filename, NULL);
  8865. char *s = file, *t, **p;
  8866. char *out_name = "stb_introspect.c";
  8867. char *out_path;
  8868. STB_ARR(char) filelist = NULL;
  8869. int i,n;
  8870. if (!file) stb_fatal("Couldn't open %s", filename);
  8871. out_path = stb_splitpathdup(filename, STB_PATH);
  8872. // search for the macros
  8873. while (*s) {
  8874. char buffer[256];
  8875. while (*s && !isupper(*s)) ++s;
  8876. s = stb_strtok_invert(buffer, s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  8877. s = stb_skipwhite(s);
  8878. if (*s == '(') {
  8879. ++s;
  8880. t = strchr(s, ')');
  8881. if (t == NULL) stb_fatal("Error parsing %s", filename);
  8882. }
  8883. }
  8884. }
  8885. #endif
  8886. //////////////////////////////////////////////////////////////////////////////
  8887. //
  8888. // STB-C sliding-window dictionary compression
  8889. //
  8890. // This uses a DEFLATE-style sliding window, but no bitwise entropy.
  8891. // Everything is on byte boundaries, so you could then apply a byte-wise
  8892. // entropy code, though that's nowhere near as effective.
  8893. //
  8894. // An STB-C stream begins with a 16-byte header:
  8895. // 4 bytes: 0x57 0xBC 0x00 0x00
  8896. // 8 bytes: big-endian size of decompressed data, 64-bits
  8897. // 4 bytes: big-endian size of window (how far back decompressor may need)
  8898. //
  8899. // The following symbols appear in the stream (these were determined ad hoc,
  8900. // not by analysis):
  8901. //
  8902. // [dict] 00000100 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx
  8903. // [END] 00000101 11111010 cccccccc cccccccc cccccccc cccccccc
  8904. // [dict] 00000110 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx
  8905. // [literals] 00000111 zzzzzzzz zzzzzzzz
  8906. // [literals] 00001zzz zzzzzzzz
  8907. // [dict] 00010yyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx
  8908. // [dict] 00011yyy yyyyyyyy yyyyyyyy xxxxxxxx
  8909. // [literals] 001zzzzz
  8910. // [dict] 01yyyyyy yyyyyyyy xxxxxxxx
  8911. // [dict] 1xxxxxxx yyyyyyyy
  8912. //
  8913. // xxxxxxxx: match length - 1
  8914. // yyyyyyyy: backwards distance - 1
  8915. // zzzzzzzz: num literals - 1
  8916. // cccccccc: adler32 checksum of decompressed data
  8917. // (all big-endian)
  8918. STB_EXTERN stb_uint stb_decompress_length(stb_uchar *input);
  8919. STB_EXTERN stb_uint stb_decompress(stb_uchar *out,stb_uchar *in,stb_uint len);
  8920. STB_EXTERN stb_uint stb_compress (stb_uchar *out,stb_uchar *in,stb_uint len);
  8921. STB_EXTERN void stb_compress_window(int z);
  8922. STB_EXTERN void stb_compress_hashsize(unsigned int z);
  8923. STB_EXTERN int stb_compress_tofile(char *filename, char *in, stb_uint len);
  8924. STB_EXTERN int stb_compress_intofile(FILE *f, char *input, stb_uint len);
  8925. STB_EXTERN char *stb_decompress_fromfile(char *filename, stb_uint *len);
  8926. STB_EXTERN int stb_compress_stream_start(FILE *f);
  8927. STB_EXTERN void stb_compress_stream_end(int close);
  8928. STB_EXTERN void stb_write(char *data, int data_len);
  8929. #ifdef STB_DEFINE
  8930. stb_uint stb_decompress_length(stb_uchar *input)
  8931. {
  8932. return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];
  8933. }
  8934. //////////////////// decompressor ///////////////////////
  8935. // simple implementation that just writes whole thing into big block
  8936. static unsigned char *stb__barrier;
  8937. static unsigned char *stb__barrier2;
  8938. static unsigned char *stb__barrier3;
  8939. static unsigned char *stb__barrier4;
  8940. static stb_uchar *stb__dout;
  8941. static void stb__match(stb_uchar *data, stb_uint length)
  8942. {
  8943. // INVERSE of memmove... write each byte before copying the next...
  8944. assert (stb__dout + length <= stb__barrier);
  8945. if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
  8946. if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; }
  8947. while (length--) *stb__dout++ = *data++;
  8948. }
  8949. static void stb__lit(stb_uchar *data, stb_uint length)
  8950. {
  8951. assert (stb__dout + length <= stb__barrier);
  8952. if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
  8953. if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }
  8954. memcpy(stb__dout, data, length);
  8955. stb__dout += length;
  8956. }
  8957. #define stb__in2(x) ((i[x] << 8) + i[(x)+1])
  8958. #define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1))
  8959. #define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1))
  8960. static stb_uchar *stb_decompress_token(stb_uchar *i)
  8961. {
  8962. if (*i >= 0x20) { // use fewer if's for cases that expand small
  8963. if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;
  8964. else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;
  8965. else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);
  8966. } else { // more ifs for cases that expand large, since overhead is amortized
  8967. if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;
  8968. else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;
  8969. else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1);
  8970. else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1);
  8971. else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;
  8972. else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;
  8973. }
  8974. return i;
  8975. }
  8976. stb_uint stb_decompress(stb_uchar *output, stb_uchar *i, stb_uint length)
  8977. {
  8978. stb_uint olen;
  8979. if (stb__in4(0) != 0x57bC0000) return 0;
  8980. if (stb__in4(4) != 0) return 0; // error! stream is > 4GB
  8981. olen = stb_decompress_length(i);
  8982. stb__barrier2 = i;
  8983. stb__barrier3 = i+length;
  8984. stb__barrier = output + olen;
  8985. stb__barrier4 = output;
  8986. i += 16;
  8987. stb__dout = output;
  8988. while (1) {
  8989. stb_uchar *old_i = i;
  8990. i = stb_decompress_token(i);
  8991. if (i == old_i) {
  8992. if (*i == 0x05 && i[1] == 0xfa) {
  8993. assert(stb__dout == output + olen);
  8994. if (stb__dout != output + olen) return 0;
  8995. if (stb_adler32(1, output, olen) != (stb_uint) stb__in4(2))
  8996. return 0;
  8997. return olen;
  8998. } else {
  8999. assert(0); /* NOTREACHED */
  9000. return 0;
  9001. }
  9002. }
  9003. assert(stb__dout <= output + olen);
  9004. if (stb__dout > output + olen)
  9005. return 0;
  9006. }
  9007. }
  9008. char *stb_decompress_fromfile(char *filename, unsigned int *len)
  9009. {
  9010. unsigned int n;
  9011. char *q;
  9012. unsigned char *p;
  9013. FILE *f = fopen(filename, "rb"); if (f == NULL) return NULL;
  9014. fseek(f, 0, SEEK_END);
  9015. n = ftell(f);
  9016. fseek(f, 0, SEEK_SET);
  9017. p = (unsigned char * ) malloc(n); if (p == NULL) return NULL;
  9018. fread(p, 1, n, f);
  9019. fclose(f);
  9020. if (p == NULL) return NULL;
  9021. if (p[0] != 0x57 || p[1] != 0xBc || p[2] || p[3]) { free(p); return NULL; }
  9022. q = (char *) malloc(stb_decompress_length(p)+1);
  9023. if (!q) { free(p); return NULL; }
  9024. *len = stb_decompress((unsigned char *) q, p, n);
  9025. if (*len) q[*len] = 0;
  9026. free(p);
  9027. return q;
  9028. }
  9029. #if 0
  9030. // streaming decompressor
  9031. static struct
  9032. {
  9033. stb__uchar *in_buffer;
  9034. stb__uchar *match;
  9035. stb__uint pending_literals;
  9036. stb__uint pending_match;
  9037. } xx;
  9038. static void stb__match(stb_uchar *data, stb_uint length)
  9039. {
  9040. // INVERSE of memmove... write each byte before copying the next...
  9041. assert (stb__dout + length <= stb__barrier);
  9042. if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
  9043. if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }
  9044. while (length--) *stb__dout++ = *data++;
  9045. }
  9046. static void stb__lit(stb_uchar *data, stb_uint length)
  9047. {
  9048. assert (stb__dout + length <= stb__barrier);
  9049. if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
  9050. if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }
  9051. memcpy(stb__dout, data, length);
  9052. stb__dout += length;
  9053. }
  9054. static void sx_match(stb_uchar *data, stb_uint length)
  9055. {
  9056. xx.match = data;
  9057. xx.pending_match = length;
  9058. }
  9059. static void sx_lit(stb_uchar *data, stb_uint length)
  9060. {
  9061. xx.pending_lit = length;
  9062. }
  9063. static int stb_decompress_token_state(void)
  9064. {
  9065. stb__uchar *i = xx.in_buffer;
  9066. if (*i >= 0x20) { // use fewer if's for cases that expand small
  9067. if (*i >= 0x80) sx_match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;
  9068. else if (*i >= 0x40) sx_match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;
  9069. else /* *i >= 0x20 */ sx_lit(i+1, i[0] - 0x20 + 1), i += 1;
  9070. } else { // more ifs for cases that expand large, since overhead is amortized
  9071. if (*i >= 0x18) sx_match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;
  9072. else if (*i >= 0x10) sx_match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;
  9073. else if (*i >= 0x08) sx_lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2;
  9074. else if (*i == 0x07) sx_lit(i+3, stb__in2(1) + 1), i += 3;
  9075. else if (*i == 0x06) sx_match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;
  9076. else if (*i == 0x04) sx_match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;
  9077. else return 0;
  9078. }
  9079. xx.in_buffer = i;
  9080. return 1;
  9081. }
  9082. #endif
  9083. //////////////////// compressor ///////////////////////
  9084. static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen)
  9085. {
  9086. stb_uint i;
  9087. for (i=0; i < maxlen; ++i)
  9088. if (m1[i] != m2[i]) return i;
  9089. return i;
  9090. }
  9091. // simple implementation that just takes the source data in a big block
  9092. static stb_uchar *stb__out;
  9093. static FILE *stb__outfile;
  9094. static stb_uint stb__outbytes;
  9095. static void stb__write(unsigned char v)
  9096. {
  9097. fputc(v, stb__outfile);
  9098. ++stb__outbytes;
  9099. }
  9100. #define stb_out(v) (stb__out ? *stb__out++ = (stb_uchar) (v) : stb__write((stb_uchar) (v)))
  9101. static void stb_out2(stb_uint v)
  9102. {
  9103. stb_out(v >> 8);
  9104. stb_out(v);
  9105. }
  9106. static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); }
  9107. static void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16);
  9108. stb_out(v >> 8 ); stb_out(v); }
  9109. static void outliterals(stb_uchar *in, int numlit)
  9110. {
  9111. while (numlit > 65536) {
  9112. outliterals(in,65536);
  9113. in += 65536;
  9114. numlit -= 65536;
  9115. }
  9116. if (numlit == 0) ;
  9117. else if (numlit <= 32) stb_out (0x000020 + numlit-1);
  9118. else if (numlit <= 2048) stb_out2(0x000800 + numlit-1);
  9119. else /* numlit <= 65536) */ stb_out3(0x070000 + numlit-1);
  9120. if (stb__out) {
  9121. memcpy(stb__out,in,numlit);
  9122. stb__out += numlit;
  9123. } else
  9124. fwrite(in, 1, numlit, stb__outfile);
  9125. }
  9126. static int stb__window = 0x40000; // 256K
  9127. void stb_compress_window(int z)
  9128. {
  9129. if (z >= 0x1000000) z = 0x1000000; // limit of implementation
  9130. if (z < 0x100) z = 0x100; // insanely small
  9131. stb__window = z;
  9132. }
  9133. static int stb_not_crap(int best, int dist)
  9134. {
  9135. return ((best > 2 && dist <= 0x00100)
  9136. || (best > 5 && dist <= 0x04000)
  9137. || (best > 7 && dist <= 0x80000));
  9138. }
  9139. static stb_uint stb__hashsize = 32768;
  9140. void stb_compress_hashsize(unsigned int y)
  9141. {
  9142. unsigned int z = 1024;
  9143. while (z < y) z <<= 1;
  9144. stb__hashsize = z >> 2; // pass in bytes, store #pointers
  9145. }
  9146. // note that you can play with the hashing functions all you
  9147. // want without needing to change the decompressor
  9148. #define stb__hc(q,h,c) (((h) << 7) + ((h) >> 25) + q[c])
  9149. #define stb__hc2(q,h,c,d) (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d])
  9150. #define stb__hc3(q,c,d,e) ((q[c] << 14) + (q[d] << 7) + q[e])
  9151. static stb_uint32 stb__running_adler;
  9152. static int stb_compress_chunk(stb_uchar *history,
  9153. stb_uchar *start,
  9154. stb_uchar *end,
  9155. int length,
  9156. int *pending_literals,
  9157. stb_uchar **chash,
  9158. stb_uint mask)
  9159. {
  9160. int window = stb__window;
  9161. stb_uint match_max;
  9162. stb_uchar *lit_start = start - *pending_literals;
  9163. stb_uchar *q = start;
  9164. #define STB__SCRAMBLE(h) (((h) + ((h) >> 16)) & mask)
  9165. // stop short of the end so we don't scan off the end doing
  9166. // the hashing; this means we won't compress the last few bytes
  9167. // unless they were part of something longer
  9168. while (q < start+length && q+12 < end) {
  9169. int m;
  9170. stb_uint h1,h2,h3,h4, h;
  9171. stb_uchar *t;
  9172. int best = 2, dist=0;
  9173. if (q+65536 > end)
  9174. match_max = end-q;
  9175. else
  9176. match_max = 65536;
  9177. #define stb__nc(b,d) ((d) <= window && ((b) > 9 || stb_not_crap(b,d)))
  9178. #define STB__TRY(t,p) /* avoid retrying a match we already tried */ \
  9179. if (p ? dist != q-t : 1) \
  9180. if ((m = stb_matchlen(t, q, match_max)) > best) \
  9181. if (stb__nc(m,q-(t))) \
  9182. best = m, dist = q - (t)
  9183. // rather than search for all matches, only try 4 candidate locations,
  9184. // chosen based on 4 different hash functions of different lengths.
  9185. // this strategy is inspired by LZO; hashing is unrolled here using the
  9186. // 'hc' macro
  9187. h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h);
  9188. t = chash[h1]; if (t) STB__TRY(t,0);
  9189. h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h);
  9190. h = stb__hc2(q,h, 5, 6); t = chash[h2]; if (t) STB__TRY(t,1);
  9191. h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h);
  9192. h = stb__hc2(q,h, 9,10); t = chash[h3]; if (t) STB__TRY(t,1);
  9193. h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h);
  9194. t = chash[h4]; if (t) STB__TRY(t,1);
  9195. // because we use a shared hash table, can only update it
  9196. // _after_ we've probed all of them
  9197. chash[h1] = chash[h2] = chash[h3] = chash[h4] = q;
  9198. if (best > 2)
  9199. assert(dist > 0);
  9200. // see if our best match qualifies
  9201. if (best < 3) { // fast path literals
  9202. ++q;
  9203. } else if (best > 2 && best <= 0x80 && dist <= 0x100) {
  9204. outliterals(lit_start, q-lit_start); lit_start = (q += best);
  9205. stb_out(0x80 + best-1);
  9206. stb_out(dist-1);
  9207. } else if (best > 5 && best <= 0x100 && dist <= 0x4000) {
  9208. outliterals(lit_start, q-lit_start); lit_start = (q += best);
  9209. stb_out2(0x4000 + dist-1);
  9210. stb_out(best-1);
  9211. } else if (best > 7 && best <= 0x100 && dist <= 0x80000) {
  9212. outliterals(lit_start, q-lit_start); lit_start = (q += best);
  9213. stb_out3(0x180000 + dist-1);
  9214. stb_out(best-1);
  9215. } else if (best > 8 && best <= 0x10000 && dist <= 0x80000) {
  9216. outliterals(lit_start, q-lit_start); lit_start = (q += best);
  9217. stb_out3(0x100000 + dist-1);
  9218. stb_out2(best-1);
  9219. } else if (best > 9 && dist <= 0x1000000) {
  9220. if (best > 65536) best = 65536;
  9221. outliterals(lit_start, q-lit_start); lit_start = (q += best);
  9222. if (best <= 0x100) {
  9223. stb_out(0x06);
  9224. stb_out3(dist-1);
  9225. stb_out(best-1);
  9226. } else {
  9227. stb_out(0x04);
  9228. stb_out3(dist-1);
  9229. stb_out2(best-1);
  9230. }
  9231. } else { // fallback literals if no match was a balanced tradeoff
  9232. ++q;
  9233. }
  9234. }
  9235. // if we didn't get all the way, add the rest to literals
  9236. if (q-start < length)
  9237. q = start+length;
  9238. // the literals are everything from lit_start to q
  9239. *pending_literals = (q - lit_start);
  9240. stb__running_adler = stb_adler32(stb__running_adler, start, q - start);
  9241. return q - start;
  9242. }
  9243. static int stb_compress_inner(stb_uchar *input, stb_uint length)
  9244. {
  9245. int literals = 0;
  9246. stb_uint len,i;
  9247. stb_uchar **chash;
  9248. chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*));
  9249. if (chash == NULL) return 0; // failure
  9250. for (i=0; i < stb__hashsize; ++i)
  9251. chash[i] = NULL;
  9252. // stream signature
  9253. stb_out(0x57); stb_out(0xbc);
  9254. stb_out2(0);
  9255. stb_out4(0); // 64-bit length requires 32-bit leading 0
  9256. stb_out4(length);
  9257. stb_out4(stb__window);
  9258. stb__running_adler = 1;
  9259. len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1);
  9260. assert(len == length);
  9261. outliterals(input+length - literals, literals);
  9262. free(chash);
  9263. stb_out2(0x05fa); // end opcode
  9264. stb_out4(stb__running_adler);
  9265. return 1; // success
  9266. }
  9267. stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length)
  9268. {
  9269. stb__out = out;
  9270. stb__outfile = NULL;
  9271. stb_compress_inner(input, length);
  9272. return stb__out - out;
  9273. }
  9274. int stb_compress_tofile(char *filename, char *input, unsigned int length)
  9275. {
  9276. //int maxlen = length + 512 + (length >> 2); // total guess
  9277. //char *buffer = (char *) malloc(maxlen);
  9278. //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);
  9279. stb__out = NULL;
  9280. stb__outfile = fopen(filename, "wb");
  9281. if (!stb__outfile) return 0;
  9282. stb__outbytes = 0;
  9283. if (!stb_compress_inner((stb_uchar*)input, length))
  9284. return 0;
  9285. fclose(stb__outfile);
  9286. return stb__outbytes;
  9287. }
  9288. int stb_compress_intofile(FILE *f, char *input, unsigned int length)
  9289. {
  9290. //int maxlen = length + 512 + (length >> 2); // total guess
  9291. //char *buffer = (char*)malloc(maxlen);
  9292. //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);
  9293. stb__out = NULL;
  9294. stb__outfile = f;
  9295. if (!stb__outfile) return 0;
  9296. stb__outbytes = 0;
  9297. if (!stb_compress_inner((stb_uchar*)input, length))
  9298. return 0;
  9299. return stb__outbytes;
  9300. }
  9301. ////////////////////// streaming I/O version /////////////////////
  9302. static size_t stb_out_backpatch_id(void)
  9303. {
  9304. if (stb__out)
  9305. return (size_t) stb__out;
  9306. else
  9307. return ftell(stb__outfile);
  9308. }
  9309. static void stb_out_backpatch(size_t id, stb_uint value)
  9310. {
  9311. stb_uchar data[4] = { value >> 24, value >> 16, value >> 8, value };
  9312. if (stb__out) {
  9313. memcpy((void *) id, data, 4);
  9314. } else {
  9315. stb_uint where = ftell(stb__outfile);
  9316. fseek(stb__outfile, id, SEEK_SET);
  9317. fwrite(data, 4, 1, stb__outfile);
  9318. fseek(stb__outfile, where, SEEK_SET);
  9319. }
  9320. }
  9321. // ok, the wraparound buffer was a total failure. let's instead
  9322. // use a copying-in-place buffer, which lets us share the code.
  9323. // This is way less efficient but it'll do for now.
  9324. static struct
  9325. {
  9326. stb_uchar *buffer;
  9327. int size; // physical size of buffer in bytes
  9328. int valid; // amount of valid data in bytes
  9329. int start; // bytes of data already output
  9330. int window;
  9331. int fsize;
  9332. int pending_literals; // bytes not-quite output but counted in start
  9333. int length_id;
  9334. stb_uint total_bytes;
  9335. stb_uchar **chash;
  9336. stb_uint hashmask;
  9337. } xtb;
  9338. static int stb_compress_streaming_start(void)
  9339. {
  9340. stb_uint i;
  9341. xtb.size = stb__window * 3;
  9342. xtb.buffer = (stb_uchar*)malloc(xtb.size);
  9343. if (!xtb.buffer) return 0;
  9344. xtb.chash = (stb_uchar**)malloc(sizeof(*xtb.chash) * stb__hashsize);
  9345. if (!xtb.chash) {
  9346. free(xtb.buffer);
  9347. return 0;
  9348. }
  9349. for (i=0; i < stb__hashsize; ++i)
  9350. xtb.chash[i] = NULL;
  9351. xtb.hashmask = stb__hashsize-1;
  9352. xtb.valid = 0;
  9353. xtb.start = 0;
  9354. xtb.window = stb__window;
  9355. xtb.fsize = stb__window;
  9356. xtb.pending_literals = 0;
  9357. xtb.total_bytes = 0;
  9358. // stream signature
  9359. stb_out(0x57); stb_out(0xbc); stb_out2(0);
  9360. stb_out4(0); // 64-bit length requires 32-bit leading 0
  9361. xtb.length_id = stb_out_backpatch_id();
  9362. stb_out4(0); // we don't know the output length yet
  9363. stb_out4(stb__window);
  9364. stb__running_adler = 1;
  9365. return 1;
  9366. }
  9367. static int stb_compress_streaming_end(void)
  9368. {
  9369. // flush out any remaining data
  9370. stb_compress_chunk(xtb.buffer, xtb.buffer+xtb.start, xtb.buffer+xtb.valid,
  9371. xtb.valid-xtb.start, &xtb.pending_literals, xtb.chash, xtb.hashmask);
  9372. // write out pending literals
  9373. outliterals(xtb.buffer + xtb.valid - xtb.pending_literals, xtb.pending_literals);
  9374. stb_out2(0x05fa); // end opcode
  9375. stb_out4(stb__running_adler);
  9376. stb_out_backpatch(xtb.length_id, xtb.total_bytes);
  9377. free(xtb.buffer);
  9378. free(xtb.chash);
  9379. return 1;
  9380. }
  9381. void stb_write(char *data, int data_len)
  9382. {
  9383. stb_uint i;
  9384. // @TODO: fast path for filling the buffer and doing nothing else
  9385. // if (xtb.valid + data_len < xtb.size)
  9386. xtb.total_bytes += data_len;
  9387. while (data_len) {
  9388. // fill buffer
  9389. if (xtb.valid < xtb.size) {
  9390. int amt = xtb.size - xtb.valid;
  9391. if (data_len < amt) amt = data_len;
  9392. memcpy(xtb.buffer + xtb.valid, data, amt);
  9393. data_len -= amt;
  9394. data += amt;
  9395. xtb.valid += amt;
  9396. }
  9397. if (xtb.valid < xtb.size)
  9398. return;
  9399. // at this point, the buffer is full
  9400. // if we can process some data, go for it; make sure
  9401. // we leave an 'fsize's worth of data, though
  9402. if (xtb.start + xtb.fsize < xtb.valid) {
  9403. int amount = (xtb.valid - xtb.fsize) - xtb.start;
  9404. int n;
  9405. assert(amount > 0);
  9406. n = stb_compress_chunk(xtb.buffer, xtb.buffer + xtb.start, xtb.buffer + xtb.valid,
  9407. amount, &xtb.pending_literals, xtb.chash, xtb.hashmask);
  9408. xtb.start += n;
  9409. }
  9410. assert(xtb.start + xtb.fsize >= xtb.valid);
  9411. // at this point, our future size is too small, so we
  9412. // need to flush some history. we, in fact, flush exactly
  9413. // one window's worth of history
  9414. {
  9415. int flush = xtb.window;
  9416. assert(xtb.start >= flush);
  9417. assert(xtb.valid >= flush);
  9418. // if 'pending literals' extends back into the shift region,
  9419. // write them out
  9420. if (xtb.start - xtb.pending_literals < flush) {
  9421. outliterals(xtb.buffer + xtb.start - xtb.pending_literals, xtb.pending_literals);
  9422. xtb.pending_literals = 0;
  9423. }
  9424. // now shift the window
  9425. memmove(xtb.buffer, xtb.buffer + flush, xtb.valid - flush);
  9426. xtb.start -= flush;
  9427. xtb.valid -= flush;
  9428. for (i=0; i <= xtb.hashmask; ++i)
  9429. if (xtb.chash[i] < xtb.buffer + flush)
  9430. xtb.chash[i] = NULL;
  9431. else
  9432. xtb.chash[i] -= flush;
  9433. }
  9434. // and now that we've made room for more data, go back to the top
  9435. }
  9436. }
  9437. int stb_compress_stream_start(FILE *f)
  9438. {
  9439. stb__out = NULL;
  9440. stb__outfile = f;
  9441. if (f == NULL)
  9442. return 0;
  9443. if (!stb_compress_streaming_start())
  9444. return 0;
  9445. return 1;
  9446. }
  9447. void stb_compress_stream_end(int close)
  9448. {
  9449. stb_compress_streaming_end();
  9450. if (close && stb__outfile) {
  9451. fclose(stb__outfile);
  9452. }
  9453. }
  9454. #endif // STB_DEFINE
  9455. //////////////////////////////////////////////////////////////////////////////
  9456. //
  9457. // File abstraction... tired of not having this... we can write
  9458. // compressors to be layers over these that auto-close their children.
  9459. typedef struct stbfile
  9460. {
  9461. int (*getbyte)(struct stbfile *); // -1 on EOF
  9462. unsigned int (*getdata)(struct stbfile *, void *block, unsigned int len);
  9463. int (*putbyte)(struct stbfile *, int byte);
  9464. unsigned int (*putdata)(struct stbfile *, void *block, unsigned int len);
  9465. unsigned int (*size)(struct stbfile *);
  9466. unsigned int (*tell)(struct stbfile *);
  9467. void (*backpatch)(struct stbfile *, unsigned int tell, void *block, unsigned int len);
  9468. void (*close)(struct stbfile *);
  9469. FILE *f; // file to fread/fwrite
  9470. unsigned char *buffer; // input/output buffer
  9471. unsigned char *indata, *inend; // input buffer
  9472. union {
  9473. int various;
  9474. void *ptr;
  9475. };
  9476. } stbfile;
  9477. STB_EXTERN unsigned int stb_getc(stbfile *f); // read
  9478. STB_EXTERN int stb_putc(stbfile *f, int ch); // write
  9479. STB_EXTERN unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len); // read
  9480. STB_EXTERN unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len); // write
  9481. STB_EXTERN unsigned int stb_tell(stbfile *f); // read
  9482. STB_EXTERN unsigned int stb_size(stbfile *f); // read/write
  9483. STB_EXTERN void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len); // write
  9484. #ifdef STB_DEFINE
  9485. unsigned int stb_getc(stbfile *f) { return f->getbyte(f); }
  9486. int stb_putc(stbfile *f, int ch) { return f->putbyte(f, ch); }
  9487. unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len)
  9488. {
  9489. return f->getdata(f, buffer, len);
  9490. }
  9491. unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len)
  9492. {
  9493. return f->putdata(f, buffer, len);
  9494. }
  9495. void stb_close(stbfile *f)
  9496. {
  9497. f->close(f);
  9498. free(f);
  9499. }
  9500. unsigned int stb_tell(stbfile *f) { return f->tell(f); }
  9501. unsigned int stb_size(stbfile *f) { return f->size(f); }
  9502. void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len)
  9503. {
  9504. f->backpatch(f,tell,buffer,len);
  9505. }
  9506. // FILE * implementation
  9507. static int stb__fgetbyte(stbfile *f) { return fgetc(f->f); }
  9508. static int stb__fputbyte(stbfile *f, int ch) { return fputc(ch, f->f)==0; }
  9509. static unsigned int stb__fgetdata(stbfile *f, void *buffer, unsigned int len) { return fread(buffer,1,len,f->f); }
  9510. static unsigned int stb__fputdata(stbfile *f, void *buffer, unsigned int len) { return fwrite(buffer,1,len,f->f); }
  9511. static unsigned int stb__fsize(stbfile *f) { return stb_filelen(f->f); }
  9512. static unsigned int stb__ftell(stbfile *f) { return ftell(f->f); }
  9513. static void stb__fbackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len)
  9514. {
  9515. fseek(f->f, where, SEEK_SET);
  9516. fwrite(buffer, 1, len, f->f);
  9517. fseek(f->f, 0, SEEK_END);
  9518. }
  9519. static void stb__fclose(stbfile *f) { fclose(f->f); }
  9520. stbfile *stb_openf(FILE *f)
  9521. {
  9522. stbfile m = { stb__fgetbyte, stb__fgetdata,
  9523. stb__fputbyte, stb__fputdata,
  9524. stb__fsize, stb__ftell, stb__fbackpatch, stb__fclose,
  9525. 0,0,0, };
  9526. stbfile *z = (stbfile *) malloc(sizeof(*z));
  9527. if (z) {
  9528. *z = m;
  9529. z->f = f;
  9530. }
  9531. return z;
  9532. }
  9533. static int stb__nogetbyte(stbfile *f) { assert(0); return -1; }
  9534. static unsigned int stb__nogetdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }
  9535. static int stb__noputbyte(stbfile *f, int ch) { assert(0); return 0; }
  9536. static unsigned int stb__noputdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }
  9537. static void stb__nobackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len) { assert(0); }
  9538. static int stb__bgetbyte(stbfile *s)
  9539. {
  9540. if (s->indata < s->inend)
  9541. return *s->indata++;
  9542. else
  9543. return -1;
  9544. }
  9545. static unsigned int stb__bgetdata(stbfile *s, void *buffer, unsigned int len)
  9546. {
  9547. if (s->indata + len > s->inend)
  9548. len = s->inend - s->indata;
  9549. memcpy(buffer, s->indata, len);
  9550. s->indata += len;
  9551. return len;
  9552. }
  9553. static unsigned int stb__bsize(stbfile *s) { return s->inend - s->buffer; }
  9554. static unsigned int stb__btell(stbfile *s) { return s->indata - s->buffer; }
  9555. static void stb__bclose(stbfile *s)
  9556. {
  9557. if (s->various)
  9558. free(s->buffer);
  9559. }
  9560. stbfile *stb_open_inbuffer(void *buffer, unsigned int len)
  9561. {
  9562. stbfile m = { stb__bgetbyte, stb__bgetdata,
  9563. stb__noputbyte, stb__noputdata,
  9564. stb__bsize, stb__btell, stb__nobackpatch, stb__bclose };
  9565. stbfile *z = (stbfile *) malloc(sizeof(*z));
  9566. if (z) {
  9567. *z = m;
  9568. z->buffer = (unsigned char *) buffer;
  9569. z->indata = z->buffer;
  9570. z->inend = z->indata + len;
  9571. }
  9572. return z;
  9573. }
  9574. stbfile *stb_open_inbuffer_free(void *buffer, unsigned int len)
  9575. {
  9576. stbfile *z = stb_open_inbuffer(buffer, len);
  9577. if (z)
  9578. z->various = 1; // free
  9579. return z;
  9580. }
  9581. #ifndef STB_VERSION
  9582. // if we've been cut-and-pasted elsewhere, you get a limited
  9583. // version of stb_open, without the 'k' flag and utf8 support
  9584. static void stb__fclose2(stbfile *f)
  9585. {
  9586. fclose(f->f);
  9587. }
  9588. stbfile *stb_open(char *filename, char *mode)
  9589. {
  9590. FILE *f = fopen(filename, mode);
  9591. stbfile *s;
  9592. if (f == NULL) return NULL;
  9593. s = stb_openf(f);
  9594. if (s)
  9595. s->close = stb__fclose2;
  9596. return s;
  9597. }
  9598. #else
  9599. // the full version depends on some code in stb.h; this
  9600. // also includes the memory buffer output format implemented with stb_arr
  9601. static void stb__fclose2(stbfile *f)
  9602. {
  9603. stb_fclose(f->f, f->various);
  9604. }
  9605. stbfile *stb_open(char *filename, char *mode)
  9606. {
  9607. FILE *f = stb_fopen(filename, mode[0] == 'k' ? mode+1 : mode);
  9608. stbfile *s;
  9609. if (f == NULL) return NULL;
  9610. s = stb_openf(f);
  9611. if (s) {
  9612. s->close = stb__fclose2;
  9613. s->various = mode[0] == 'k' ? stb_keep_if_different : stb_keep_yes;
  9614. }
  9615. return s;
  9616. }
  9617. static int stb__aputbyte(stbfile *f, int ch)
  9618. {
  9619. stb_arr_push(f->buffer, ch);
  9620. return 1;
  9621. }
  9622. static unsigned int stb__aputdata(stbfile *f, void *data, unsigned int len)
  9623. {
  9624. memcpy(stb_arr_addn(f->buffer, (int) len), data, len);
  9625. return len;
  9626. }
  9627. static unsigned int stb__asize(stbfile *f) { return stb_arr_len(f->buffer); }
  9628. static void stb__abackpatch(stbfile *f, unsigned int where, void *data, unsigned int len)
  9629. {
  9630. memcpy(f->buffer+where, data, len);
  9631. }
  9632. static void stb__aclose(stbfile *f)
  9633. {
  9634. *(unsigned char **) f->ptr = f->buffer;
  9635. }
  9636. stbfile *stb_open_outbuffer(unsigned char **update_on_close)
  9637. {
  9638. stbfile m = { stb__nogetbyte, stb__nogetdata,
  9639. stb__aputbyte, stb__aputdata,
  9640. stb__asize, stb__asize, stb__abackpatch, stb__aclose };
  9641. stbfile *z = (stbfile *) malloc(sizeof(*z));
  9642. if (z) {
  9643. z->ptr = update_on_close;
  9644. *z = m;
  9645. }
  9646. return z;
  9647. }
  9648. #endif
  9649. #endif
  9650. //////////////////////////////////////////////////////////////////////////////
  9651. //
  9652. // Arithmetic coder... based on cbloom's notes on the subject, should be
  9653. // less code than a huffman code.
  9654. typedef struct
  9655. {
  9656. unsigned int range_low;
  9657. unsigned int range_high;
  9658. unsigned int code, range; // decode
  9659. int buffered_u8;
  9660. int pending_ffs;
  9661. stbfile *output;
  9662. } stb_arith;
  9663. STB_EXTERN void stb_arith_init_encode(stb_arith *a, stbfile *out);
  9664. STB_EXTERN void stb_arith_init_decode(stb_arith *a, stbfile *in);
  9665. STB_EXTERN stbfile *stb_arith_encode_close(stb_arith *a);
  9666. STB_EXTERN stbfile *stb_arith_decode_close(stb_arith *a);
  9667. STB_EXTERN void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);
  9668. STB_EXTERN void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);
  9669. STB_EXTERN unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq);
  9670. STB_EXTERN void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);
  9671. STB_EXTERN unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2);
  9672. STB_EXTERN void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);
  9673. STB_EXTERN void stb_arith_encode_byte(stb_arith *a, int byte);
  9674. STB_EXTERN int stb_arith_decode_byte(stb_arith *a);
  9675. // this is a memory-inefficient way of doing things, but it's
  9676. // fast(?) and simple
  9677. typedef struct
  9678. {
  9679. unsigned short cumfreq;
  9680. unsigned short samples;
  9681. } stb_arith_symstate_item;
  9682. typedef struct
  9683. {
  9684. int num_sym;
  9685. unsigned int pow2;
  9686. int countdown;
  9687. stb_arith_symstate_item data[1];
  9688. } stb_arith_symstate;
  9689. #ifdef STB_DEFINE
  9690. void stb_arith_init_encode(stb_arith *a, stbfile *out)
  9691. {
  9692. a->range_low = 0;
  9693. a->range_high = 0xffffffff;
  9694. a->pending_ffs = -1; // means no buffered character currently, to speed up normal case
  9695. a->output = out;
  9696. }
  9697. static void stb__arith_carry(stb_arith *a)
  9698. {
  9699. int i;
  9700. assert(a->pending_ffs != -1); // can't carry with no data
  9701. stb_putc(a->output, a->buffered_u8);
  9702. for (i=0; i < a->pending_ffs; ++i)
  9703. stb_putc(a->output, 0);
  9704. }
  9705. static void stb__arith_putbyte(stb_arith *a, int byte)
  9706. {
  9707. if (a->pending_ffs) {
  9708. if (a->pending_ffs == -1) { // means no buffered data; encoded for fast path efficiency
  9709. if (byte == 0xff)
  9710. stb_putc(a->output, byte); // just write it immediately
  9711. else {
  9712. a->buffered_u8 = byte;
  9713. a->pending_ffs = 0;
  9714. }
  9715. } else if (byte == 0xff) {
  9716. ++a->pending_ffs;
  9717. } else {
  9718. int i;
  9719. stb_putc(a->output, a->buffered_u8);
  9720. for (i=0; i < a->pending_ffs; ++i)
  9721. stb_putc(a->output, 0xff);
  9722. }
  9723. } else if (byte == 0xff) {
  9724. ++a->pending_ffs;
  9725. } else {
  9726. // fast path
  9727. stb_putc(a->output, a->buffered_u8);
  9728. a->buffered_u8 = byte;
  9729. }
  9730. }
  9731. static void stb__arith_flush(stb_arith *a)
  9732. {
  9733. if (a->pending_ffs >= 0) {
  9734. int i;
  9735. stb_putc(a->output, a->buffered_u8);
  9736. for (i=0; i < a->pending_ffs; ++i)
  9737. stb_putc(a->output, 0xff);
  9738. }
  9739. }
  9740. static void stb__renorm_encoder(stb_arith *a)
  9741. {
  9742. stb__arith_putbyte(a, a->range_low >> 24);
  9743. a->range_low <<= 8;
  9744. a->range_high = (a->range_high << 8) | 0xff;
  9745. }
  9746. static void stb__renorm_decoder(stb_arith *a)
  9747. {
  9748. int c = stb_getc(a->output);
  9749. a->code = (a->code << 8) + (c >= 0 ? c : 0); // if EOF, insert 0
  9750. }
  9751. void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)
  9752. {
  9753. unsigned int range = a->range_high - a->range_low;
  9754. unsigned int old = a->range_low;
  9755. range /= totalfreq;
  9756. a->range_low += range * cumfreq;
  9757. a->range_high = a->range_low + range*freq;
  9758. if (a->range_low < old)
  9759. stb__arith_carry(a);
  9760. while (a->range_high - a->range_low < 0x1000000)
  9761. stb__renorm_encoder(a);
  9762. }
  9763. void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)
  9764. {
  9765. unsigned int range = a->range_high - a->range_low;
  9766. unsigned int old = a->range_low;
  9767. range >>= totalfreq2;
  9768. a->range_low += range * cumfreq;
  9769. a->range_high = a->range_low + range*freq;
  9770. if (a->range_low < old)
  9771. stb__arith_carry(a);
  9772. while (a->range_high - a->range_low < 0x1000000)
  9773. stb__renorm_encoder(a);
  9774. }
  9775. unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq)
  9776. {
  9777. unsigned int freqsize = a->range / totalfreq;
  9778. unsigned int z = a->code / freqsize;
  9779. return z >= totalfreq ? totalfreq-1 : z;
  9780. }
  9781. void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)
  9782. {
  9783. unsigned int freqsize = a->range / totalfreq; // @OPTIMIZE, share with above divide somehow?
  9784. a->code -= freqsize * cumfreq;
  9785. a->range = freqsize * freq;
  9786. while (a->range < 0x1000000)
  9787. stb__renorm_decoder(a);
  9788. }
  9789. unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2)
  9790. {
  9791. unsigned int freqsize = a->range >> totalfreq2;
  9792. unsigned int z = a->code / freqsize;
  9793. return z >= (1U<<totalfreq2) ? (1U<<totalfreq2)-1 : z;
  9794. }
  9795. void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)
  9796. {
  9797. unsigned int freqsize = a->range >> totalfreq2;
  9798. a->code -= freqsize * cumfreq;
  9799. a->range = freqsize * freq;
  9800. while (a->range < 0x1000000)
  9801. stb__renorm_decoder(a);
  9802. }
  9803. stbfile *stb_arith_encode_close(stb_arith *a)
  9804. {
  9805. // put exactly as many bytes as we'll read, so we can turn on/off arithmetic coding in a stream
  9806. stb__arith_putbyte(a, a->range_low >> 24);
  9807. stb__arith_putbyte(a, a->range_low >> 16);
  9808. stb__arith_putbyte(a, a->range_low >> 8);
  9809. stb__arith_putbyte(a, a->range_low >> 0);
  9810. stb__arith_flush(a);
  9811. return a->output;
  9812. }
  9813. stbfile *stb_arith_decode_close(stb_arith *a)
  9814. {
  9815. return a->output;
  9816. }
  9817. // this is a simple power-of-two based model -- using
  9818. // power of two means we need one divide per decode,
  9819. // not two.
  9820. #define POW2_LIMIT 12
  9821. stb_arith_symstate *stb_arith_state_create(int num_sym)
  9822. {
  9823. stb_arith_symstate *s = (stb_arith_symstate *) malloc(sizeof(*s) + (num_sym-1) * sizeof(s->data[0]));
  9824. if (s) {
  9825. int i, cf, cf_next, next;
  9826. int start_freq, extra;
  9827. s->num_sym = num_sym;
  9828. s->pow2 = 4;
  9829. while (s->pow2 < 15 && (1 << s->pow2) < 3*num_sym) {
  9830. ++s->pow2;
  9831. }
  9832. start_freq = (1 << s->pow2) / num_sym;
  9833. assert(start_freq >= 1);
  9834. extra = (1 << s->pow2) % num_sym;
  9835. // now set up the initial stats
  9836. if (s->pow2 < POW2_LIMIT)
  9837. next = 0;
  9838. else
  9839. next = 1;
  9840. cf = cf_next = 0;
  9841. for (i=0; i < extra; ++i) {
  9842. s->data[i].cumfreq = cf;
  9843. s->data[i].samples = next;
  9844. cf += start_freq+1;
  9845. cf_next += next;
  9846. }
  9847. for (; i < num_sym; ++i) {
  9848. s->data[i].cumfreq = cf;
  9849. s->data[i].samples = next;
  9850. cf += start_freq;
  9851. cf_next += next;
  9852. }
  9853. assert(cf == (1 << s->pow2));
  9854. // now, how long should we go until we have 2 << s->pow2 samples?
  9855. s->countdown = (2 << s->pow2) - cf - cf_next;
  9856. }
  9857. return s;
  9858. }
  9859. static void stb_arith_state_rescale(stb_arith_symstate *s)
  9860. {
  9861. if (s->pow2 < POW2_LIMIT) {
  9862. int pcf, cf, cf_next, next, i;
  9863. ++s->pow2;
  9864. if (s->pow2 < POW2_LIMIT)
  9865. next = 0;
  9866. else
  9867. next = 1;
  9868. cf = cf_next = 0;
  9869. pcf = 0;
  9870. for (i=0; i < s->num_sym; ++i) {
  9871. int sample = s->data[i].cumfreq - pcf + s->data[i].samples;
  9872. s->data[i].cumfreq = cf;
  9873. cf += sample;
  9874. s->data[i].samples = next;
  9875. cf_next += next;
  9876. }
  9877. assert(cf == (1 << s->pow2));
  9878. s->countdown = (2 << s->pow2) - cf - cf_next;
  9879. } else {
  9880. int pcf, cf, cf_next, i;
  9881. cf = cf_next = 0;
  9882. pcf = 0;
  9883. for (i=0; i < s->num_sym; ++i) {
  9884. int sample = (s->data[i].cumfreq - pcf + s->data[i].samples) >> 1;
  9885. s->data[i].cumfreq = cf;
  9886. cf += sample;
  9887. s->data[i].samples = 1;
  9888. cf_next += 1;
  9889. }
  9890. assert(cf == (1 << s->pow2)); // this isn't necessarily true, due to rounding down!
  9891. s->countdown = (2 << s->pow2) - cf - cf_next;
  9892. }
  9893. }
  9894. void stb_arith_encode_byte(stb_arith *a, int byte)
  9895. {
  9896. }
  9897. int stb_arith_decode_byte(stb_arith *a)
  9898. {
  9899. return -1;
  9900. }
  9901. #endif
  9902. //////////////////////////////////////////////////////////////////////////////
  9903. //
  9904. // Threads
  9905. //
  9906. #ifndef _WIN32
  9907. #ifdef STB_THREADS
  9908. #error "threads not implemented except for Windows"
  9909. #endif
  9910. #endif
  9911. // call this function to free any global variables for memory testing
  9912. STB_EXTERN void stb_thread_cleanup(void);
  9913. typedef void * (*stb_thread_func)(void *);
  9914. // do not rely on these types, this is an implementation detail.
  9915. // compare against STB_THREAD_NULL and ST_SEMAPHORE_NULL
  9916. typedef void *stb_thread;
  9917. typedef void *stb_semaphore;
  9918. typedef void *stb_mutex;
  9919. typedef struct stb__sync *stb_sync;
  9920. #define STB_SEMAPHORE_NULL NULL
  9921. #define STB_THREAD_NULL NULL
  9922. #define STB_MUTEX_NULL NULL
  9923. #define STB_SYNC_NULL NULL
  9924. // get the number of processors (limited to those in the affinity mask for this process).
  9925. STB_EXTERN int stb_processor_count(void);
  9926. // force to run on a single core -- needed for RDTSC to work, e.g. for iprof
  9927. STB_EXTERN void stb_force_uniprocessor(void);
  9928. // stb_work functions: queue up work to be done by some worker threads
  9929. // set number of threads to serve the queue; you can change this on the fly,
  9930. // but if you decrease it, it won't decrease until things currently on the
  9931. // queue are finished
  9932. STB_EXTERN void stb_work_numthreads(int n);
  9933. // set maximum number of units in the queue; you can only set this BEFORE running any work functions
  9934. STB_EXTERN int stb_work_maxunits(int n);
  9935. // enqueue some work to be done (can do this from any thread, or even from a piece of work);
  9936. // return value of f is stored in *return_code if non-NULL
  9937. STB_EXTERN int stb_work(stb_thread_func f, void *d, volatile void **return_code);
  9938. // as above, but stb_sync_reach is called on 'rel' after work is complete
  9939. STB_EXTERN int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);
  9940. // necessary to call this when using volatile to order writes/reads
  9941. STB_EXTERN void stb_barrier(void);
  9942. // support for independent queues with their own threads
  9943. typedef struct stb__workqueue stb_workqueue;
  9944. STB_EXTERN stb_workqueue*stb_workq_new(int numthreads, int max_units);
  9945. STB_EXTERN stb_workqueue*stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex);
  9946. STB_EXTERN void stb_workq_delete(stb_workqueue *q);
  9947. STB_EXTERN void stb_workq_numthreads(stb_workqueue *q, int n);
  9948. STB_EXTERN int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code);
  9949. STB_EXTERN int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);
  9950. STB_EXTERN int stb_workq_length(stb_workqueue *q);
  9951. STB_EXTERN stb_thread stb_create_thread (stb_thread_func f, void *d);
  9952. STB_EXTERN stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel);
  9953. STB_EXTERN void stb_destroy_thread(stb_thread t);
  9954. STB_EXTERN stb_semaphore stb_sem_new(int max_val);
  9955. STB_EXTERN stb_semaphore stb_sem_new_extra(int max_val, int start_val);
  9956. STB_EXTERN void stb_sem_delete (stb_semaphore s);
  9957. STB_EXTERN void stb_sem_waitfor(stb_semaphore s);
  9958. STB_EXTERN void stb_sem_release(stb_semaphore s);
  9959. STB_EXTERN stb_mutex stb_mutex_new(void);
  9960. STB_EXTERN void stb_mutex_delete(stb_mutex m);
  9961. STB_EXTERN void stb_mutex_begin(stb_mutex m);
  9962. STB_EXTERN void stb_mutex_end(stb_mutex m);
  9963. STB_EXTERN stb_sync stb_sync_new(void);
  9964. STB_EXTERN void stb_sync_delete(stb_sync s);
  9965. STB_EXTERN int stb_sync_set_target(stb_sync s, int count);
  9966. STB_EXTERN void stb_sync_reach_and_wait(stb_sync s); // wait for 'target' reachers
  9967. STB_EXTERN int stb_sync_reach(stb_sync s);
  9968. typedef struct stb__threadqueue stb_threadqueue;
  9969. #define STB_THREADQ_DYNAMIC 0
  9970. STB_EXTERN stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove);
  9971. STB_EXTERN void stb_threadq_delete(stb_threadqueue *tq);
  9972. STB_EXTERN int stb_threadq_get(stb_threadqueue *tq, void *output);
  9973. STB_EXTERN void stb_threadq_get_block(stb_threadqueue *tq, void *output);
  9974. STB_EXTERN int stb_threadq_add(stb_threadqueue *tq, void *input);
  9975. // can return FALSE if STB_THREADQ_DYNAMIC and attempt to grow fails
  9976. STB_EXTERN int stb_threadq_add_block(stb_threadqueue *tq, void *input);
  9977. #ifdef STB_THREADS
  9978. #ifdef STB_DEFINE
  9979. typedef struct
  9980. {
  9981. stb_thread_func f;
  9982. void *d;
  9983. volatile void **return_val;
  9984. stb_semaphore sem;
  9985. } stb__thread;
  9986. // this is initialized along all possible paths to create threads, therefore
  9987. // it's always initialized before any other threads are create, therefore
  9988. // it's free of races AS LONG AS you only create threads through stb_*
  9989. static stb_mutex stb__threadmutex, stb__workmutex;
  9990. static void stb__threadmutex_init(void)
  9991. {
  9992. if (stb__threadmutex == STB_SEMAPHORE_NULL) {
  9993. stb__threadmutex = stb_mutex_new();
  9994. stb__workmutex = stb_mutex_new();
  9995. }
  9996. }
  9997. #ifdef STB_THREAD_TEST
  9998. volatile float stb__t1=1, stb__t2;
  9999. static void stb__wait(int n)
  10000. {
  10001. float z = 0;
  10002. int i;
  10003. for (i=0; i < n; ++i)
  10004. z += 1 / (stb__t1+i);
  10005. stb__t2 = z;
  10006. }
  10007. #else
  10008. #define stb__wait(x)
  10009. #endif
  10010. #ifdef _WIN32
  10011. // avoid including windows.h -- note that our definitions aren't
  10012. // exactly the same (we don't define the security descriptor struct)
  10013. // so if you want to include windows.h, make sure you do it first.
  10014. #include <process.h>
  10015. #ifndef _WINDOWS_ // check windows.h guard
  10016. #define STB__IMPORT STB_EXTERN __declspec(dllimport)
  10017. #define STB__DW unsigned long
  10018. STB__IMPORT int __stdcall TerminateThread(void *, STB__DW);
  10019. STB__IMPORT void * __stdcall CreateSemaphoreA(void *sec, long,long,char*);
  10020. STB__IMPORT int __stdcall CloseHandle(void *);
  10021. STB__IMPORT STB__DW __stdcall WaitForSingleObject(void *, STB__DW);
  10022. STB__IMPORT int __stdcall ReleaseSemaphore(void *, long, long *);
  10023. STB__IMPORT void __stdcall Sleep(STB__DW);
  10024. #endif
  10025. // necessary to call this when using volatile to order writes/reads
  10026. void stb_barrier(void)
  10027. {
  10028. #ifdef MemoryBarrier
  10029. MemoryBarrier();
  10030. #else
  10031. long temp;
  10032. __asm xchg temp,eax;
  10033. #endif
  10034. }
  10035. static void stb__thread_run(void *t)
  10036. {
  10037. void *res;
  10038. stb__thread info = * (stb__thread *) t;
  10039. free(t);
  10040. res = info.f(info.d);
  10041. if (info.return_val)
  10042. *info.return_val = res;
  10043. if (info.sem != STB_SEMAPHORE_NULL)
  10044. stb_sem_release(info.sem);
  10045. }
  10046. static stb_thread stb_create_thread_raw(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)
  10047. {
  10048. #ifdef _MT
  10049. #if defined(STB_FASTMALLOC) && !defined(STB_FASTMALLOC_ITS_OKAY_I_ONLY_MALLOC_IN_ONE_THREAD)
  10050. stb_fatal("Error! Cannot use STB_FASTMALLOC with threads.\n");
  10051. return STB_THREAD_NULL;
  10052. #else
  10053. unsigned long id;
  10054. stb__thread *data = (stb__thread *) malloc(sizeof(*data));
  10055. if (!data) return NULL;
  10056. stb__threadmutex_init();
  10057. data->f = f;
  10058. data->d = d;
  10059. data->return_val = return_code;
  10060. data->sem = rel;
  10061. id = _beginthread(stb__thread_run, 0, data);
  10062. if (id == -1) return NULL;
  10063. return (void *) id;
  10064. #endif
  10065. #else
  10066. #ifdef STB_NO_STB_STRINGS
  10067. stb_fatal("Invalid compilation");
  10068. #else
  10069. stb_fatal("Must compile mult-threaded to use stb_thread/stb_work.");
  10070. #endif
  10071. return NULL;
  10072. #endif
  10073. }
  10074. // trivial win32 wrappers
  10075. void stb_destroy_thread(stb_thread t) { TerminateThread(t,0); }
  10076. stb_semaphore stb_sem_new(int maxv) {return CreateSemaphoreA(NULL,0,maxv,NULL); }
  10077. stb_semaphore stb_sem_new_extra(int maxv,int start){return CreateSemaphoreA(NULL,start,maxv,NULL); }
  10078. void stb_sem_delete(stb_semaphore s) { if (s != NULL) CloseHandle(s); }
  10079. void stb_sem_waitfor(stb_semaphore s) { WaitForSingleObject(s, 0xffffffff); } // INFINITE
  10080. void stb_sem_release(stb_semaphore s) { ReleaseSemaphore(s,1,NULL); }
  10081. static void stb__thread_sleep(int ms) { Sleep(ms); }
  10082. #ifndef _WINDOWS_
  10083. STB__IMPORT int __stdcall GetProcessAffinityMask(void *, STB__DW *, STB__DW *);
  10084. STB__IMPORT void * __stdcall GetCurrentProcess(void);
  10085. STB__IMPORT int __stdcall SetProcessAffinityMask(void *, STB__DW);
  10086. #endif
  10087. int stb_processor_count(void)
  10088. {
  10089. unsigned long proc,sys;
  10090. GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);
  10091. return stb_bitcount(proc);
  10092. }
  10093. void stb_force_uniprocessor(void)
  10094. {
  10095. unsigned long proc,sys;
  10096. GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);
  10097. if (stb_bitcount(proc) > 1) {
  10098. int z;
  10099. for (z=0; z < 32; ++z)
  10100. if (proc & (1 << z))
  10101. break;
  10102. if (z < 32) {
  10103. proc = 1 << z;
  10104. SetProcessAffinityMask(GetCurrentProcess(), proc);
  10105. }
  10106. }
  10107. }
  10108. #ifdef _WINDOWS_
  10109. #define STB_MUTEX_NATIVE
  10110. void *stb_mutex_new(void)
  10111. {
  10112. CRITICAL_SECTION *p = (CRITICAL_SECTION *) malloc(sizeof(*p));
  10113. if (p)
  10114. #if _WIN32_WINNT >= 0x0500
  10115. InitializeCriticalSectionAndSpinCount(p, 500);
  10116. #else
  10117. InitializeCriticalSection(p);
  10118. #endif
  10119. return p;
  10120. }
  10121. void stb_mutex_delete(void *p)
  10122. {
  10123. if (p) {
  10124. DeleteCriticalSection((CRITICAL_SECTION *) p);
  10125. free(p);
  10126. }
  10127. }
  10128. void stb_mutex_begin(void *p)
  10129. {
  10130. stb__wait(500);
  10131. if (p)
  10132. EnterCriticalSection((CRITICAL_SECTION *) p);
  10133. }
  10134. void stb_mutex_end(void *p)
  10135. {
  10136. if (p)
  10137. LeaveCriticalSection((CRITICAL_SECTION *) p);
  10138. stb__wait(500);
  10139. }
  10140. #endif // _WINDOWS_
  10141. #if 0
  10142. // for future reference,
  10143. // InterlockedCompareExchange for x86:
  10144. int cas64_mp(void * dest, void * xcmp, void * xxchg) {
  10145. __asm
  10146. {
  10147. mov esi, [xxchg] ; exchange
  10148. mov ebx, [esi + 0]
  10149. mov ecx, [esi + 4]
  10150. mov esi, [xcmp] ; comparand
  10151. mov eax, [esi + 0]
  10152. mov edx, [esi + 4]
  10153. mov edi, [dest] ; destination
  10154. lock cmpxchg8b [edi]
  10155. jz yyyy;
  10156. mov [esi + 0], eax;
  10157. mov [esi + 4], edx;
  10158. yyyy:
  10159. xor eax, eax;
  10160. setz al;
  10161. };
  10162. inline unsigned __int64 _InterlockedCompareExchange64(volatile unsigned __int64 *dest
  10163. ,unsigned __int64 exchange
  10164. ,unsigned __int64 comperand)
  10165. {
  10166. //value returned in eax::edx
  10167. __asm {
  10168. lea esi,comperand;
  10169. lea edi,exchange;
  10170. mov eax,[esi];
  10171. mov edx,4[esi];
  10172. mov ebx,[edi];
  10173. mov ecx,4[edi];
  10174. mov esi,dest;
  10175. lock CMPXCHG8B [esi];
  10176. }
  10177. #endif // #if 0
  10178. #endif // _WIN32
  10179. stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)
  10180. {
  10181. return stb_create_thread_raw(f,d,return_code,rel);
  10182. }
  10183. stb_thread stb_create_thread(stb_thread_func f, void *d)
  10184. {
  10185. return stb_create_thread2(f,d,NULL,STB_SEMAPHORE_NULL);
  10186. }
  10187. // mutex implemented by wrapping semaphore
  10188. #ifndef STB_MUTEX_NATIVE
  10189. stb_mutex stb_mutex_new(void) { return stb_sem_new_extra(1,1); }
  10190. void stb_mutex_delete(stb_mutex m) { stb_sem_delete (m); }
  10191. void stb_mutex_begin(stb_mutex m) { stb__wait(500); if (m) stb_sem_waitfor(m); }
  10192. void stb_mutex_end(stb_mutex m) { if (m) stb_sem_release(m); stb__wait(500); }
  10193. #endif
  10194. // thread merge operation
  10195. struct stb__sync
  10196. {
  10197. int target; // target number of threads to hit it
  10198. int sofar; // total threads that hit it
  10199. int waiting; // total threads waiting
  10200. stb_mutex start; // mutex to prevent starting again before finishing previous
  10201. stb_mutex mutex; // mutex while tweaking state
  10202. stb_semaphore release; // semaphore wake up waiting threads
  10203. // we have to wake them up one at a time, rather than using a single release
  10204. // call, because win32 semaphores don't let you dynamically change the max count!
  10205. };
  10206. stb_sync stb_sync_new(void)
  10207. {
  10208. stb_sync s = (stb_sync) malloc(sizeof(*s));
  10209. if (!s) return s;
  10210. s->target = s->sofar = s->waiting = 0;
  10211. s->mutex = stb_mutex_new();
  10212. s->start = stb_mutex_new();
  10213. s->release = stb_sem_new(1);
  10214. if (s->mutex == STB_MUTEX_NULL || s->release == STB_SEMAPHORE_NULL || s->start == STB_MUTEX_NULL) {
  10215. stb_mutex_delete(s->mutex);
  10216. stb_mutex_delete(s->mutex);
  10217. stb_sem_delete(s->release);
  10218. free(s);
  10219. return NULL;
  10220. }
  10221. return s;
  10222. }
  10223. void stb_sync_delete(stb_sync s)
  10224. {
  10225. if (s->waiting) {
  10226. // it's bad to delete while there are threads waiting!
  10227. // shall we wait for them to reach, or just bail? just bail
  10228. assert(0);
  10229. }
  10230. stb_mutex_delete(s->mutex);
  10231. stb_mutex_delete(s->release);
  10232. free(s);
  10233. }
  10234. int stb_sync_set_target(stb_sync s, int count)
  10235. {
  10236. // don't allow setting a target until the last one is fully released;
  10237. // note that this can lead to inefficient pipelining, and maybe we'd
  10238. // be better off ping-ponging between two internal syncs?
  10239. // I tried seeing how often this happened using TryEnterCriticalSection
  10240. // and could _never_ get it to happen in imv(stb), even with more threads
  10241. // than processors. So who knows!
  10242. stb_mutex_begin(s->start);
  10243. // this mutex is pointless, since it's not valid for threads
  10244. // to call reach() before anyone calls set_target() anyway
  10245. stb_mutex_begin(s->mutex);
  10246. assert(s->target == 0); // enforced by start mutex
  10247. s->target = count;
  10248. s->sofar = 0;
  10249. s->waiting = 0;
  10250. stb_mutex_end(s->mutex);
  10251. return STB_TRUE;
  10252. }
  10253. void stb__sync_release(stb_sync s)
  10254. {
  10255. if (s->waiting)
  10256. stb_sem_release(s->release);
  10257. else {
  10258. s->target = 0;
  10259. stb_mutex_end(s->start);
  10260. }
  10261. }
  10262. int stb_sync_reach(stb_sync s)
  10263. {
  10264. int n;
  10265. stb_mutex_begin(s->mutex);
  10266. assert(s->sofar < s->target);
  10267. n = ++s->sofar; // record this value to avoid possible race if we did 'return s->sofar';
  10268. if (s->sofar == s->target)
  10269. stb__sync_release(s);
  10270. stb_mutex_end(s->mutex);
  10271. return n;
  10272. }
  10273. void stb_sync_reach_and_wait(stb_sync s)
  10274. {
  10275. stb_mutex_begin(s->mutex);
  10276. assert(s->sofar < s->target);
  10277. ++s->sofar;
  10278. if (s->sofar == s->target) {
  10279. stb__sync_release(s);
  10280. stb_mutex_end(s->mutex);
  10281. } else {
  10282. ++s->waiting; // we're waiting, so one more waiter
  10283. stb_mutex_end(s->mutex); // release the mutex to other threads
  10284. stb_sem_waitfor(s->release); // wait for merge completion
  10285. stb_mutex_begin(s->mutex); // on merge completion, grab the mutex
  10286. --s->waiting; // we're done waiting
  10287. stb__sync_release(s); // restart the next waiter
  10288. stb_mutex_end(s->mutex); // and now we're done
  10289. // this ends the same as the first case, but it's a lot
  10290. // clearer to understand without sharing the code
  10291. }
  10292. }
  10293. struct stb__threadqueue
  10294. {
  10295. stb_mutex add, remove;
  10296. stb_semaphore nonempty, nonfull;
  10297. int head_blockers; // number of threads blocking--used to know whether to release(avail)
  10298. int tail_blockers;
  10299. int head, tail, array_size, growable;
  10300. int item_size;
  10301. char *data;
  10302. };
  10303. static int stb__tq_wrap(volatile stb_threadqueue *z, int p)
  10304. {
  10305. if (p == z->array_size)
  10306. return p - z->array_size;
  10307. else
  10308. return p;
  10309. }
  10310. int stb__threadq_get_raw(stb_threadqueue *tq2, void *output, int block)
  10311. {
  10312. volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;
  10313. if (tq->head == tq->tail && !block) return 0;
  10314. stb_mutex_begin(tq->remove);
  10315. while (tq->head == tq->tail) {
  10316. if (!block) {
  10317. stb_mutex_end(tq->remove);
  10318. return 0;
  10319. }
  10320. ++tq->head_blockers;
  10321. stb_mutex_end(tq->remove);
  10322. stb_sem_waitfor(tq->nonempty);
  10323. stb_mutex_begin(tq->remove);
  10324. --tq->head_blockers;
  10325. }
  10326. memcpy(output, tq->data + tq->head*tq->item_size, tq->item_size);
  10327. stb_barrier();
  10328. tq->head = stb__tq_wrap(tq, tq->head+1);
  10329. stb_sem_release(tq->nonfull);
  10330. if (tq->head_blockers) // can't check if actually non-empty due to race?
  10331. stb_sem_release(tq->nonempty); // if there are other blockers, wake one
  10332. stb_mutex_end(tq->remove);
  10333. return STB_TRUE;
  10334. }
  10335. int stb__threadq_grow(volatile stb_threadqueue *tq)
  10336. {
  10337. int n;
  10338. char *p;
  10339. assert(tq->remove != STB_MUTEX_NULL); // must have this to allow growth!
  10340. stb_mutex_begin(tq->remove);
  10341. n = tq->array_size * 2;
  10342. p = (char *) realloc(tq->data, n * tq->item_size);
  10343. if (p == NULL) {
  10344. stb_mutex_end(tq->remove);
  10345. stb_mutex_end(tq->add);
  10346. return STB_FALSE;
  10347. }
  10348. if (tq->tail < tq->head) {
  10349. memcpy(p + tq->array_size * tq->item_size, p, tq->tail * tq->item_size);
  10350. tq->tail += tq->array_size;
  10351. }
  10352. tq->data = p;
  10353. tq->array_size = n;
  10354. stb_mutex_end(tq->remove);
  10355. return STB_TRUE;
  10356. }
  10357. int stb__threadq_add_raw(stb_threadqueue *tq2, void *input, int block)
  10358. {
  10359. int tail,pos;
  10360. volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;
  10361. stb_mutex_begin(tq->add);
  10362. for(;;) {
  10363. pos = tq->tail;
  10364. tail = stb__tq_wrap(tq, pos+1);
  10365. if (tail != tq->head) break;
  10366. // full
  10367. if (tq->growable) {
  10368. if (!stb__threadq_grow(tq)) {
  10369. stb_mutex_end(tq->add);
  10370. return STB_FALSE; // out of memory
  10371. }
  10372. } else if (!block) {
  10373. stb_mutex_end(tq->add);
  10374. return STB_FALSE;
  10375. } else {
  10376. ++tq->tail_blockers;
  10377. stb_mutex_end(tq->add);
  10378. stb_sem_waitfor(tq->nonfull);
  10379. stb_mutex_begin(tq->add);
  10380. --tq->tail_blockers;
  10381. }
  10382. }
  10383. memcpy(tq->data + tq->item_size * pos, input, tq->item_size);
  10384. stb_barrier();
  10385. tq->tail = tail;
  10386. stb_sem_release(tq->nonempty);
  10387. if (tq->tail_blockers) // can't check if actually non-full due to race?
  10388. stb_sem_release(tq->nonfull);
  10389. stb_mutex_end(tq->add);
  10390. return STB_TRUE;
  10391. }
  10392. int stb_threadq_length(stb_threadqueue *tq2)
  10393. {
  10394. int a,b,n;
  10395. volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;
  10396. stb_mutex_begin(tq->add);
  10397. a = tq->head;
  10398. b = tq->tail;
  10399. n = tq->array_size;
  10400. stb_mutex_end(tq->add);
  10401. if (a > b) b += n;
  10402. return b-a;
  10403. }
  10404. int stb_threadq_get(stb_threadqueue *tq, void *output)
  10405. {
  10406. return stb__threadq_get_raw(tq, output, STB_FALSE);
  10407. }
  10408. void stb_threadq_get_block(stb_threadqueue *tq, void *output)
  10409. {
  10410. stb__threadq_get_raw(tq, output, STB_TRUE);
  10411. }
  10412. int stb_threadq_add(stb_threadqueue *tq, void *input)
  10413. {
  10414. return stb__threadq_add_raw(tq, input, STB_FALSE);
  10415. }
  10416. int stb_threadq_add_block(stb_threadqueue *tq, void *input)
  10417. {
  10418. return stb__threadq_add_raw(tq, input, STB_TRUE);
  10419. }
  10420. void stb_threadq_delete(stb_threadqueue *tq)
  10421. {
  10422. if (tq) {
  10423. free(tq->data);
  10424. stb_mutex_delete(tq->add);
  10425. stb_mutex_delete(tq->remove);
  10426. stb_sem_delete(tq->nonempty);
  10427. stb_sem_delete(tq->nonfull);
  10428. free(tq);
  10429. }
  10430. }
  10431. #define STB_THREADQUEUE_DYNAMIC 0
  10432. stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove)
  10433. {
  10434. int error=0;
  10435. stb_threadqueue *tq = (stb_threadqueue *) malloc(sizeof(*tq));
  10436. if (tq == NULL) return NULL;
  10437. if (num_items == STB_THREADQUEUE_DYNAMIC) {
  10438. tq->growable = STB_TRUE;
  10439. num_items = 32;
  10440. } else
  10441. tq->growable = STB_FALSE;
  10442. tq->item_size = item_size;
  10443. tq->array_size = num_items+1;
  10444. tq->add = tq->remove = STB_MUTEX_NULL;
  10445. tq->nonempty = tq->nonfull = STB_SEMAPHORE_NULL;
  10446. tq->data = NULL;
  10447. if (many_add)
  10448. { tq->add = stb_mutex_new(); if (tq->add == STB_MUTEX_NULL) goto error; }
  10449. if (many_remove || tq->growable)
  10450. { tq->remove = stb_mutex_new(); if (tq->remove == STB_MUTEX_NULL) goto error; }
  10451. tq->nonempty = stb_sem_new(1); if (tq->nonempty == STB_SEMAPHORE_NULL) goto error;
  10452. tq->nonfull = stb_sem_new(1); if (tq->nonfull == STB_SEMAPHORE_NULL) goto error;
  10453. tq->data = (char *) malloc(tq->item_size * tq->array_size);
  10454. if (tq->data == NULL) goto error;
  10455. tq->head = tq->tail = 0;
  10456. tq->head_blockers = tq->tail_blockers = 0;
  10457. return tq;
  10458. error:
  10459. stb_threadq_delete(tq);
  10460. return NULL;
  10461. }
  10462. typedef struct
  10463. {
  10464. stb_thread_func f;
  10465. void *d;
  10466. volatile void **retval;
  10467. stb_sync sync;
  10468. } stb__workinfo;
  10469. //static volatile stb__workinfo *stb__work;
  10470. struct stb__workqueue
  10471. {
  10472. int numthreads;
  10473. stb_threadqueue *tq;
  10474. };
  10475. static stb_workqueue *stb__work_global;
  10476. static void *stb__thread_workloop(void *p)
  10477. {
  10478. volatile stb_workqueue *q = (volatile stb_workqueue *) p;
  10479. for(;;) {
  10480. void *z;
  10481. stb__workinfo w;
  10482. stb_threadq_get_block(q->tq, &w);
  10483. if (w.f == NULL) // null work is a signal to end the thread
  10484. return NULL;
  10485. z = w.f(w.d);
  10486. if (w.retval) { stb_barrier(); *w.retval = z; }
  10487. if (w.sync != STB_SYNC_NULL) stb_sync_reach(w.sync);
  10488. }
  10489. }
  10490. stb_workqueue *stb_workq_new(int num_threads, int max_units)
  10491. {
  10492. return stb_workq_new_flags(num_threads, max_units, 0,0);
  10493. }
  10494. stb_workqueue *stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex)
  10495. {
  10496. stb_workqueue *q = (stb_workqueue *) malloc(sizeof(*q));
  10497. if (q == NULL) return NULL;
  10498. q->tq = stb_threadq_new(sizeof(stb__workinfo), max_units, !no_add_mutex, !no_remove_mutex);
  10499. if (q->tq == NULL) { free(q); return NULL; }
  10500. q->numthreads = 0;
  10501. stb_workq_numthreads(q, numthreads);
  10502. return q;
  10503. }
  10504. void stb_workq_delete(stb_workqueue *q)
  10505. {
  10506. while (stb_workq_length(q) != 0)
  10507. stb__thread_sleep(1);
  10508. stb_threadq_delete(q->tq);
  10509. free(q);
  10510. }
  10511. static int stb__work_maxitems = STB_THREADQUEUE_DYNAMIC;
  10512. static void stb_work_init(int num_threads)
  10513. {
  10514. if (stb__work_global == NULL) {
  10515. stb__threadmutex_init();
  10516. stb_mutex_begin(stb__workmutex);
  10517. stb_barrier();
  10518. if (*(stb_workqueue * volatile *) &stb__work_global == NULL)
  10519. stb__work_global = stb_workq_new(num_threads, stb__work_maxitems);
  10520. stb_mutex_end(stb__workmutex);
  10521. }
  10522. }
  10523. static int stb__work_raw(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)
  10524. {
  10525. stb__workinfo w;
  10526. if (q == NULL) {
  10527. stb_work_init(1);
  10528. q = stb__work_global;
  10529. }
  10530. w.f = f;
  10531. w.d = d;
  10532. w.retval = return_code;
  10533. w.sync = rel;
  10534. return stb_threadq_add(q->tq, &w);
  10535. }
  10536. int stb_workq_length(stb_workqueue *q)
  10537. {
  10538. return stb_threadq_length(q->tq);
  10539. }
  10540. int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code)
  10541. {
  10542. if (f == NULL) return 0;
  10543. return stb_workq_reach(q, f, d, return_code, NULL);
  10544. }
  10545. int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)
  10546. {
  10547. if (f == NULL) return 0;
  10548. return stb__work_raw(q, f, d, return_code, rel);
  10549. }
  10550. static void stb__workq_numthreads(stb_workqueue *q, int n)
  10551. {
  10552. while (q->numthreads < n) {
  10553. stb_create_thread(stb__thread_workloop, q);
  10554. ++q->numthreads;
  10555. }
  10556. while (q->numthreads > n) {
  10557. stb__work_raw(q, NULL, NULL, NULL, NULL);
  10558. --q->numthreads;
  10559. }
  10560. }
  10561. void stb_workq_numthreads(stb_workqueue *q, int n)
  10562. {
  10563. stb_mutex_begin(stb__threadmutex);
  10564. stb__workq_numthreads(q,n);
  10565. stb_mutex_end(stb__threadmutex);
  10566. }
  10567. int stb_work_maxunits(int n)
  10568. {
  10569. if (stb__work_global == NULL) {
  10570. stb__work_maxitems = n;
  10571. stb_work_init(1);
  10572. }
  10573. return stb__work_maxitems;
  10574. }
  10575. int stb_work(stb_thread_func f, void *d, volatile void **return_code)
  10576. {
  10577. return stb_workq(stb__work_global, f,d,return_code);
  10578. }
  10579. int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)
  10580. {
  10581. return stb_workq_reach(stb__work_global, f,d,return_code,rel);
  10582. }
  10583. void stb_work_numthreads(int n)
  10584. {
  10585. if (stb__work_global == NULL)
  10586. stb_work_init(n);
  10587. else
  10588. stb_workq_numthreads(stb__work_global, n);
  10589. }
  10590. #endif // STB_DEFINE
  10591. //////////////////////////////////////////////////////////////////////////////
  10592. //
  10593. // Background disk I/O
  10594. //
  10595. //
  10596. #define STB_BGIO_READ_ALL (-1)
  10597. STB_EXTERN int stb_bgio_read (char *filename, int offset, int len, stb_uchar **result, int *olen);
  10598. STB_EXTERN int stb_bgio_readf (FILE *f , int offset, int len, stb_uchar **result, int *olen);
  10599. STB_EXTERN int stb_bgio_read_to (char *filename, int offset, int len, stb_uchar *buffer, int *olen);
  10600. STB_EXTERN int stb_bgio_readf_to(FILE *f , int offset, int len, stb_uchar *buffer, int *olen);
  10601. typedef struct
  10602. {
  10603. int have_data;
  10604. int is_valid;
  10605. int is_dir;
  10606. time_t filetime;
  10607. stb_int64 filesize;
  10608. } stb_bgstat;
  10609. STB_EXTERN int stb_bgio_stat (char *filename, stb_bgstat *result);
  10610. #ifdef STB_DEFINE
  10611. static stb_workqueue *stb__diskio;
  10612. static stb_mutex stb__diskio_mutex;
  10613. void stb_thread_cleanup(void)
  10614. {
  10615. if (stb__work_global) stb_workq_delete(stb__work_global); stb__work_global = NULL;
  10616. if (stb__threadmutex) stb_mutex_delete(stb__threadmutex); stb__threadmutex = NULL;
  10617. if (stb__workmutex) stb_mutex_delete(stb__workmutex); stb__workmutex = NULL;
  10618. if (stb__diskio) stb_workq_delete(stb__diskio); stb__diskio = NULL;
  10619. if (stb__diskio_mutex)stb_mutex_delete(stb__diskio_mutex);stb__diskio_mutex= NULL;
  10620. }
  10621. typedef struct
  10622. {
  10623. char *filename;
  10624. FILE *f;
  10625. int offset;
  10626. int len;
  10627. stb_bgstat *stat_out;
  10628. stb_uchar *output;
  10629. stb_uchar **result;
  10630. int *len_output;
  10631. int *flag;
  10632. } stb__disk_command;
  10633. #define STB__MAX_DISK_COMMAND 100
  10634. static stb__disk_command stb__dc_queue[STB__MAX_DISK_COMMAND];
  10635. static int stb__dc_offset;
  10636. void stb__io_init(void)
  10637. {
  10638. if (!stb__diskio) {
  10639. stb__threadmutex_init();
  10640. stb_mutex_begin(stb__threadmutex);
  10641. stb_barrier();
  10642. if (*(stb_thread * volatile *) &stb__diskio == NULL) {
  10643. stb__diskio_mutex = stb_mutex_new();
  10644. // use many threads so OS can try to schedule seeks
  10645. stb__diskio = stb_workq_new_flags(16,STB__MAX_DISK_COMMAND,STB_FALSE,STB_FALSE);
  10646. }
  10647. stb_mutex_end(stb__threadmutex);
  10648. }
  10649. }
  10650. static void * stb__io_error(stb__disk_command *dc)
  10651. {
  10652. if (dc->len_output) *dc->len_output = 0;
  10653. if (dc->result) *dc->result = NULL;
  10654. if (dc->flag) *dc->flag = -1;
  10655. return NULL;
  10656. }
  10657. static void * stb__io_task(void *p)
  10658. {
  10659. stb__disk_command *dc = (stb__disk_command *) p;
  10660. int len;
  10661. FILE *f;
  10662. stb_uchar *buf;
  10663. if (dc->stat_out) {
  10664. struct _stati64 s;
  10665. if (!_stati64(dc->filename, &s)) {
  10666. dc->stat_out->filesize = s.st_size;
  10667. dc->stat_out->filetime = s.st_mtime;
  10668. dc->stat_out->is_dir = s.st_mode & _S_IFDIR;
  10669. dc->stat_out->is_valid = (s.st_mode & _S_IFREG) || dc->stat_out->is_dir;
  10670. } else
  10671. dc->stat_out->is_valid = 0;
  10672. stb_barrier();
  10673. dc->stat_out->have_data = 1;
  10674. free(dc->filename);
  10675. return 0;
  10676. }
  10677. if (dc->f) {
  10678. #ifdef WIN32
  10679. f = _fdopen(_dup(_fileno(dc->f)), "rb");
  10680. #else
  10681. f = fdopen(dup(fileno(dc->f)), "rb");
  10682. #endif
  10683. if (!f)
  10684. return stb__io_error(dc);
  10685. } else {
  10686. f = fopen(dc->filename, "rb");
  10687. free(dc->filename);
  10688. if (!f)
  10689. return stb__io_error(dc);
  10690. }
  10691. len = dc->len;
  10692. if (len < 0) {
  10693. fseek(f, 0, SEEK_END);
  10694. len = ftell(f) - dc->offset;
  10695. }
  10696. if (fseek(f, dc->offset, SEEK_SET)) {
  10697. fclose(f);
  10698. return stb__io_error(dc);
  10699. }
  10700. if (dc->output)
  10701. buf = dc->output;
  10702. else {
  10703. buf = (stb_uchar *) malloc(len);
  10704. if (buf == NULL) {
  10705. fclose(f);
  10706. return stb__io_error(dc);
  10707. }
  10708. }
  10709. len = fread(buf, 1, len, f);
  10710. fclose(f);
  10711. if (dc->len_output) *dc->len_output = len;
  10712. if (dc->result) *dc->result = buf;
  10713. if (dc->flag) *dc->flag = 1;
  10714. return NULL;
  10715. }
  10716. int stb__io_add(char *fname, FILE *f, int off, int len, stb_uchar *out, stb_uchar **result, int *olen, int *flag, stb_bgstat *stat)
  10717. {
  10718. int res;
  10719. stb__io_init();
  10720. // do memory allocation outside of mutex
  10721. if (fname) fname = strdup(fname);
  10722. stb_mutex_begin(stb__diskio_mutex);
  10723. {
  10724. stb__disk_command *dc = &stb__dc_queue[stb__dc_offset];
  10725. dc->filename = fname;
  10726. dc->f = f;
  10727. dc->offset = off;
  10728. dc->len = len;
  10729. dc->output = out;
  10730. dc->result = result;
  10731. dc->len_output = olen;
  10732. dc->flag = flag;
  10733. dc->stat_out = stat;
  10734. res = stb_workq(stb__diskio, stb__io_task, dc, NULL);
  10735. if (res)
  10736. stb__dc_offset = (stb__dc_offset + 1 == STB__MAX_DISK_COMMAND ? 0 : stb__dc_offset+1);
  10737. }
  10738. stb_mutex_end(stb__diskio_mutex);
  10739. return res;
  10740. }
  10741. int stb_bgio_read(char *filename, int offset, int len, stb_uchar **result, int *olen)
  10742. {
  10743. return stb__io_add(filename,NULL,offset,len,NULL,result,olen,NULL,NULL);
  10744. }
  10745. int stb_bgio_readf(FILE *f, int offset, int len, stb_uchar **result, int *olen)
  10746. {
  10747. return stb__io_add(NULL,f,offset,len,NULL,result,olen,NULL,NULL);
  10748. }
  10749. int stb_bgio_read_to(char *filename, int offset, int len, stb_uchar *buffer, int *olen)
  10750. {
  10751. return stb__io_add(filename,NULL,offset,len,buffer,NULL,olen,NULL,NULL);
  10752. }
  10753. int stb_bgio_readf_to(FILE *f, int offset, int len, stb_uchar *buffer, int *olen)
  10754. {
  10755. return stb__io_add(NULL,f,offset,len,buffer,NULL,olen,NULL,NULL);
  10756. }
  10757. STB_EXTERN int stb_bgio_stat (char *filename, stb_bgstat *result)
  10758. {
  10759. result->have_data = 0;
  10760. return stb__io_add(filename,NULL,0,0,0,NULL,0,NULL, result);
  10761. }
  10762. #endif
  10763. #endif
  10764. //////////////////////////////////////////////////////////////////////////////
  10765. //
  10766. // Fast malloc implementation
  10767. //
  10768. // This is a clone of TCMalloc, but without the thread support.
  10769. // 1. large objects are allocated directly, page-aligned
  10770. // 2. small objects are allocated in homogeonous heaps, 0 overhead
  10771. //
  10772. // We keep an allocation table for pages a la TCMalloc. This would
  10773. // require 4MB for the entire address space, but we only allocate
  10774. // the parts that are in use. The overhead from using homogenous heaps
  10775. // everywhere is 3MB. (That is, if you allocate 1 object of each size,
  10776. // you'll use 3MB.)
  10777. #if defined(STB_DEFINE) && (defined(_WIN32) || defined(STB_FASTMALLOC))
  10778. #ifdef _WIN32
  10779. #ifndef _WINDOWS_
  10780. #ifndef STB__IMPORT
  10781. #define STB__IMPORT STB_EXTERN __declspec(dllimport)
  10782. #define STB__DW unsigned long
  10783. #endif
  10784. STB__IMPORT void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);
  10785. STB__IMPORT int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);
  10786. #endif
  10787. #define stb__alloc_pages_raw(x) (stb_uint32) VirtualAlloc(NULL, (x), 0x3000, 0x04)
  10788. #define stb__dealloc_pages_raw(p) VirtualFree((void *) p, 0, 0x8000)
  10789. #else
  10790. #error "Platform not currently supported"
  10791. #endif
  10792. typedef struct stb__span
  10793. {
  10794. int start, len;
  10795. struct stb__span *next, *prev;
  10796. void *first_free;
  10797. unsigned short list; // 1..256 free; 257..511 sizeclass; 0=large block
  10798. short allocations; // # outstanding allocations for sizeclass
  10799. } stb__span; // 24
  10800. static stb__span **stb__span_for_page;
  10801. static int stb__firstpage, stb__lastpage;
  10802. static void stb__update_page_range(int first, int last)
  10803. {
  10804. stb__span **sfp;
  10805. int i, f,l;
  10806. if (first >= stb__firstpage && last <= stb__lastpage) return;
  10807. if (stb__span_for_page == NULL) {
  10808. f = first;
  10809. l = f+stb_max(last-f, 16384);
  10810. l = stb_min(l, 1<<20);
  10811. } else if (last > stb__lastpage) {
  10812. f = stb__firstpage;
  10813. l = f + (stb__lastpage - f) * 2;
  10814. l = stb_clamp(last, l,1<<20);
  10815. } else {
  10816. l = stb__lastpage;
  10817. f = l - (l - stb__firstpage) * 2;
  10818. f = stb_clamp(f, 0,first);
  10819. }
  10820. sfp = (stb__span **) stb__alloc_pages_raw(sizeof(void *) * (l-f));
  10821. for (i=f; i < stb__firstpage; ++i) sfp[i - f] = NULL;
  10822. for ( ; i < stb__lastpage ; ++i) sfp[i - f] = stb__span_for_page[i - stb__firstpage];
  10823. for ( ; i < l ; ++i) sfp[i - f] = NULL;
  10824. if (stb__span_for_page) stb__dealloc_pages_raw(stb__span_for_page);
  10825. stb__firstpage = f;
  10826. stb__lastpage = l;
  10827. stb__span_for_page = sfp;
  10828. }
  10829. static stb__span *stb__span_free=NULL;
  10830. static stb__span *stb__span_first, *stb__span_end;
  10831. static stb__span *stb__span_alloc(void)
  10832. {
  10833. stb__span *s = stb__span_free;
  10834. if (s)
  10835. stb__span_free = s->next;
  10836. else {
  10837. if (!stb__span_first) {
  10838. stb__span_first = (stb__span *) stb__alloc_pages_raw(65536);
  10839. if (stb__span_first == NULL) return NULL;
  10840. stb__span_end = stb__span_first + (65536 / sizeof(stb__span));
  10841. }
  10842. s = stb__span_first++;
  10843. if (stb__span_first == stb__span_end) stb__span_first = NULL;
  10844. }
  10845. return s;
  10846. }
  10847. static stb__span *stb__spanlist[512];
  10848. static void stb__spanlist_unlink(stb__span *s)
  10849. {
  10850. if (s->prev)
  10851. s->prev->next = s->next;
  10852. else {
  10853. int n = s->list;
  10854. assert(stb__spanlist[n] == s);
  10855. stb__spanlist[n] = s->next;
  10856. }
  10857. if (s->next)
  10858. s->next->prev = s->prev;
  10859. s->next = s->prev = NULL;
  10860. s->list = 0;
  10861. }
  10862. static void stb__spanlist_add(int n, stb__span *s)
  10863. {
  10864. s->list = n;
  10865. s->next = stb__spanlist[n];
  10866. s->prev = NULL;
  10867. stb__spanlist[n] = s;
  10868. if (s->next) s->next->prev = s;
  10869. }
  10870. #define stb__page_shift 12
  10871. #define stb__page_size (1 << stb__page_shift)
  10872. #define stb__page_number(x) ((x) >> stb__page_shift)
  10873. #define stb__page_address(x) ((x) << stb__page_shift)
  10874. static void stb__set_span_for_page(stb__span *s)
  10875. {
  10876. int i;
  10877. for (i=0; i < s->len; ++i)
  10878. stb__span_for_page[s->start + i - stb__firstpage] = s;
  10879. }
  10880. static stb__span *stb__coalesce(stb__span *a, stb__span *b)
  10881. {
  10882. assert(a->start + a->len == b->start);
  10883. if (a->list) stb__spanlist_unlink(a);
  10884. if (b->list) stb__spanlist_unlink(b);
  10885. a->len += b->len;
  10886. b->len = 0;
  10887. b->next = stb__span_free;
  10888. stb__span_free = b;
  10889. stb__set_span_for_page(a);
  10890. return a;
  10891. }
  10892. static void stb__free_span(stb__span *s)
  10893. {
  10894. stb__span *n = NULL;
  10895. if (s->start > stb__firstpage) {
  10896. n = stb__span_for_page[s->start-1 - stb__firstpage];
  10897. if (n && n->allocations == -2 && n->start + n->len == s->start) s = stb__coalesce(n,s);
  10898. }
  10899. if (s->start + s->len < stb__lastpage) {
  10900. n = stb__span_for_page[s->start + s->len - stb__firstpage];
  10901. if (n && n->allocations == -2 && s->start + s->len == n->start) s = stb__coalesce(s,n);
  10902. }
  10903. s->allocations = -2;
  10904. stb__spanlist_add(s->len > 256 ? 256 : s->len, s);
  10905. }
  10906. static stb__span *stb__alloc_pages(int num)
  10907. {
  10908. stb__span *s = stb__span_alloc();
  10909. int p;
  10910. if (!s) return NULL;
  10911. p = stb__alloc_pages_raw(num << stb__page_shift);
  10912. if (p == 0) { s->next = stb__span_free; stb__span_free = s; return 0; }
  10913. assert(stb__page_address(stb__page_number(p)) == p);
  10914. p = stb__page_number(p);
  10915. stb__update_page_range(p, p+num);
  10916. s->start = p;
  10917. s->len = num;
  10918. s->next = NULL;
  10919. s->prev = NULL;
  10920. stb__set_span_for_page(s);
  10921. return s;
  10922. }
  10923. static stb__span *stb__alloc_span(int pagecount)
  10924. {
  10925. int i;
  10926. stb__span *p = NULL;
  10927. for(i=pagecount; i < 256; ++i)
  10928. if (stb__spanlist[i]) {
  10929. p = stb__spanlist[i];
  10930. break;
  10931. }
  10932. if (!p) {
  10933. p = stb__spanlist[256];
  10934. while (p && p->len < pagecount)
  10935. p = p->next;
  10936. }
  10937. if (!p) {
  10938. p = stb__alloc_pages(pagecount < 16 ? 16 : pagecount);
  10939. if (p == NULL) return 0;
  10940. } else
  10941. stb__spanlist_unlink(p);
  10942. if (p->len > pagecount) {
  10943. stb__span *q = stb__span_alloc();
  10944. if (q) {
  10945. q->start = p->start + pagecount;
  10946. q->len = p->len - pagecount;
  10947. p->len = pagecount;
  10948. for (i=0; i < q->len; ++i)
  10949. stb__span_for_page[q->start+i - stb__firstpage] = q;
  10950. stb__spanlist_add(q->len > 256 ? 256 : q->len, q);
  10951. }
  10952. }
  10953. return p;
  10954. }
  10955. #define STB__MAX_SMALL_SIZE 32768
  10956. #define STB__MAX_SIZE_CLASSES 256
  10957. static unsigned char stb__class_base[32];
  10958. static unsigned char stb__class_shift[32];
  10959. static unsigned char stb__pages_for_class[STB__MAX_SIZE_CLASSES];
  10960. static int stb__size_for_class[STB__MAX_SIZE_CLASSES];
  10961. stb__span *stb__get_nonempty_sizeclass(int c)
  10962. {
  10963. int s = c + 256, i, size, tsize; // remap to span-list index
  10964. char *z;
  10965. void *q;
  10966. stb__span *p = stb__spanlist[s];
  10967. if (p) {
  10968. if (p->first_free) return p; // fast path: it's in the first one in list
  10969. for (p=p->next; p; p=p->next)
  10970. if (p->first_free) {
  10971. // move to front for future queries
  10972. stb__spanlist_unlink(p);
  10973. stb__spanlist_add(s, p);
  10974. return p;
  10975. }
  10976. }
  10977. // no non-empty ones, so allocate a new one
  10978. p = stb__alloc_span(stb__pages_for_class[c]);
  10979. if (!p) return NULL;
  10980. // create the free list up front
  10981. size = stb__size_for_class[c];
  10982. tsize = stb__pages_for_class[c] << stb__page_shift;
  10983. i = 0;
  10984. z = (char *) stb__page_address(p->start);
  10985. q = NULL;
  10986. while (i + size <= tsize) {
  10987. * (void **) z = q; q = z;
  10988. z += size;
  10989. i += size;
  10990. }
  10991. p->first_free = q;
  10992. p->allocations = 0;
  10993. stb__spanlist_add(s,p);
  10994. return p;
  10995. }
  10996. static int stb__sizeclass(size_t sz)
  10997. {
  10998. int z = stb_log2_floor(sz); // -1 below to group e.g. 13,14,15,16 correctly
  10999. return stb__class_base[z] + ((sz-1) >> stb__class_shift[z]);
  11000. }
  11001. static void stb__init_sizeclass(void)
  11002. {
  11003. int i, size, overhead;
  11004. int align_shift = 2; // allow 4-byte and 12-byte blocks as well, vs. TCMalloc
  11005. int next_class = 1;
  11006. int last_log = 0;
  11007. for (i = 0; i < align_shift; i++) {
  11008. stb__class_base [i] = next_class;
  11009. stb__class_shift[i] = align_shift;
  11010. }
  11011. for (size = 1 << align_shift; size <= STB__MAX_SMALL_SIZE; size += 1 << align_shift) {
  11012. i = stb_log2_floor(size);
  11013. if (i > last_log) {
  11014. if (size == 16) ++align_shift; // switch from 4-byte to 8-byte alignment
  11015. else if (size >= 128 && align_shift < 8) ++align_shift;
  11016. stb__class_base[i] = next_class - ((size-1) >> align_shift);
  11017. stb__class_shift[i] = align_shift;
  11018. last_log = i;
  11019. }
  11020. stb__size_for_class[next_class++] = size;
  11021. }
  11022. for (i=1; i <= STB__MAX_SMALL_SIZE; ++i)
  11023. assert(i <= stb__size_for_class[stb__sizeclass(i)]);
  11024. overhead = 0;
  11025. for (i = 1; i < next_class; i++) {
  11026. int s = stb__size_for_class[i];
  11027. size = stb__page_size;
  11028. while (size % s > size >> 3)
  11029. size += stb__page_size;
  11030. stb__pages_for_class[i] = (unsigned char) (size >> stb__page_shift);
  11031. overhead += size;
  11032. }
  11033. assert(overhead < (4 << 20)); // make sure it's under 4MB of overhead
  11034. }
  11035. #ifdef STB_DEBUG
  11036. #define stb__smemset(a,b,c) memset((void *) a, b, c)
  11037. #elif defined(STB_FASTMALLOC_INIT)
  11038. #define stb__smemset(a,b,c) memset((void *) a, b, c)
  11039. #else
  11040. #define stb__smemset(a,b,c)
  11041. #endif
  11042. void *stb_smalloc(size_t sz)
  11043. {
  11044. stb__span *s;
  11045. if (sz == 0) return NULL;
  11046. if (stb__size_for_class[1] == 0) stb__init_sizeclass();
  11047. if (sz > STB__MAX_SMALL_SIZE) {
  11048. s = stb__alloc_span((sz + stb__page_size - 1) >> stb__page_shift);
  11049. if (s == NULL) return NULL;
  11050. s->list = 0;
  11051. s->next = s->prev = NULL;
  11052. s->allocations = -32767;
  11053. stb__smemset(stb__page_address(s->start), 0xcd, (sz+3)&~3);
  11054. return (void *) stb__page_address(s->start);
  11055. } else {
  11056. void *p;
  11057. int c = stb__sizeclass(sz);
  11058. s = stb__spanlist[256+c];
  11059. if (!s || !s->first_free)
  11060. s = stb__get_nonempty_sizeclass(c);
  11061. if (s == NULL) return NULL;
  11062. p = s->first_free;
  11063. s->first_free = * (void **) p;
  11064. ++s->allocations;
  11065. stb__smemset(p,0xcd, sz);
  11066. return p;
  11067. }
  11068. }
  11069. int stb_ssize(void *p)
  11070. {
  11071. stb__span *s;
  11072. if (p == NULL) return 0;
  11073. s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];
  11074. if (s->list >= 256) {
  11075. return stb__size_for_class[s->list - 256];
  11076. } else {
  11077. assert(s->list == 0);
  11078. return s->len << stb__page_shift;
  11079. }
  11080. }
  11081. void stb_sfree(void *p)
  11082. {
  11083. stb__span *s;
  11084. if (p == NULL) return;
  11085. s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];
  11086. if (s->list >= 256) {
  11087. stb__smemset(p, 0xfe, stb__size_for_class[s->list-256]);
  11088. * (void **) p = s->first_free;
  11089. s->first_free = p;
  11090. if (--s->allocations == 0) {
  11091. stb__spanlist_unlink(s);
  11092. stb__free_span(s);
  11093. }
  11094. } else {
  11095. assert(s->list == 0);
  11096. stb__smemset(p, 0xfe, stb_ssize(p));
  11097. stb__free_span(s);
  11098. }
  11099. }
  11100. void *stb_srealloc(void *p, size_t sz)
  11101. {
  11102. size_t cur_size;
  11103. if (p == NULL) return stb_smalloc(sz);
  11104. if (sz == 0) { stb_sfree(p); return NULL; }
  11105. cur_size = stb_ssize(p);
  11106. if (sz > cur_size || sz <= (cur_size >> 1)) {
  11107. void *q;
  11108. if (sz > cur_size && sz < (cur_size << 1)) sz = cur_size << 1;
  11109. q = stb_smalloc(sz); if (q == NULL) return NULL;
  11110. memcpy(q, p, sz < cur_size ? sz : cur_size);
  11111. stb_sfree(p);
  11112. return q;
  11113. }
  11114. return p;
  11115. }
  11116. void *stb_scalloc(size_t n, size_t sz)
  11117. {
  11118. void *p;
  11119. if (n == 0 || sz == 0) return NULL;
  11120. if (stb_log2_ceil(n) + stb_log2_ceil(n) >= 32) return NULL;
  11121. p = stb_smalloc(n*sz);
  11122. if (p) memset(p, 0, n*sz);
  11123. return p;
  11124. }
  11125. char *stb_sstrdup(char *s)
  11126. {
  11127. int n = strlen(s);
  11128. char *p = (char *) stb_smalloc(n+1);
  11129. if (p) strcpy(p,s);
  11130. return p;
  11131. }
  11132. #endif // STB_DEFINE
  11133. //////////////////////////////////////////////////////////////////////////////
  11134. //
  11135. // Source code constants
  11136. //
  11137. // This is a trivial system to let you specify constants in source code,
  11138. // then while running you can change the constants.
  11139. //
  11140. // Note that you can't wrap the #defines, because we need to know their
  11141. // names. So we provide a pre-wrapped version without 'STB_' for convenience;
  11142. // to request it, #define STB_CONVENIENT_H, yielding:
  11143. // KI -- integer
  11144. // KU -- unsigned integer
  11145. // KF -- float
  11146. // KD -- double
  11147. // KS -- string constant
  11148. //
  11149. // Defaults to functioning in debug build, not in release builds.
  11150. // To force on, define STB_ALWAYS_H
  11151. #ifdef STB_CONVENIENT_H
  11152. #define KI(x) STB_I(x)
  11153. #define KU(x) STB_UI(x)
  11154. #define KF(x) STB_F(x)
  11155. #define KD(x) STB_D(x)
  11156. #define KS(x) STB_S(x)
  11157. #endif
  11158. STB_EXTERN void stb_source_path(char *str);
  11159. #ifdef STB_DEFINE
  11160. char *stb__source_path;
  11161. void stb_source_path(char *path)
  11162. {
  11163. stb__source_path = path;
  11164. }
  11165. char *stb__get_sourcefile_path(char *file)
  11166. {
  11167. static char filebuf[512];
  11168. if (stb__source_path) {
  11169. sprintf(filebuf, "%s/%s", stb__source_path, file);
  11170. if (stb_fexists(filebuf)) return filebuf;
  11171. }
  11172. if (stb_fexists(file)) return file;
  11173. sprintf(filebuf, "../%s", file);
  11174. if (!stb_fexists(filebuf)) return filebuf;
  11175. return file;
  11176. }
  11177. #endif
  11178. #define STB_F(x) ((float) STB_H(x))
  11179. #define STB_UI(x) ((unsigned int) STB_I(x))
  11180. #if !defined(STB_DEBUG) && !defined(STB_ALWAYS_H)
  11181. #define STB_D(x) ((double) (x))
  11182. #define STB_I(x) ((int) (x))
  11183. #define STB_S(x) ((char *) (x))
  11184. #else
  11185. #define STB_D(x) stb__double_constant(__FILE__, __LINE__-1, (x))
  11186. #define STB_I(x) stb__int_constant(__FILE__, __LINE__-1, (x))
  11187. #define STB_S(x) stb__string_constant(__FILE__, __LINE__-1, (x))
  11188. STB_EXTERN double stb__double_constant(char *file, int line, double x);
  11189. STB_EXTERN int stb__int_constant(char *file, int line, int x);
  11190. STB_EXTERN char * stb__string_constant(char *file, int line, char *str);
  11191. #ifdef STB_DEFINE
  11192. enum
  11193. {
  11194. STB__CTYPE_int,
  11195. STB__CTYPE_uint,
  11196. STB__CTYPE_float,
  11197. STB__CTYPE_double,
  11198. STB__CTYPE_string,
  11199. };
  11200. typedef struct
  11201. {
  11202. int line;
  11203. int type;
  11204. union {
  11205. int ival;
  11206. double dval;
  11207. char *sval;
  11208. };
  11209. } stb__Entry;
  11210. typedef struct
  11211. {
  11212. stb__Entry *entries;
  11213. char *filename;
  11214. time_t timestamp;
  11215. char **file_data;
  11216. int file_len;
  11217. unsigned short *line_index;
  11218. } stb__FileEntry;
  11219. static void stb__constant_parse(stb__FileEntry *f, int i)
  11220. {
  11221. char *s;
  11222. int n;
  11223. if (!stb_arr_valid(f->entries, i)) return;
  11224. n = f->entries[i].line;
  11225. if (n >= f->file_len) return;
  11226. s = f->file_data[n];
  11227. switch (f->entries[i].type) {
  11228. case STB__CTYPE_float:
  11229. while (*s) {
  11230. if (!strncmp(s, "STB_D(", 6)) { s+=6; goto matched_float; }
  11231. if (!strncmp(s, "STB_F(", 6)) { s+=6; goto matched_float; }
  11232. if (!strncmp(s, "KD(", 3)) { s+=3; goto matched_float; }
  11233. if (!strncmp(s, "KF(", 3)) { s+=3; goto matched_float; }
  11234. ++s;
  11235. }
  11236. break;
  11237. matched_float:
  11238. f->entries[i].dval = strtod(s, NULL);
  11239. break;
  11240. case STB__CTYPE_int:
  11241. while (*s) {
  11242. if (!strncmp(s, "STB_I(", 6)) { s+=6; goto matched_int; }
  11243. if (!strncmp(s, "STB_UI(", 7)) { s+=7; goto matched_int; }
  11244. if (!strncmp(s, "KI(", 3)) { s+=3; goto matched_int; }
  11245. if (!strncmp(s, "KU(", 3)) { s+=3; goto matched_int; }
  11246. ++s;
  11247. }
  11248. break;
  11249. matched_int: {
  11250. int neg=0;
  11251. s = stb_skipwhite(s);
  11252. while (*s == '-') { neg = !neg; s = stb_skipwhite(s+1); } // handle '- - 5', pointlessly
  11253. if (s[0] == '0' && tolower(s[1]) == 'x')
  11254. f->entries[i].ival = strtol(s, NULL, 16);
  11255. else if (s[0] == '0')
  11256. f->entries[i].ival = strtol(s, NULL, 8);
  11257. else
  11258. f->entries[i].ival = strtol(s, NULL, 10);
  11259. if (neg) f->entries[i].ival = -f->entries[i].ival;
  11260. break;
  11261. }
  11262. case STB__CTYPE_string:
  11263. // @TODO
  11264. break;
  11265. }
  11266. }
  11267. static stb_sdict *stb__constant_file_hash;
  11268. stb__Entry *stb__constant_get_entry(char *filename, int line, int type)
  11269. {
  11270. int i;
  11271. stb__FileEntry *f;
  11272. if (stb__constant_file_hash == NULL)
  11273. stb__constant_file_hash = stb_sdict_new(STB_TRUE);
  11274. f = (stb__FileEntry*) stb_sdict_get(stb__constant_file_hash, filename);
  11275. if (f == NULL) {
  11276. char *s = stb__get_sourcefile_path(filename);
  11277. if (s == NULL || !stb_fexists(s)) return 0;
  11278. f = (stb__FileEntry *) malloc(sizeof(*f));
  11279. f->timestamp = stb_ftimestamp(s);
  11280. f->file_data = stb_stringfile(s, &f->file_len);
  11281. f->filename = strdup(s); // cache the full path
  11282. f->entries = NULL;
  11283. f->line_index = 0;
  11284. stb_arr_setlen(f->line_index, f->file_len);
  11285. memset(f->line_index, 0xff, stb_arr_storage(f->line_index));
  11286. } else {
  11287. time_t t = stb_ftimestamp(f->filename);
  11288. if (f->timestamp != t) {
  11289. f->timestamp = t;
  11290. free(f->file_data);
  11291. f->file_data = stb_stringfile(f->filename, &f->file_len);
  11292. stb_arr_setlen(f->line_index, f->file_len);
  11293. for (i=0; i < stb_arr_len(f->entries); ++i)
  11294. stb__constant_parse(f, i);
  11295. }
  11296. }
  11297. if (line >= f->file_len) return 0;
  11298. if (f->line_index[line] >= stb_arr_len(f->entries)) {
  11299. // need a new entry
  11300. int n = stb_arr_len(f->entries);
  11301. stb__Entry e;
  11302. e.line = line;
  11303. if (line < f->file_len)
  11304. f->line_index[line] = n;
  11305. e.type = type;
  11306. stb_arr_push(f->entries, e);
  11307. stb__constant_parse(f, n);
  11308. }
  11309. return f->entries + f->line_index[line];
  11310. }
  11311. double stb__double_constant(char *file, int line, double x)
  11312. {
  11313. stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_float);
  11314. if (!e) return x;
  11315. return e->dval;
  11316. }
  11317. int stb__int_constant(char *file, int line, int x)
  11318. {
  11319. stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_int);
  11320. if (!e) return x;
  11321. return e->ival;
  11322. }
  11323. char * stb__string_constant(char *file, int line, char *x)
  11324. {
  11325. stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_string);
  11326. if (!e) return x;
  11327. return e->sval;
  11328. }
  11329. #endif // STB_DEFINE
  11330. #endif // !STB_DEBUG && !STB_ALWAYS_H
  11331. #ifdef STB_STUA
  11332. //////////////////////////////////////////////////////////////////////////
  11333. //
  11334. // stua: little scripting language
  11335. //
  11336. // define STB_STUA to compile it
  11337. //
  11338. // see http://nothings.org/stb/stb_stua.html for documentation
  11339. //
  11340. // basic parsing model:
  11341. //
  11342. // lexical analysis
  11343. // use stb_lex() to parse tokens; keywords get their own tokens
  11344. //
  11345. // parsing:
  11346. // recursive descent parser. too much of a hassle to make an unambiguous
  11347. // LR(1) grammar, and one-pass generation is clumsier (recursive descent
  11348. // makes it easier to e.g. compile nested functions). on the other hand,
  11349. // dictionary syntax required hackery to get extra lookahead.
  11350. //
  11351. // codegen:
  11352. // output into an evaluation tree, using array indices as 'pointers'
  11353. //
  11354. // run:
  11355. // traverse the tree; support for 'break/continue/return' is tricky
  11356. //
  11357. // garbage collection:
  11358. // stu__mark and sweep; explicit stack with non-stu__compile_global_scope roots
  11359. typedef stb_int32 stua_obj;
  11360. typedef stb_idict stua_dict;
  11361. STB_EXTERN void stua_run_script(char *s);
  11362. STB_EXTERN void stua_uninit(void);
  11363. extern stua_obj stua_globals;
  11364. STB_EXTERN double stua_number(stua_obj z);
  11365. STB_EXTERN stua_obj stua_getnil(void);
  11366. STB_EXTERN stua_obj stua_getfalse(void);
  11367. STB_EXTERN stua_obj stua_gettrue(void);
  11368. STB_EXTERN stua_obj stua_string(char *z);
  11369. STB_EXTERN stua_obj stua_make_number(double d);
  11370. STB_EXTERN stua_obj stua_box(int type, void *data, int size);
  11371. enum
  11372. {
  11373. STUA_op_negate=129,
  11374. STUA_op_shl, STUA_op_ge,
  11375. STUA_op_shr, STUA_op_le,
  11376. STUA_op_shru,
  11377. STUA_op_last
  11378. };
  11379. #define STUA_NO_VALUE 2 // equivalent to a tagged NULL
  11380. STB_EXTERN stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c);
  11381. STB_EXTERN stua_obj stua_error(char *err, ...);
  11382. STB_EXTERN stua_obj stua_pushroot(stua_obj o);
  11383. STB_EXTERN void stua_poproot ( void );
  11384. #ifdef STB_DEFINE
  11385. // INTERPRETER
  11386. // 31-bit floating point implementation
  11387. // force the (1 << 30) bit (2nd highest bit) to be zero by re-biasing the exponent;
  11388. // then shift and set the bottom bit
  11389. static stua_obj stu__floatp(float *f)
  11390. {
  11391. unsigned int n = *(unsigned int *) f;
  11392. unsigned int e = n & (0xff << 23);
  11393. assert(sizeof(int) == 4 && sizeof(float) == 4);
  11394. if (!e) // zero?
  11395. n = n; // no change
  11396. else if (e < (64 << 23)) // underflow of the packed encoding?
  11397. n = (n & 0x80000000); // signed 0
  11398. else if (e > (190 << 23)) // overflow of the encoding? (or INF or NAN)
  11399. n = (n & 0x80000000) + (127 << 23); // new INF encoding
  11400. else
  11401. n -= 0x20000000;
  11402. // now we need to shuffle the bits so that the spare bit is at the bottom
  11403. assert((n & 0x40000000) == 0);
  11404. return (n & 0x80000000) + (n << 1) + 1;
  11405. }
  11406. static unsigned char stu__getfloat_addend[256];
  11407. static float stu__getfloat(stua_obj v)
  11408. {
  11409. unsigned int n;
  11410. unsigned int e = ((unsigned int) v) >> 24;
  11411. n = (int) v >> 1; // preserve high bit
  11412. n += stu__getfloat_addend[e] << 24;
  11413. return *(float *) &n;
  11414. }
  11415. stua_obj stua_float(float f)
  11416. {
  11417. return stu__floatp(&f);
  11418. }
  11419. static void stu__float_init(void)
  11420. {
  11421. int i;
  11422. stu__getfloat_addend[0] = 0; // do nothing to biased exponent of 0
  11423. for (i=1; i < 127; ++i)
  11424. stu__getfloat_addend[i] = 32; // undo the -0x20000000
  11425. stu__getfloat_addend[127] = 64; // convert packed INF to INF (0x3f -> 0x7f)
  11426. for (i=0; i < 128; ++i) // for signed floats, remove the bit we just shifted down
  11427. stu__getfloat_addend[128+i] = stu__getfloat_addend[i] - 64;
  11428. }
  11429. // Tagged data type implementation
  11430. // TAGS:
  11431. #define stu__int_tag 0 // of 2 bits // 00 int
  11432. #define stu__float_tag 1 // of 1 bit // 01 float
  11433. #define stu__ptr_tag 2 // of 2 bits // 10 boxed
  11434. // 11 float
  11435. #define stu__tag(x) ((x) & 3)
  11436. #define stu__number(x) (stu__tag(x) != stu__ptr_tag)
  11437. #define stu__isint(x) (stu__tag(x) == stu__int_tag)
  11438. #define stu__int(x) ((x) >> 2)
  11439. #define stu__float(x) (stu__getfloat(x))
  11440. #define stu__makeint(v) ((v)*4+stu__int_tag)
  11441. // boxed data, and tag support for boxed data
  11442. enum
  11443. {
  11444. STU___float = 1, STU___int = 2,
  11445. STU___number = 3, STU___string = 4,
  11446. STU___function = 5, STU___dict = 6,
  11447. STU___boolean = 7, STU___error = 8,
  11448. };
  11449. // boxed data
  11450. #define STU__BOX short type, stua_gc
  11451. typedef struct stu__box { STU__BOX; } stu__box;
  11452. stu__box stu__nil = { 0, 1 };
  11453. stu__box stu__true = { STU___boolean, 1, };
  11454. stu__box stu__false = { STU___boolean, 1, };
  11455. #define stu__makeptr(v) ((stua_obj) (v) + stu__ptr_tag)
  11456. #define stua_nil stu__makeptr(&stu__nil)
  11457. #define stua_true stu__makeptr(&stu__true)
  11458. #define stua_false stu__makeptr(&stu__false)
  11459. stua_obj stua_getnil(void) { return stua_nil; }
  11460. stua_obj stua_getfalse(void) { return stua_false; }
  11461. stua_obj stua_gettrue(void) { return stua_true; }
  11462. #define stu__ptr(x) ((stu__box *) ((x) - stu__ptr_tag))
  11463. #define stu__checkt(t,x) ((t) == STU___float ? ((x) & 1) == stu__float_tag : \
  11464. (t) == STU___int ? stu__isint(x) : \
  11465. (t) == STU___number ? stu__number(x) : \
  11466. stu__tag(x) == stu__ptr_tag && stu__ptr(x)->type == (t))
  11467. typedef struct
  11468. {
  11469. STU__BOX;
  11470. void *ptr;
  11471. } stu__wrapper;
  11472. // implementation of a 'function' or function + closure
  11473. typedef struct stu__func
  11474. {
  11475. STU__BOX;
  11476. stua_obj closure_source; // 0 - regular function; 4 - C function
  11477. // if closure, pointer to source function
  11478. union {
  11479. stua_obj closure_data; // partial-application data
  11480. void *store; // pointer to free that holds 'code'
  11481. stua_obj (*func)(stua_dict *context);
  11482. } f;
  11483. // closure ends here
  11484. short *code;
  11485. int num_param;
  11486. stua_obj *param; // list of parameter strings
  11487. } stu__func;
  11488. // apply this to 'short *code' to get at data
  11489. #define stu__const(f) ((stua_obj *) (f))
  11490. static void stu__free_func(stu__func *f)
  11491. {
  11492. if (f->closure_source == 0) free(f->f.store);
  11493. if ((stb_uint) f->closure_source <= 4) free(f->param);
  11494. free(f);
  11495. }
  11496. #define stu__pd(x) ((stua_dict *) stu__ptr(x))
  11497. #define stu__pw(x) ((stu__wrapper *) stu__ptr(x))
  11498. #define stu__pf(x) ((stu__func *) stu__ptr(x))
  11499. // garbage-collection
  11500. static stu__box ** stu__gc_ptrlist;
  11501. static stua_obj * stu__gc_root_stack;
  11502. stua_obj stua_pushroot(stua_obj o) { stb_arr_push(stu__gc_root_stack, o); return o; }
  11503. void stua_poproot ( void ) { stb_arr_pop(stu__gc_root_stack); }
  11504. static stb_sdict *stu__strings;
  11505. static void stu__mark(stua_obj z)
  11506. {
  11507. int i;
  11508. stu__box *p = stu__ptr(z);
  11509. if (p->stua_gc == 1) return; // already marked
  11510. assert(p->stua_gc == 0);
  11511. p->stua_gc = 1;
  11512. switch(p->type) {
  11513. case STU___function: {
  11514. stu__func *f = (stu__func *) p;
  11515. if ((stb_uint) f->closure_source <= 4) {
  11516. if (f->closure_source == 0) {
  11517. for (i=1; i <= f->code[0]; ++i)
  11518. if (!stu__number(((stua_obj *) f->code)[-i]))
  11519. stu__mark(((stua_obj *) f->code)[-i]);
  11520. }
  11521. for (i=0; i < f->num_param; ++i)
  11522. stu__mark(f->param[i]);
  11523. } else {
  11524. stu__mark(f->closure_source);
  11525. stu__mark(f->f.closure_data);
  11526. }
  11527. break;
  11528. }
  11529. case STU___dict: {
  11530. stua_dict *e = (stua_dict *) p;
  11531. for (i=0; i < e->limit; ++i)
  11532. if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL) {
  11533. if (!stu__number(e->table[i].k)) stu__mark((int) e->table[i].k);
  11534. if (!stu__number(e->table[i].v)) stu__mark((int) e->table[i].v);
  11535. }
  11536. break;
  11537. }
  11538. }
  11539. }
  11540. static int stu__num_allocs, stu__size_allocs;
  11541. static stua_obj stu__flow_val = stua_nil; // used for break & return
  11542. static void stua_gc(int force)
  11543. {
  11544. int i;
  11545. if (!force && stu__num_allocs == 0 && stu__size_allocs == 0) return;
  11546. stu__num_allocs = stu__size_allocs = 0;
  11547. //printf("[gc]\n");
  11548. // clear marks
  11549. for (i=0; i < stb_arr_len(stu__gc_ptrlist); ++i)
  11550. stu__gc_ptrlist[i]->stua_gc = 0;
  11551. // stu__mark everything reachable
  11552. stu__nil.stua_gc = stu__true.stua_gc = stu__false.stua_gc = 1;
  11553. stu__mark(stua_globals);
  11554. if (!stu__number(stu__flow_val))
  11555. stu__mark(stu__flow_val);
  11556. for (i=0; i < stb_arr_len(stu__gc_root_stack); ++i)
  11557. if (!stu__number(stu__gc_root_stack[i]))
  11558. stu__mark(stu__gc_root_stack[i]);
  11559. // sweep unreachables
  11560. for (i=0; i < stb_arr_len(stu__gc_ptrlist);) {
  11561. stu__box *z = stu__gc_ptrlist[i];
  11562. if (!z->stua_gc) {
  11563. switch (z->type) {
  11564. case STU___dict: stb_idict_destroy((stua_dict *) z); break;
  11565. case STU___error: free(((stu__wrapper *) z)->ptr); break;
  11566. case STU___string: stb_sdict_remove(stu__strings, (char*) ((stu__wrapper *) z)->ptr, NULL); free(z); break;
  11567. case STU___function: stu__free_func((stu__func *) z); break;
  11568. }
  11569. // swap in the last item over this, and repeat
  11570. z = stb_arr_pop(stu__gc_ptrlist);
  11571. stu__gc_ptrlist[i] = z;
  11572. } else
  11573. ++i;
  11574. }
  11575. }
  11576. static void stu__consider_gc(stua_obj x)
  11577. {
  11578. if (stu__size_allocs < 100000) return;
  11579. if (stu__num_allocs < 10 && stu__size_allocs < 1000000) return;
  11580. stb_arr_push(stu__gc_root_stack, x);
  11581. stua_gc(0);
  11582. stb_arr_pop(stu__gc_root_stack);
  11583. }
  11584. static stua_obj stu__makeobj(int type, void *data, int size, int safe_to_gc)
  11585. {
  11586. stua_obj x = stu__makeptr(data);
  11587. ((stu__box *) data)->type = type;
  11588. stb_arr_push(stu__gc_ptrlist, (stu__box *) data);
  11589. stu__num_allocs += 1;
  11590. stu__size_allocs += size;
  11591. if (safe_to_gc) stu__consider_gc(x);
  11592. return x;
  11593. }
  11594. stua_obj stua_box(int type, void *data, int size)
  11595. {
  11596. stu__wrapper *p = (stu__wrapper *) malloc(sizeof(*p));
  11597. p->ptr = data;
  11598. return stu__makeobj(type, p, size, 0);
  11599. }
  11600. // a stu string can be directly compared for equality, because
  11601. // they go into a hash table
  11602. stua_obj stua_string(char *z)
  11603. {
  11604. stu__wrapper *b = (stu__wrapper *) stb_sdict_get(stu__strings, z);
  11605. if (b == NULL) {
  11606. int o = stua_box(STU___string, NULL, strlen(z) + sizeof(*b));
  11607. b = stu__pw(o);
  11608. stb_sdict_add(stu__strings, z, b);
  11609. stb_sdict_getkey(stu__strings, z, (char **) &b->ptr);
  11610. }
  11611. return stu__makeptr(b);
  11612. }
  11613. // stb_obj dictionary is just an stb_idict
  11614. static void stu__set(stua_dict *d, stua_obj k, stua_obj v)
  11615. { if (stb_idict_set(d, k, v)) stu__size_allocs += 8; }
  11616. static stua_obj stu__get(stua_dict *d, stua_obj k, stua_obj res)
  11617. {
  11618. stb_idict_get_flag(d, k, &res);
  11619. return res;
  11620. }
  11621. static stua_obj make_string(char *z, int len)
  11622. {
  11623. stua_obj s;
  11624. char temp[256], *q = (char *) stb_temp(temp, len+1), *p = q;
  11625. while (len > 0) {
  11626. if (*z == '\\') {
  11627. if (z[1] == 'n') *p = '\n';
  11628. else if (z[1] == 'r') *p = '\r';
  11629. else if (z[1] == 't') *p = '\t';
  11630. else *p = z[1];
  11631. p += 1; z += 2; len -= 2;
  11632. } else {
  11633. *p++ = *z++; len -= 1;
  11634. }
  11635. }
  11636. *p = 0;
  11637. s = stua_string(q);
  11638. stb_tempfree(temp, q);
  11639. return s;
  11640. }
  11641. enum token_names
  11642. {
  11643. T__none=128,
  11644. ST_shl = STUA_op_shl, ST_ge = STUA_op_ge,
  11645. ST_shr = STUA_op_shr, ST_le = STUA_op_le,
  11646. ST_shru = STUA_op_shru, STU__negate = STUA_op_negate,
  11647. ST__reset_numbering = STUA_op_last,
  11648. ST_white,
  11649. ST_id, ST_float, ST_decimal, ST_hex, ST_char,ST_string, ST_number,
  11650. // make sure the keywords come _AFTER_ ST_id, so stb_lex prefer them
  11651. ST_if, ST_while, ST_for, ST_eq, ST_nil,
  11652. ST_then, ST_do, ST_in, ST_ne, ST_true,
  11653. ST_else, ST_break, ST_let, ST_and, ST_false,
  11654. ST_elseif, ST_continue, ST_into, ST_or, ST_repeat,
  11655. ST_end, ST_as, ST_return, ST_var, ST_func,
  11656. ST_catch, ST__frame,
  11657. ST__max_terminals,
  11658. STU__defaultparm, STU__seq,
  11659. };
  11660. static stua_dict * stu__globaldict;
  11661. stua_obj stua_globals;
  11662. static enum
  11663. {
  11664. FLOW_normal, FLOW_continue, FLOW_break, FLOW_return, FLOW_error,
  11665. } stu__flow;
  11666. stua_obj stua_error(char *z, ...)
  11667. {
  11668. stua_obj a;
  11669. char temp[4096], *x;
  11670. va_list v; va_start(v,z); vsprintf(temp, z, v); va_end(v);
  11671. x = strdup(temp);
  11672. a = stua_box(STU___error, x, strlen(x));
  11673. stu__flow = FLOW_error;
  11674. stu__flow_val = a;
  11675. return stua_nil;
  11676. }
  11677. double stua_number(stua_obj z)
  11678. {
  11679. return stu__tag(z) == stu__int_tag ? stu__int(z) : stu__float(z);
  11680. }
  11681. stua_obj stua_make_number(double d)
  11682. {
  11683. double e = floor(d);
  11684. if (e == d && e < (1 << 29) && e >= -(1 << 29))
  11685. return stu__makeint((int) e);
  11686. else
  11687. return stua_float((float) d);
  11688. }
  11689. stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c) = NULL;
  11690. static stua_obj stu__op(int op, stua_obj a, stua_obj b, stua_obj c)
  11691. {
  11692. stua_obj r = STUA_NO_VALUE;
  11693. if (op == '+') {
  11694. if (stu__checkt(STU___string, a) && stu__checkt(STU___string, b)) {
  11695. ;// @TODO: string concatenation
  11696. } else if (stu__checkt(STU___function, a) && stu__checkt(STU___dict, b)) {
  11697. stu__func *f = (stu__func *) malloc(12);
  11698. assert(offsetof(stu__func, code)==12);
  11699. f->closure_source = a;
  11700. f->f.closure_data = b;
  11701. return stu__makeobj(STU___function, f, 16, 1);
  11702. }
  11703. }
  11704. if (stua_overload) r = stua_overload(op,a,b,c);
  11705. if (stu__flow != FLOW_error && r == STUA_NO_VALUE)
  11706. stua_error("Typecheck for operator %d", op), r=stua_nil;
  11707. return r;
  11708. }
  11709. #define STU__EVAL2(a,b) \
  11710. a = stu__eval(stu__f[n+1]); if (stu__flow) break; stua_pushroot(a); \
  11711. b = stu__eval(stu__f[n+2]); stua_poproot(); if (stu__flow) break;
  11712. #define STU__FB(op) \
  11713. STU__EVAL2(a,b) \
  11714. if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \
  11715. return ((a) op (b)); \
  11716. if (stu__number(a) && stu__number(b)) \
  11717. return stua_make_number(stua_number(a) op stua_number(b)); \
  11718. return stu__op(stu__f[n], a,b, stua_nil)
  11719. #define STU__F(op) \
  11720. STU__EVAL2(a,b) \
  11721. if (stu__number(a) && stu__number(b)) \
  11722. return stua_make_number(stua_number(a) op stua_number(b)); \
  11723. return stu__op(stu__f[n], a,b, stua_nil)
  11724. #define STU__I(op) \
  11725. STU__EVAL2(a,b) \
  11726. if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \
  11727. return stu__makeint(stu__int(a) op stu__int(b)); \
  11728. return stu__op(stu__f[n], a,b, stua_nil)
  11729. #define STU__C(op) \
  11730. STU__EVAL2(a,b) \
  11731. if (stu__number(a) && stu__number(b)) \
  11732. return (stua_number(a) op stua_number(b)) ? stua_true : stua_false; \
  11733. return stu__op(stu__f[n], a,b, stua_nil)
  11734. #define STU__CE(op) \
  11735. STU__EVAL2(a,b) \
  11736. return (a op b) ? stua_true : stua_false
  11737. static short *stu__f;
  11738. static stua_obj stu__f_obj;
  11739. static stua_dict *stu__c;
  11740. static stua_obj stu__funceval(stua_obj fo, stua_obj co);
  11741. static int stu__cond(stua_obj x)
  11742. {
  11743. if (stu__flow) return 0;
  11744. if (!stu__checkt(STU___boolean, x))
  11745. x = stu__op('!', x, stua_nil, stua_nil);
  11746. if (x == stua_true ) return 1;
  11747. if (x == stua_false) return 0;
  11748. stu__flow = FLOW_error;
  11749. return 0;
  11750. }
  11751. // had to manually eliminate tailcall recursion for debugging complex stuff
  11752. #define TAILCALL(x) n = (x); goto top;
  11753. static stua_obj stu__eval(int n)
  11754. {
  11755. top:
  11756. if (stu__flow >= FLOW_return) return stua_nil; // is this needed?
  11757. if (n < 0) return stu__const(stu__f)[n];
  11758. assert(n != 0 && n != 1);
  11759. switch (stu__f[n]) {
  11760. stua_obj a,b,c;
  11761. case ST_catch: a = stu__eval(stu__f[n+1]);
  11762. if (stu__flow == FLOW_error) { a=stu__flow_val; stu__flow = FLOW_normal; }
  11763. return a;
  11764. case ST_var: b = stu__eval(stu__f[n+2]); if (stu__flow) break;
  11765. stu__set(stu__c, stu__const(stu__f)[stu__f[n+1]], b);
  11766. return b;
  11767. case STU__seq: stu__eval(stu__f[n+1]); if (stu__flow) break;
  11768. TAILCALL(stu__f[n+2]);
  11769. case ST_if: if (!stu__cond(stu__eval(stu__f[n+1]))) return stua_nil;
  11770. TAILCALL(stu__f[n+2]);
  11771. case ST_else: a = stu__cond(stu__eval(stu__f[n+1]));
  11772. TAILCALL(stu__f[n + 2 + !a]);
  11773. #define STU__HANDLE_BREAK \
  11774. if (stu__flow >= FLOW_break) { \
  11775. if (stu__flow == FLOW_break) { \
  11776. a = stu__flow_val; \
  11777. stu__flow = FLOW_normal; \
  11778. stu__flow_val = stua_nil; \
  11779. return a; \
  11780. } \
  11781. return stua_nil; \
  11782. }
  11783. case ST_as: stu__eval(stu__f[n+3]);
  11784. STU__HANDLE_BREAK
  11785. // fallthrough!
  11786. case ST_while: a = stua_nil; stua_pushroot(a);
  11787. while (stu__cond(stu__eval(stu__f[n+1]))) {
  11788. stua_poproot();
  11789. a = stu__eval(stu__f[n+2]);
  11790. STU__HANDLE_BREAK
  11791. stu__flow = FLOW_normal; // clear 'continue' flag
  11792. stua_pushroot(a);
  11793. if (stu__f[n+3]) stu__eval(stu__f[n+3]);
  11794. STU__HANDLE_BREAK
  11795. stu__flow = FLOW_normal; // clear 'continue' flag
  11796. }
  11797. stua_poproot();
  11798. return a;
  11799. case ST_break: stu__flow = FLOW_break; stu__flow_val = stu__eval(stu__f[n+1]); break;
  11800. case ST_continue:stu__flow = FLOW_continue; break;
  11801. case ST_return: stu__flow = FLOW_return; stu__flow_val = stu__eval(stu__f[n+1]); break;
  11802. case ST__frame: return stu__f_obj;
  11803. case '[': STU__EVAL2(a,b);
  11804. if (stu__checkt(STU___dict, a))
  11805. return stu__get(stu__pd(a), b, stua_nil);
  11806. return stu__op(stu__f[n], a, b, stua_nil);
  11807. case '=': a = stu__eval(stu__f[n+2]); if (stu__flow) break;
  11808. n = stu__f[n+1];
  11809. if (stu__f[n] == ST_id) {
  11810. if (!stb_idict_update(stu__c, stu__const(stu__f)[stu__f[n+1]], a))
  11811. if (!stb_idict_update(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], a))
  11812. return stua_error("Assignment to undefined variable");
  11813. } else if (stu__f[n] == '[') {
  11814. stua_pushroot(a);
  11815. b = stu__eval(stu__f[n+1]); if (stu__flow) { stua_poproot(); break; }
  11816. stua_pushroot(b);
  11817. c = stu__eval(stu__f[n+2]); stua_poproot(); stua_poproot();
  11818. if (stu__flow) break;
  11819. if (!stu__checkt(STU___dict, b)) return stua_nil;
  11820. stu__set(stu__pd(b), c, a);
  11821. } else {
  11822. return stu__op(stu__f[n], stu__eval(n), a, stua_nil);
  11823. }
  11824. return a;
  11825. case STU__defaultparm:
  11826. a = stu__eval(stu__f[n+2]);
  11827. stu__flow = FLOW_normal;
  11828. if (stb_idict_add(stu__c, stu__const(stu__f)[stu__f[n+1]], a))
  11829. stu__size_allocs += 8;
  11830. return stua_nil;
  11831. case ST_id: a = stu__get(stu__c, stu__const(stu__f)[stu__f[n+1]], STUA_NO_VALUE); // try local variable
  11832. return a != STUA_NO_VALUE // else try stu__compile_global_scope variable
  11833. ? a : stu__get(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], stua_nil);
  11834. case STU__negate:a = stu__eval(stu__f[n+1]); if (stu__flow) break;
  11835. return stu__isint(a) ? -a : stu__op(stu__f[n], a, stua_nil, stua_nil);
  11836. case '~': a = stu__eval(stu__f[n+1]); if (stu__flow) break;
  11837. return stu__isint(a) ? (~a)&~3 : stu__op(stu__f[n], a, stua_nil, stua_nil);
  11838. case '!': a = stu__eval(stu__f[n+1]); if (stu__flow) break;
  11839. a = stu__cond(a); if (stu__flow) break;
  11840. return a ? stua_true : stua_false;
  11841. case ST_eq: STU__CE(==); case ST_le: STU__C(<=); case '<': STU__C(<);
  11842. case ST_ne: STU__CE(!=); case ST_ge: STU__C(>=); case '>': STU__C(>);
  11843. case '+' : STU__FB(+); case '*': STU__F(*); case '&': STU__I(&); case ST_shl: STU__I(<<);
  11844. case '-' : STU__FB(-); case '/': STU__F(/); case '|': STU__I(|); case ST_shr: STU__I(>>);
  11845. case '%': STU__I(%); case '^': STU__I(^);
  11846. case ST_shru: STU__EVAL2(a,b);
  11847. if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag)
  11848. return stu__makeint((unsigned) stu__int(a) >> stu__int(b));
  11849. return stu__op(stu__f[n], a,b, stua_nil);
  11850. case ST_and: a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;
  11851. return a ? stu__eval(stu__f[n+2]) : a;
  11852. case ST_or : a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;
  11853. return a ? b : stu__eval(stu__f[n+2]);
  11854. case'(':case':': STU__EVAL2(a,b);
  11855. if (!stu__checkt(STU___function, a))
  11856. return stu__op(stu__f[n], a,b, stua_nil);
  11857. if (!stu__checkt(STU___dict, b))
  11858. return stua_nil;
  11859. if (stu__f[n] == ':')
  11860. b = stu__makeobj(STU___dict, stb_idict_copy(stu__pd(b)), stb_idict_memory_usage(stu__pd(b)), 0);
  11861. a = stu__funceval(a,b);
  11862. return a;
  11863. case '{' : {
  11864. stua_dict *d;
  11865. d = stb_idict_new_size(stu__f[n+1] > 40 ? 64 : 16);
  11866. if (d == NULL)
  11867. return stua_nil; // breakpoint fodder
  11868. c = stu__makeobj(STU___dict, d, 32, 1);
  11869. stua_pushroot(c);
  11870. a = stu__f[n+1];
  11871. for (b=0; b < a; ++b) {
  11872. stua_obj x = stua_pushroot(stu__eval(stu__f[n+2 + b*2 + 0]));
  11873. stua_obj y = stu__eval(stu__f[n+2 + b*2 + 1]);
  11874. stua_poproot();
  11875. if (stu__flow) { stua_poproot(); return stua_nil; }
  11876. stu__set(d, x, y);
  11877. }
  11878. stua_poproot();
  11879. return c;
  11880. }
  11881. default: if (stu__f[n] < 0) return stu__const(stu__f)[stu__f[n]];
  11882. assert(0); /* NOTREACHED */ // internal error!
  11883. }
  11884. return stua_nil;
  11885. }
  11886. int stb__stua_nesting;
  11887. static stua_obj stu__funceval(stua_obj fo, stua_obj co)
  11888. {
  11889. stu__func *f = stu__pf(fo);
  11890. stua_dict *context = stu__pd(co);
  11891. int i,j;
  11892. stua_obj p;
  11893. short *tf = stu__f; // save previous function
  11894. stua_dict *tc = stu__c;
  11895. if (stu__flow == FLOW_error) return stua_nil;
  11896. assert(stu__flow == FLOW_normal);
  11897. stua_pushroot(fo);
  11898. stua_pushroot(co);
  11899. stu__consider_gc(stua_nil);
  11900. while ((stb_uint) f->closure_source > 4) {
  11901. // add data from closure to context
  11902. stua_dict *e = (stua_dict *) stu__pd(f->f.closure_data);
  11903. for (i=0; i < e->limit; ++i)
  11904. if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL)
  11905. if (stb_idict_add(context, e->table[i].k, e->table[i].v))
  11906. stu__size_allocs += 8;
  11907. // use add so if it's already defined, we don't override it; that way
  11908. // explicit parameters win over applied ones, and most recent applications
  11909. // win over previous ones
  11910. f = stu__pf(f->closure_source);
  11911. }
  11912. for (j=0, i=0; i < f->num_param; ++i)
  11913. // if it doesn't already exist, add it from the numbered parameters
  11914. if (stb_idict_add(context, f->param[i], stu__get(context, stu__int(j), stua_nil)))
  11915. ++j;
  11916. // @TODO: if (stu__get(context, stu__int(f->num_param+1)) != STUA_NO_VALUE) // error: too many parameters
  11917. // @TODO: ditto too few parameters
  11918. if (f->closure_source == 4)
  11919. p = f->f.func(context);
  11920. else {
  11921. stu__f = f->code, stu__c = context;
  11922. stu__f_obj = co;
  11923. ++stb__stua_nesting;
  11924. if (stu__f[1])
  11925. p = stu__eval(stu__f[1]);
  11926. else
  11927. p = stua_nil;
  11928. --stb__stua_nesting;
  11929. stu__f = tf, stu__c = tc; // restore previous function
  11930. if (stu__flow == FLOW_return) {
  11931. stu__flow = FLOW_normal;
  11932. p = stu__flow_val;
  11933. stu__flow_val = stua_nil;
  11934. }
  11935. }
  11936. stua_poproot();
  11937. stua_poproot();
  11938. return p;
  11939. }
  11940. // Parser
  11941. static int stu__tok;
  11942. static stua_obj stu__tokval;
  11943. static char *stu__curbuf, *stu__bufstart;
  11944. static stb_matcher *stu__lex_matcher;
  11945. static unsigned char stu__prec[ST__max_terminals], stu__end[ST__max_terminals];
  11946. static void stu__nexttoken(void)
  11947. {
  11948. int len;
  11949. retry:
  11950. stu__tok = stb_lex(stu__lex_matcher, stu__curbuf, &len);
  11951. if (stu__tok == 0)
  11952. return;
  11953. switch(stu__tok) {
  11954. case ST_white : stu__curbuf += len; goto retry;
  11955. case T__none : stu__tok = *stu__curbuf; break;
  11956. case ST_string: stu__tokval = make_string(stu__curbuf+1, len-2); break;
  11957. case ST_id : stu__tokval = make_string(stu__curbuf, len); break;
  11958. case ST_hex : stu__tokval = stu__makeint(strtol(stu__curbuf+2,NULL,16)); stu__tok = ST_number; break;
  11959. case ST_decimal: stu__tokval = stu__makeint(strtol(stu__curbuf ,NULL,10)); stu__tok = ST_number; break;
  11960. case ST_float : stu__tokval = stua_float((float) atof(stu__curbuf)) ; stu__tok = ST_number; break;
  11961. case ST_char : stu__tokval = stu__curbuf[2] == '\\' ? stu__curbuf[3] : stu__curbuf[2];
  11962. if (stu__curbuf[3] == 't') stu__tokval = '\t';
  11963. if (stu__curbuf[3] == 'n') stu__tokval = '\n';
  11964. if (stu__curbuf[3] == 'r') stu__tokval = '\r';
  11965. stu__tokval = stu__makeint(stu__tokval);
  11966. stu__tok = ST_number;
  11967. break;
  11968. }
  11969. stu__curbuf += len;
  11970. }
  11971. static struct { int stu__tok; char *regex; } stu__lexemes[] =
  11972. {
  11973. ST_white , "([ \t\n\r]|/\\*(.|\n)*\\*/|//[^\r\n]*([\r\n]|$))+",
  11974. ST_id , "[_a-zA-Z][_a-zA-Z0-9]*",
  11975. ST_hex , "0x[0-9a-fA-F]+",
  11976. ST_decimal, "[0-9]+[0-9]*",
  11977. ST_float , "[0-9]+\\.?[0-9]*([eE][-+]?[0-9]+)?",
  11978. ST_float , "\\.[0-9]+([eE][-+]?[0-9]+)?",
  11979. ST_char , "c'(\\\\.|[^\\'])'",
  11980. ST_string , "\"(\\\\.|[^\\\"\n\r])*\"",
  11981. ST_string , "\'(\\\\.|[^\\\'\n\r])*\'",
  11982. #define stua_key4(a,b,c,d) ST_##a, #a, ST_##b, #b, ST_##c, #c, ST_##d, #d,
  11983. stua_key4(if,then,else,elseif) stua_key4(while,do,for,in)
  11984. stua_key4(func,var,let,break) stua_key4(nil,true,false,end)
  11985. stua_key4(return,continue,as,repeat) stua_key4(_frame,catch,catch,catch)
  11986. ST_shl, "<<", ST_and, "&&", ST_eq, "==", ST_ge, ">=",
  11987. ST_shr, ">>", ST_or , "||", ST_ne, "!=", ST_le, "<=",
  11988. ST_shru,">>>", ST_into, "=>",
  11989. T__none, ".",
  11990. };
  11991. typedef struct
  11992. {
  11993. stua_obj *data; // constants being compiled
  11994. short *code; // code being compiled
  11995. stua_dict *locals;
  11996. short *non_local_refs;
  11997. } stu__comp_func;
  11998. static stu__comp_func stu__pfunc;
  11999. static stu__comp_func *func_stack = NULL;
  12000. static void stu__push_func_comp(void)
  12001. {
  12002. stb_arr_push(func_stack, stu__pfunc);
  12003. stu__pfunc.data = NULL;
  12004. stu__pfunc.code = NULL;
  12005. stu__pfunc.locals = stb_idict_new_size(16);
  12006. stu__pfunc.non_local_refs = NULL;
  12007. stb_arr_push(stu__pfunc.code, 0); // number of data items
  12008. stb_arr_push(stu__pfunc.code, 1); // starting execution address
  12009. }
  12010. static void stu__pop_func_comp(void)
  12011. {
  12012. stb_arr_free(stu__pfunc.code);
  12013. stb_arr_free(stu__pfunc.data);
  12014. stb_idict_destroy(stu__pfunc.locals);
  12015. stb_arr_free(stu__pfunc.non_local_refs);
  12016. stu__pfunc = stb_arr_pop(func_stack);
  12017. }
  12018. // if an id is a reference to an outer lexical scope, this
  12019. // function returns the "name" of it, and updates the stack
  12020. // structures to make sure the names are propogated in.
  12021. static int stu__nonlocal_id(stua_obj var_obj)
  12022. {
  12023. stua_obj dummy, var = var_obj;
  12024. int i, n = stb_arr_len(func_stack), j,k;
  12025. if (stb_idict_get_flag(stu__pfunc.locals, var, &dummy)) return 0;
  12026. for (i=n-1; i > 1; --i) {
  12027. if (stb_idict_get_flag(func_stack[i].locals, var, &dummy))
  12028. break;
  12029. }
  12030. if (i <= 1) return 0; // stu__compile_global_scope
  12031. j = i; // need to access variable from j'th frame
  12032. for (i=0; i < stb_arr_len(stu__pfunc.non_local_refs); ++i)
  12033. if (stu__pfunc.non_local_refs[i] == j) return j-n;
  12034. stb_arr_push(stu__pfunc.non_local_refs, j-n);
  12035. // now make sure all the parents propogate it down
  12036. for (k=n-1; k > 1; --k) {
  12037. if (j-k >= 0) return j-n; // comes direct from this parent
  12038. for(i=0; i < stb_arr_len(func_stack[k].non_local_refs); ++i)
  12039. if (func_stack[k].non_local_refs[i] == j-k)
  12040. return j-n;
  12041. stb_arr_push(func_stack[k].non_local_refs, j-k);
  12042. }
  12043. assert (k != 1);
  12044. return j-n;
  12045. }
  12046. static int stu__off(void) { return stb_arr_len(stu__pfunc.code); }
  12047. static void stu__cc(int a)
  12048. {
  12049. assert(a >= -2000 && a < 5000);
  12050. stb_arr_push(stu__pfunc.code, a);
  12051. }
  12052. static int stu__cc1(int a) { stu__cc(a); return stu__off()-1; }
  12053. static int stu__cc2(int a, int b) { stu__cc(a); stu__cc(b); return stu__off()-2; }
  12054. static int stu__cc3(int a, int b, int c) {
  12055. if (a == '=') assert(c != 0);
  12056. stu__cc(a); stu__cc(b); stu__cc(c); return stu__off()-3; }
  12057. static int stu__cc4(int a, int b, int c, int d) { stu__cc(a); stu__cc(b); stu__cc(c); stu__cc(d); return stu__off()-4; }
  12058. static int stu__cdv(stua_obj p)
  12059. {
  12060. int i;
  12061. assert(p != STUA_NO_VALUE);
  12062. for (i=0; i < stb_arr_len(stu__pfunc.data); ++i)
  12063. if (stu__pfunc.data[i] == p)
  12064. break;
  12065. if (i == stb_arr_len(stu__pfunc.data))
  12066. stb_arr_push(stu__pfunc.data, p);
  12067. return ~i;
  12068. }
  12069. static int stu__cdt(void)
  12070. {
  12071. int z = stu__cdv(stu__tokval);
  12072. stu__nexttoken();
  12073. return z;
  12074. }
  12075. static int stu__seq(int a, int b)
  12076. {
  12077. return !a ? b : !b ? a : stu__cc3(STU__seq, a,b);
  12078. }
  12079. static char stu__comp_err_str[1024];
  12080. static int stu__comp_err_line;
  12081. static int stu__err(char *str, ...)
  12082. {
  12083. va_list v;
  12084. char *s = stu__bufstart;
  12085. stu__comp_err_line = 1;
  12086. while (s < stu__curbuf) {
  12087. if (s[0] == '\n' || s[0] == '\r') {
  12088. if (s[0]+s[1] == '\n' + '\r') ++s;
  12089. ++stu__comp_err_line;
  12090. }
  12091. ++s;
  12092. }
  12093. va_start(v, str);
  12094. vsprintf(stu__comp_err_str, str, v);
  12095. va_end(v);
  12096. return 0;
  12097. }
  12098. static int stu__accept(int p)
  12099. {
  12100. if (stu__tok != p) return 0;
  12101. stu__nexttoken();
  12102. return 1;
  12103. }
  12104. static int stu__demand(int p)
  12105. {
  12106. if (stu__accept(p)) return 1;
  12107. return stu__err("Didn't find expected stu__tok");
  12108. }
  12109. static int stu__demandv(int p, stua_obj *val)
  12110. {
  12111. if (stu__tok == p || p==0) {
  12112. *val = stu__tokval;
  12113. stu__nexttoken();
  12114. return 1;
  12115. } else
  12116. return 0;
  12117. }
  12118. static int stu__expr(int p);
  12119. int stu__nexpr(int p) { stu__nexttoken(); return stu__expr(p); }
  12120. static int stu__statements(int once, int as);
  12121. static int stu__parse_if(void) // parse both ST_if and ST_elseif
  12122. {
  12123. int b,c,a;
  12124. a = stu__nexpr(1); if (!a) return 0;
  12125. if (!stu__demand(ST_then)) return stu__err("expecting THEN");
  12126. b = stu__statements(0,0); if (!b) return 0;
  12127. if (b == 1) b = -1;
  12128. if (stu__tok == ST_elseif) {
  12129. return stu__parse_if();
  12130. } else if (stu__accept(ST_else)) {
  12131. c = stu__statements(0,0); if (!c) return 0;
  12132. if (!stu__demand(ST_end)) return stu__err("expecting END after else clause");
  12133. return stu__cc4(ST_else, a, b, c);
  12134. } else {
  12135. if (!stu__demand(ST_end)) return stu__err("expecting END in if statement");
  12136. return stu__cc3(ST_if, a, b);
  12137. }
  12138. }
  12139. int stu__varinit(int z, int in_globals)
  12140. {
  12141. int a,b;
  12142. stu__nexttoken();
  12143. while (stu__demandv(ST_id, &b)) {
  12144. if (!stb_idict_add(stu__pfunc.locals, b, 1))
  12145. if (!in_globals) return stu__err("Redefined variable %s.", stu__pw(b)->ptr);
  12146. if (stu__accept('=')) {
  12147. a = stu__expr(1); if (!a) return 0;
  12148. } else
  12149. a = stu__cdv(stua_nil);
  12150. z = stu__seq(z, stu__cc3(ST_var, stu__cdv(b), a));
  12151. if (!stu__accept(',')) break;
  12152. }
  12153. return z;
  12154. }
  12155. static int stu__compile_unary(int z, int outparm, int require_inparm)
  12156. {
  12157. int op = stu__tok, a, b;
  12158. stu__nexttoken();
  12159. if (outparm) {
  12160. if (require_inparm || (stu__tok && stu__tok != ST_end && stu__tok != ST_else && stu__tok != ST_elseif && stu__tok !=';')) {
  12161. a = stu__expr(1); if (!a) return 0;
  12162. } else
  12163. a = stu__cdv(stua_nil);
  12164. b = stu__cc2(op, a);
  12165. } else
  12166. b = stu__cc1(op);
  12167. return stu__seq(z,b);
  12168. }
  12169. static int stu__assign(void)
  12170. {
  12171. int z;
  12172. stu__accept(ST_let);
  12173. z = stu__expr(1); if (!z) return 0;
  12174. if (stu__accept('=')) {
  12175. int y,p = (z >= 0 ? stu__pfunc.code[z] : 0);
  12176. if (z < 0 || (p != ST_id && p != '[')) return stu__err("Invalid lvalue in assignment");
  12177. y = stu__assign(); if (!y) return 0;
  12178. z = stu__cc3('=', z, y);
  12179. }
  12180. return z;
  12181. }
  12182. static int stu__statements(int once, int stop_while)
  12183. {
  12184. int a,b, c, z=0;
  12185. for(;;) {
  12186. switch (stu__tok) {
  12187. case ST_if : a = stu__parse_if(); if (!a) return 0;
  12188. z = stu__seq(z, a);
  12189. break;
  12190. case ST_while : if (stop_while) return (z ? z:1);
  12191. a = stu__nexpr(1); if (!a) return 0;
  12192. if (stu__accept(ST_as)) c = stu__statements(0,0); else c = 0;
  12193. if (!stu__demand(ST_do)) return stu__err("expecting DO");
  12194. b = stu__statements(0,0); if (!b) return 0;
  12195. if (!stu__demand(ST_end)) return stu__err("expecting END");
  12196. if (b == 1) b = -1;
  12197. z = stu__seq(z, stu__cc4(ST_while, a, b, c));
  12198. break;
  12199. case ST_repeat : stu__nexttoken();
  12200. c = stu__statements(0,1); if (!c) return 0;
  12201. if (!stu__demand(ST_while)) return stu__err("expecting WHILE");
  12202. a = stu__expr(1); if (!a) return 0;
  12203. if (!stu__demand(ST_do)) return stu__err("expecting DO");
  12204. b = stu__statements(0,0); if (!b) return 0;
  12205. if (!stu__demand(ST_end)) return stu__err("expecting END");
  12206. if (b == 1) b = -1;
  12207. z = stu__seq(z, stu__cc4(ST_as, a, b, c));
  12208. break;
  12209. case ST_catch : a = stu__nexpr(1); if (!a) return 0;
  12210. z = stu__seq(z, stu__cc2(ST_catch, a));
  12211. break;
  12212. case ST_var : z = stu__varinit(z,0); break;
  12213. case ST_return : z = stu__compile_unary(z,1,1); break;
  12214. case ST_continue:z = stu__compile_unary(z,0,0); break;
  12215. case ST_break : z = stu__compile_unary(z,1,0); break;
  12216. case ST_into : if (z == 0 && !once) return stu__err("=> cannot be first statement in block");
  12217. a = stu__nexpr(99);
  12218. b = (a >= 0? stu__pfunc.code[a] : 0);
  12219. if (a < 0 || (b != ST_id && b != '[')) return stu__err("Invalid lvalue on right side of =>");
  12220. z = stu__cc3('=', a, z);
  12221. break;
  12222. default : if (stu__end[stu__tok]) return once ? 0 : (z ? z:1);
  12223. a = stu__assign(); if (!a) return 0;
  12224. stu__accept(';');
  12225. if (stu__tok && !stu__end[stu__tok]) {
  12226. if (a < 0)
  12227. return stu__err("Constant has no effect");
  12228. if (stu__pfunc.code[a] != '(' && stu__pfunc.code[a] != '=')
  12229. return stu__err("Expression has no effect");
  12230. }
  12231. z = stu__seq(z, a);
  12232. break;
  12233. }
  12234. if (!z) return 0;
  12235. stu__accept(';');
  12236. if (once && stu__tok != ST_into) return z;
  12237. }
  12238. }
  12239. static int stu__postexpr(int z, int p);
  12240. static int stu__dictdef(int end, int *count)
  12241. {
  12242. int z,n=0,i,flags=0;
  12243. short *dict=NULL;
  12244. stu__nexttoken();
  12245. while (stu__tok != end) {
  12246. if (stu__tok == ST_id) {
  12247. stua_obj id = stu__tokval;
  12248. stu__nexttoken();
  12249. if (stu__tok == '=') {
  12250. flags |= 1;
  12251. stb_arr_push(dict, stu__cdv(id));
  12252. z = stu__nexpr(1); if (!z) return 0;
  12253. } else {
  12254. z = stu__cc2(ST_id, stu__cdv(id));
  12255. z = stu__postexpr(z,1); if (!z) return 0;
  12256. flags |= 2;
  12257. stb_arr_push(dict, stu__cdv(stu__makeint(n++)));
  12258. }
  12259. } else {
  12260. z = stu__expr(1); if (!z) return 0;
  12261. flags |= 2;
  12262. stb_arr_push(dict, stu__cdv(stu__makeint(n++)));
  12263. }
  12264. if (end != ')' && flags == 3) { z=stu__err("can't mix initialized and uninitialized defs"); goto done;}
  12265. stb_arr_push(dict, z);
  12266. if (!stu__accept(',')) break;
  12267. }
  12268. if (!stu__demand(end))
  12269. return stu__err(end == ')' ? "Expecting ) at end of function call"
  12270. : "Expecting } at end of dictionary definition");
  12271. z = stu__cc2('{', stb_arr_len(dict)/2);
  12272. for (i=0; i < stb_arr_len(dict); ++i)
  12273. stu__cc(dict[i]);
  12274. if (count) *count = n;
  12275. done:
  12276. stb_arr_free(dict);
  12277. return z;
  12278. }
  12279. static int stu__comp_id(void)
  12280. {
  12281. int z,d;
  12282. d = stu__nonlocal_id(stu__tokval);
  12283. if (d == 0)
  12284. return z = stu__cc2(ST_id, stu__cdt());
  12285. // access a non-local frame by naming it with the appropriate int
  12286. assert(d < 0);
  12287. z = stu__cdv(d); // relative frame # is the 'variable' in our local frame
  12288. z = stu__cc2(ST_id, z); // now access that dictionary
  12289. return stu__cc3('[', z, stu__cdt()); // now access the variable from that dir
  12290. }
  12291. static stua_obj stu__funcdef(stua_obj *id, stua_obj *func);
  12292. static int stu__expr(int p)
  12293. {
  12294. int z;
  12295. // unary
  12296. switch (stu__tok) {
  12297. case ST_number: z = stu__cdt(); break;
  12298. case ST_string: z = stu__cdt(); break; // @TODO - string concatenation like C
  12299. case ST_id : z = stu__comp_id(); break;
  12300. case ST__frame: z = stu__cc1(ST__frame); stu__nexttoken(); break;
  12301. case ST_func : z = stu__funcdef(NULL,NULL); break;
  12302. case ST_if : z = stu__parse_if(); break;
  12303. case ST_nil : z = stu__cdv(stua_nil); stu__nexttoken(); break;
  12304. case ST_true : z = stu__cdv(stua_true); stu__nexttoken(); break;
  12305. case ST_false : z = stu__cdv(stua_false); stu__nexttoken(); break;
  12306. case '-' : z = stu__nexpr(99); if (z) z=stu__cc2(STU__negate,z); else return z; break;
  12307. case '!' : z = stu__nexpr(99); if (z) z=stu__cc2('!',z); else return z; break;
  12308. case '~' : z = stu__nexpr(99); if (z) z=stu__cc2('~',z); else return z; break;
  12309. case '{' : z = stu__dictdef('}', NULL); break;
  12310. default : return stu__err("Unexpected token");
  12311. case '(' : stu__nexttoken(); z = stu__statements(0,0); if (!stu__demand(')')) return stu__err("Expecting )");
  12312. }
  12313. return stu__postexpr(z,p);
  12314. }
  12315. static int stu__postexpr(int z, int p)
  12316. {
  12317. int q;
  12318. // postfix
  12319. while (stu__tok == '(' || stu__tok == '[' || stu__tok == '.') {
  12320. if (stu__accept('.')) {
  12321. // MUST be followed by a plain identifier! use [] for other stuff
  12322. if (stu__tok != ST_id) return stu__err("Must follow . with plain name; try [] instead");
  12323. z = stu__cc3('[', z, stu__cdv(stu__tokval));
  12324. stu__nexttoken();
  12325. } else if (stu__accept('[')) {
  12326. while (stu__tok != ']') {
  12327. int r = stu__expr(1); if (!r) return 0;
  12328. z = stu__cc3('[', z, r);
  12329. if (!stu__accept(',')) break;
  12330. }
  12331. if (!stu__demand(']')) return stu__err("Expecting ]");
  12332. } else {
  12333. int n, p = stu__dictdef(')', &n); if (!p) return 0;
  12334. #if 0 // this is incorrect!
  12335. if (z > 0 && stu__pfunc.code[z] == ST_id) {
  12336. stua_obj q = stu__get(stu__globaldict, stu__pfunc.data[-stu__pfunc.code[z+1]-1], stua_nil);
  12337. if (stu__checkt(STU___function, q))
  12338. if ((stu__pf(q))->num_param != n)
  12339. return stu__err("Incorrect number of parameters");
  12340. }
  12341. #endif
  12342. z = stu__cc3('(', z, p);
  12343. }
  12344. }
  12345. // binop - this implementation taken from lcc
  12346. for (q=stu__prec[stu__tok]; q >= p; --q) {
  12347. while (stu__prec[stu__tok] == q) {
  12348. int o = stu__tok, y = stu__nexpr(p+1); if (!y) return 0;
  12349. z = stu__cc3(o,z,y);
  12350. }
  12351. }
  12352. return z;
  12353. }
  12354. static stua_obj stu__finish_func(stua_obj *param, int start)
  12355. {
  12356. int n, size;
  12357. stu__func *f = (stu__func *) malloc(sizeof(*f));
  12358. f->closure_source = 0;
  12359. f->num_param = stb_arr_len(param);
  12360. f->param = (int *) stb_copy(param, f->num_param * sizeof(*f->param));
  12361. size = stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data) + sizeof(*f) + 8;
  12362. f->f.store = malloc(stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data));
  12363. f->code = (short *) ((char *) f->f.store + stb_arr_storage(stu__pfunc.data));
  12364. memcpy(f->code, stu__pfunc.code, stb_arr_storage(stu__pfunc.code));
  12365. f->code[1] = start;
  12366. f->code[0] = stb_arr_len(stu__pfunc.data);
  12367. for (n=0; n < f->code[0]; ++n)
  12368. ((stua_obj *) f->code)[-1-n] = stu__pfunc.data[n];
  12369. return stu__makeobj(STU___function, f, size, 0);
  12370. }
  12371. static int stu__funcdef(stua_obj *id, stua_obj *result)
  12372. {
  12373. int n,z=0,i,q;
  12374. stua_obj *param = NULL;
  12375. short *nonlocal;
  12376. stua_obj v,f=stua_nil;
  12377. assert(stu__tok == ST_func);
  12378. stu__nexttoken();
  12379. if (id) {
  12380. if (!stu__demandv(ST_id, id)) return stu__err("Expecting function name");
  12381. } else
  12382. stu__accept(ST_id);
  12383. if (!stu__demand('(')) return stu__err("Expecting ( for function parameter");
  12384. stu__push_func_comp();
  12385. while (stu__tok != ')') {
  12386. if (!stu__demandv(ST_id, &v)) { z=stu__err("Expecting parameter name"); goto done; }
  12387. stb_idict_add(stu__pfunc.locals, v, 1);
  12388. if (stu__tok == '=') {
  12389. n = stu__nexpr(1); if (!n) { z=0; goto done; }
  12390. z = stu__seq(z, stu__cc3(STU__defaultparm, stu__cdv(v), n));
  12391. } else
  12392. stb_arr_push(param, v);
  12393. if (!stu__accept(',')) break;
  12394. }
  12395. if (!stu__demand(')')) { z=stu__err("Expecting ) at end of parameter list"); goto done; }
  12396. n = stu__statements(0,0); if (!n) { z=0; goto done; }
  12397. if (!stu__demand(ST_end)) { z=stu__err("Expecting END at end of function"); goto done; }
  12398. if (n == 1) n = 0;
  12399. n = stu__seq(z,n);
  12400. f = stu__finish_func(param, n);
  12401. if (result) { *result = f; z=1; stu__pop_func_comp(); }
  12402. else {
  12403. nonlocal = stu__pfunc.non_local_refs;
  12404. stu__pfunc.non_local_refs = NULL;
  12405. stu__pop_func_comp();
  12406. z = stu__cdv(f);
  12407. if (nonlocal) { // build a closure with references to the needed frames
  12408. short *initcode = NULL;
  12409. for (i=0; i < stb_arr_len(nonlocal); ++i) {
  12410. int k = nonlocal[i], p;
  12411. stb_arr_push(initcode, stu__cdv(k));
  12412. if (k == -1) p = stu__cc1(ST__frame);
  12413. else { p = stu__cdv(stu__makeint(k+1)); p = stu__cc2(ST_id, p); }
  12414. stb_arr_push(initcode, p);
  12415. }
  12416. q = stu__cc2('{', stb_arr_len(nonlocal));
  12417. for (i=0; i < stb_arr_len(initcode); ++i)
  12418. stu__cc(initcode[i]);
  12419. z = stu__cc3('+', z, q);
  12420. stb_arr_free(initcode);
  12421. }
  12422. stb_arr_free(nonlocal);
  12423. }
  12424. done:
  12425. stb_arr_free(param);
  12426. if (!z) stu__pop_func_comp();
  12427. return z;
  12428. }
  12429. static int stu__compile_global_scope(void)
  12430. {
  12431. stua_obj o;
  12432. int z=0;
  12433. stu__push_func_comp();
  12434. while (stu__tok != 0) {
  12435. if (stu__tok == ST_func) {
  12436. stua_obj id, f;
  12437. if (!stu__funcdef(&id,&f))
  12438. goto error;
  12439. stu__set(stu__globaldict, id, f);
  12440. } else if (stu__tok == ST_var) {
  12441. z = stu__varinit(z,1); if (!z) goto error;
  12442. } else {
  12443. int y = stu__statements(1,0); if (!y) goto error;
  12444. z = stu__seq(z,y);
  12445. }
  12446. stu__accept(';');
  12447. }
  12448. o = stu__finish_func(NULL, z);
  12449. stu__pop_func_comp();
  12450. o = stu__funceval(o, stua_globals); // initialize stu__globaldict
  12451. if (stu__flow == FLOW_error)
  12452. printf("Error: %s\n", ((stu__wrapper *) stu__ptr(stu__flow_val))->ptr);
  12453. return 1;
  12454. error:
  12455. stu__pop_func_comp();
  12456. return 0;
  12457. }
  12458. stua_obj stu__myprint(stua_dict *context)
  12459. {
  12460. stua_obj x = stu__get(context, stua_string("x"), stua_nil);
  12461. if ((x & 1) == stu__float_tag) printf("%f", stu__getfloat(x));
  12462. else if (stu__tag(x) == stu__int_tag) printf("%d", stu__int(x));
  12463. else {
  12464. stu__wrapper *s = stu__pw(x);
  12465. if (s->type == STU___string || s->type == STU___error)
  12466. printf("%s", s->ptr);
  12467. else if (s->type == STU___dict) printf("{{dictionary}}");
  12468. else if (s->type == STU___function) printf("[[function]]");
  12469. else
  12470. printf("[[ERROR:%s]]", s->ptr);
  12471. }
  12472. return x;
  12473. }
  12474. void stua_init(void)
  12475. {
  12476. if (!stu__globaldict) {
  12477. int i;
  12478. stua_obj s;
  12479. stu__func *f;
  12480. stu__prec[ST_and] = stu__prec[ST_or] = 1;
  12481. stu__prec[ST_eq ] = stu__prec[ST_ne] = stu__prec[ST_le] =
  12482. stu__prec[ST_ge] = stu__prec['>' ] = stu__prec['<'] = 2;
  12483. stu__prec[':'] = 3;
  12484. stu__prec['&'] = stu__prec['|'] = stu__prec['^'] = 4;
  12485. stu__prec['+'] = stu__prec['-'] = 5;
  12486. stu__prec['*'] = stu__prec['/'] = stu__prec['%'] =
  12487. stu__prec[ST_shl]= stu__prec[ST_shr]= stu__prec[ST_shru]= 6;
  12488. stu__end[')'] = stu__end[ST_end] = stu__end[ST_else] = 1;
  12489. stu__end[ST_do] = stu__end[ST_elseif] = 1;
  12490. stu__float_init();
  12491. stu__lex_matcher = stb_lex_matcher();
  12492. for (i=0; i < sizeof(stu__lexemes)/sizeof(stu__lexemes[0]); ++i)
  12493. stb_lex_item(stu__lex_matcher, stu__lexemes[i].regex, stu__lexemes[i].stu__tok);
  12494. stu__globaldict = stb_idict_new_size(64);
  12495. stua_globals = stu__makeobj(STU___dict, stu__globaldict, 0,0);
  12496. stu__strings = stb_sdict_new(0);
  12497. stu__curbuf = stu__bufstart = "func _print(x) end\n"
  12498. "func print()\n var x=0 while _frame[x] != nil as x=x+1 do _print(_frame[x]) end end\n";
  12499. stu__nexttoken();
  12500. if (!stu__compile_global_scope())
  12501. printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);
  12502. s = stu__get(stu__globaldict, stua_string("_print"), stua_nil);
  12503. if (stu__tag(s) == stu__ptr_tag && stu__ptr(s)->type == STU___function) {
  12504. f = stu__pf(s);
  12505. free(f->f.store);
  12506. f->closure_source = 4;
  12507. f->f.func = stu__myprint;
  12508. f->code = NULL;
  12509. }
  12510. }
  12511. }
  12512. void stua_uninit(void)
  12513. {
  12514. if (stu__globaldict) {
  12515. stb_idict_remove_all(stu__globaldict);
  12516. stb_arr_setlen(stu__gc_root_stack, 0);
  12517. stua_gc(1);
  12518. stb_idict_destroy(stu__globaldict);
  12519. stb_sdict_delete(stu__strings);
  12520. stb_matcher_free(stu__lex_matcher);
  12521. stb_arr_free(stu__gc_ptrlist);
  12522. stb_arr_free(func_stack);
  12523. stb_arr_free(stu__gc_root_stack);
  12524. stu__globaldict = NULL;
  12525. }
  12526. }
  12527. void stua_run_script(char *s)
  12528. {
  12529. stua_init();
  12530. stu__curbuf = stu__bufstart = s;
  12531. stu__nexttoken();
  12532. stu__flow = FLOW_normal;
  12533. if (!stu__compile_global_scope())
  12534. printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);
  12535. stua_gc(1);
  12536. }
  12537. #endif // STB_DEFINE
  12538. #endif // STB_STUA
  12539. #undef STB_EXTERN
  12540. #endif // STB_INCLUDE_STB_H
  12541. /*
  12542. ------------------------------------------------------------------------------
  12543. This software is available under 2 licenses -- choose whichever you prefer.
  12544. ------------------------------------------------------------------------------
  12545. ALTERNATIVE A - MIT License
  12546. Copyright (c) 2017 Sean Barrett
  12547. Permission is hereby granted, free of charge, to any person obtaining a copy of
  12548. this software and associated documentation files (the "Software"), to deal in
  12549. the Software without restriction, including without limitation the rights to
  12550. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  12551. of the Software, and to permit persons to whom the Software is furnished to do
  12552. so, subject to the following conditions:
  12553. The above copyright notice and this permission notice shall be included in all
  12554. copies or substantial portions of the Software.
  12555. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12556. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12557. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12558. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12559. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12560. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12561. SOFTWARE.
  12562. ------------------------------------------------------------------------------
  12563. ALTERNATIVE B - Public Domain (www.unlicense.org)
  12564. This is free and unencumbered software released into the public domain.
  12565. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  12566. software, either in source code form or as a compiled binary, for any purpose,
  12567. commercial or non-commercial, and by any means.
  12568. In jurisdictions that recognize copyright laws, the author or authors of this
  12569. software dedicate any and all copyright interest in the software to the public
  12570. domain. We make this dedication for the benefit of the public at large and to
  12571. the detriment of our heirs and successors. We intend this dedication to be an
  12572. overt act of relinquishment in perpetuity of all present and future rights to
  12573. this software under copyright law.
  12574. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12575. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12576. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12577. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  12578. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  12579. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  12580. ------------------------------------------------------------------------------
  12581. */