Created
April 14, 2015 12:44
-
-
Save gnull/f8fd641c6b0cbafdad9f to your computer and use it in GitHub Desktop.
MC homework #2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdint.h> | |
#ifndef QUEUE_MAXLEN | |
#define QUEUE_MAXLEN 0x10 | |
#endif | |
#define E_EMPTY -1 | |
#define E_FULL -2 | |
typedef struct queue { | |
uint8_t buffer[QUEUE_MAXLEN]; | |
int read_from, write_to; | |
int len; | |
} queue_t; | |
// Инициализация. Должна быть вызвана перед использованием очереди. | |
void queue_init( queue_t *q ) | |
{ | |
q->read_from = q->write_to = q->len = 0; | |
} | |
// Добавление элемента. При успехе возвращает 0. | |
int queue_push( queue_t *q, uint8_t val ) | |
{ | |
if( q->len == QUEUE_MAXLEN ) | |
return E_FULL; | |
q->len++; | |
q->buffer[q->write_to] = val; | |
q->write_to = ( q->write_to + 1 ) % QUEUE_MAXLEN; | |
return 0; | |
} | |
// Извлечение элемента. При успехе возвращает 0, | |
// при ошибке - отрицательное число. | |
int queue_pop( queue_t *q ) | |
{ | |
if( !q->len ) | |
return E_EMPTY; | |
int result = q->buffer[q->read_from]; | |
q->len--; | |
q->read_from = ( q->read_from + 1 ) % QUEUE_MAXLEN; | |
return result; | |
} | |
// Количество элементов в очереди. | |
int queue_length( const queue_t *q ) | |
{ | |
return q->len; | |
} | |
// Проверка, заполнена ли очередь. | |
int queue_full( const queue_t *q ) | |
{ | |
return q->len == QUEUE_MAXLEN; | |
} | |
// Далее код для тестирования | |
char help[] = " push <value> | pop | exit\n"; | |
int main() | |
{ | |
queue_t Q; | |
queue_t *q = &Q; | |
queue_init( q ); | |
printf( help ); | |
char cmd[20]; | |
while( printf( "> " ), | |
scanf( "%19s", cmd ), | |
strcmp( cmd, "exit" ) ) { | |
if( !strcmp( cmd, "push" ) ) { | |
uint8_t val; | |
scanf( "%hhu", &val ); | |
printf( " push( %hhu ) = %d\n", val, queue_push(q, val) ); | |
} else if ( !strcmp( cmd, "pop" ) ) { | |
printf( " pop() = %d\n", queue_pop( q ) ); | |
} else { | |
printf( " Uknown command: %s\n%s", cmd, help ); | |
} | |
printf( " length = %d / %d\n", queue_length( q ), QUEUE_MAXLEN ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment