Statistics
| Branch: | Revision:

grapes / src / Chunkiser / input-stream-dumb.c @ 997c2b68

History | View | Annotate | Download (2 KB)

1
/*
2
 *  Copyright (c) 2010 Luca Abeni
3
 *
4
 *  This is free software; see gpl-3.0.txt
5
 */
6

    
7
#include <sys/types.h>
8
#include <sys/stat.h>
9
#include <fcntl.h>
10
#include <unistd.h>
11
#include <errno.h>
12
#include <stdint.h>
13
#include <stdlib.h>
14
#include <string.h>
15

    
16
#include "chunkiser_iface.h"
17
#include "config.h"
18

    
19
struct chunkiser_ctx {
20
  int loop;        //loop on input file infinitely
21
  int chunk_size;
22
  int fds[2];
23
};
24
#define DEFAULT_CHUNK_SIZE 2 * 1024
25

    
26
static struct chunkiser_ctx *dumb_open(const char *fname, int *period, const char *config)
27
{
28
  struct tag *cfg_tags;
29
  struct chunkiser_ctx *res;
30

    
31
  res = malloc(sizeof(struct chunkiser_ctx));
32
  if (res == NULL) {
33
    return NULL;
34
  }
35

    
36
  res->loop = 0;
37
  res->fds[0] = open(fname, O_RDONLY);
38
  if (res->fds[0] < 0) {
39
    free(res);
40

    
41
    return NULL;
42
  }
43
  res->fds[1] = -1;
44

    
45
  *period = 0;
46
  res->chunk_size = DEFAULT_CHUNK_SIZE;
47
  cfg_tags = config_parse(config);
48
  if (cfg_tags) {
49
    const char *access_mode;
50

    
51
    config_value_int(cfg_tags, "loop", &res->loop);
52
    config_value_int(cfg_tags, "chunk_size", &res->chunk_size);
53
    access_mode = config_value_str(cfg_tags, "mode");
54
    if (access_mode && !strcmp(access_mode, "nonblock")) {
55
      fcntl(res->fds[0], F_SETFL, O_NONBLOCK);
56
    }
57
  }
58
  free(cfg_tags);
59

    
60
  return res;
61
}
62

    
63
static void dumb_close(struct chunkiser_ctx *s)
64
{
65
  close(s->fds[0]);
66
  free(s);
67
}
68

    
69
static uint8_t *dumb_chunkise(struct chunkiser_ctx *s, int id, int *size, uint64_t *ts)
70
{
71
  uint8_t *res;
72

    
73
  res = malloc(s->chunk_size);
74
  if (res == NULL) {
75
    *size = -1;
76

    
77
    return NULL;
78
  }
79
  *ts = 0;
80
  *size = read(s->fds[0], res, s->chunk_size);
81
  if ((*size == 0) && (errno != EAGAIN)) {
82
    *size = -1;
83
    if (s->loop) {
84
      if (lseek(s->fds[0], 0, SEEK_SET) == 0) {
85
        *size = 0;
86
      }
87
    }
88
    free(res);
89
    res = NULL;
90
  }
91

    
92
  return res;
93
}
94

    
95
const int *dumb_get_fds(const struct chunkiser_ctx *s)
96
{
97
  return s->fds;
98
}
99

    
100
struct chunkiser_iface in_dumb = {
101
  .open = dumb_open,
102
  .close = dumb_close,
103
  .chunkise = dumb_chunkise,
104
  .get_fds = dumb_get_fds,
105
};
106

    
107