21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

#include <br />

#include <br />

#include <br />

#include <br />

#ifndef TIOCGWINSZ<br />

#include <br />

#endif<br />

#include <br />

#define HASH_OUT_SZ 20<br />

#define OVERHEAD_CHARS 7<br />

#define DEFAULT_BARSIZE (78 - OVERHEAD_CHARS)<br />

#define MAX_BARSIZE 200<br />

void spc_raw(int fd, struct termios *saved_opts) {<br />

struct termios new_opts;<br />

if (tcgetattr(fd, saved_opts) < 0) abort( );<br />

/* Make a copy of saved_opts, not an alias. */<br />

new_opts = *saved_opts;<br />

new_opts.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);<br />

new_opts.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);<br />

new_opts.c_cflag &= ~(CSIZE | PARENB);<br />

new_opts.c_cflag |= CS8;<br />

new_opts.c_oflag &= ~OPOST;<br />

new_opts.c_cc[VMIN] = 1;<br />

new_opts.c_cc[VTIME] = 0;<br />

if (tcsetattr(fd, TCSAFLUSH, &new_opts) < 0) abort( );<br />

}<br />

/* Query the terminal file descriptor with the TIOCGWINSZ ioctl in order to find<br />

* out the width of the terminal. If we get an error, go ahead and assume a 78<br />

* character display. The worst that may happen is bad wrapping.<br />

*/<br />

static int spc_get_barsize(int ttyfd) {<br />

struct winsize sz;<br />

if (ioctl(ttyfd, TIOCGWINSZ, (char *)&sz) < 0) return DEFAULT_BARSIZE;<br />

if (sz.ws_col < OVERHEAD_CHARS) return 0;<br />

if (sz.ws_col - OVERHEAD_CHARS > MAX_BARSIZE) return MAX_BARSIZE;<br />

return sz.ws_col - OVERHEAD_CHARS;<br />

}<br />

static void spc_show_progress_bar(double entropy, int target, int ttyfd) {<br />

int bsz, c;<br />

char bf[MAX_BARSIZE + OVERHEAD_CHARS];<br />

bsz = spc_get_barsize(ttyfd);<br />

c = (int)((entropy * bsz) / target);<br />

bf[sizeof(bf) - 1] = 0;<br />

if (bsz) {<br />

snprintf(bf, sizeof(bf), "\r[%-*s] %d%%", bsz, "",<br />

(int)(entropy * 100.0 / target));<br />

memset(bf + 2, '=', c);<br />

632 | Chapter 11: Random Numbers<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!