summaryrefslogtreecommitdiff
path: root/el.c
blob: 40dccbd59e84034c481cfc2540a1c2a0de383dd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/* Extract Lines
   Usage: echo -x 10 2 7 100 | el -x data.txt
   extracts lines 16, 2, 7, 256 from the file data.txt
*/

#include <stdlib.h>
#include "mystdlib.h"
#include <unistd.h>
#include <ctype.h>

// Our index into the already scanned lines.
// memory buffer is estimated to 1/32th of the
// indexed file's size, meaning each line
// containing approx 31 letters. If it hits the
// top, we increase in 1/32th steps
static unsigned char **index = NULL;

// this denotes the number of fields, NOT the
// memory occupied (would be a size_t, then!!!)
static long indexsize = 0;

// this specifies, how many lines have been indexed
// already, scanning always only happens to the
// last reqeusted line
static long indexfilled = 1;

// If set, the stream of linenums specified calls
// the first line number 0... *shiver*
static int g_zerobased = 0;

// If set, line numbers are prepended to each line
// (the way grep does it, i.e. ^2342:<line>$)
static int g_echolinenr = 0;

// This tells us, whether we need to scan for hex
// line numbers
static char *g_scanfmodifier = "%i";

// If user specifies some line numbers on command
// line, store pointer here
static char *g_immediatelinenums = (char *)0;

// If input is guaranteed to come from "grep -n"
// we will spare the user from "| cut -f 1 -d :"
static int g_fromgrep = 0;
static int g_fromgrepverbatim = 0;

static int nextchar( void ) {
  if( !g_immediatelinenums )
    return getchar();
  if( *g_immediatelinenums )
    return *g_immediatelinenums++;
  return EOF;
}

// scans the text file for the requested line
// returns NULL, if line exceeds file's end
// Note: we will not extend the index too early
// to prevent huge numbers from stdin to steal our
// memory

static unsigned char * scanforline( MAP file, const long lineno, long *size ) {
  unsigned char *scanline, *const e_o_f = file->addr + file->size;
  static int alllinesscanned = 0;
  *size = 0;

  // lines start at 1
  if( lineno < 1 ) return NULL;

  // lines we already found can simply be returned
  if( lineno < indexfilled ) {
    *size = index[lineno] - index[lineno-1];
    return index[lineno-1];
  }

  // if alllines were scanned, were either on
  // or behind last line
  if( alllinesscanned ) {
    if( lineno == indexfilled ) {
      *size = e_o_f - index[lineno-1];
      return index[lineno-1];
      }
    return NULL;
  }

  // exploring undiscovered land...
  scanline = index[indexfilled-1];

  while( indexfilled <= lineno ) {
    // scan for next line
    while( ( scanline < e_o_f ) && ( *scanline++ != '\n' ));

    // store pointer
    if( scanline == e_o_f ) {
      alllinesscanned = 1;
      if( indexfilled == lineno ) {
        *size = e_o_f - index[lineno-1];
        return index[lineno-1];
      } else
        return NULL;
    }

    index[indexfilled++] = scanline;

    // reallocate some memory
    if( indexfilled == indexsize ) {
      unsigned char ** newblock = (unsigned char**) realloc( index, sizeof(char *) * ( indexsize + file->size / 32 ) );
      if( !newblock ) {
        fputs( "Could not allocate memory, exiting.\n", stderr);
        // unmap file and zero pointer
        unmap_file( &file );
        exit ( 1 );
      }
      indexsize += file->size / 32;
      index = newblock;
    }
  
  }

  *size = index[lineno] - index[lineno-1];
  return index[lineno-1];
}

// Reads all characters up to the next white space
// from stdin, eof is treated as a white space
// If more than 13 characters without white space
// occur, we assume a too large line number and return
// 0 which is an invalid line (these start at 1) and will
// result in an empty line being printed

// Rationale:
// Since we wont support linenos greater 2^31 and this
// is 12 characters + leading 0 in octal, we stop parsing
// after 13 characters (technically, 001 is 01, but
// constructing such strings to annoy parser writers must
// be punished

static int acquire_lineno( int c ) {
  char input[15];
  int inputindex = 0, lineno;

  while ( (c != EOF) && !isspace(c)) {
    if( g_fromgrep && c == ':' ) {
      if( g_echolinenr )
        putchar( ':' );
      while( ( ( c = nextchar() ) != EOF ) && ( c != '\n' ) )
        if( g_fromgrepverbatim )
          putchar(c);
      if( g_fromgrepverbatim )
        putchar( '\t' );
      break;
    }
    if( g_echolinenr )
      putchar( c );
    if( inputindex < 14 )
      input[inputindex++] = (char)c;
    c = nextchar();
  }
  if( !g_fromgrep && g_echolinenr )
    putchar( ':' );

  if( inputindex == 14 )
    return 0;

  input[inputindex] = 0;

  // Try to read 
  if( sscanf( input, g_scanfmodifier, &lineno ) != 1 )
    return 0;

  return lineno + g_zerobased;
}

static void usage() {
  fputs( "Usage: el [-0Ggnxh] [-i linenums] filename < linenum_file\n", stderr);
}

int main( int argc, char **argv ) {
  // Our handle to the mapped text file
  MAP textfile = NULL;
  int c;

  while ((c = getopt(argc, argv, ":0i:gGnxh")) != -1) {
    switch (c) {
      case '0':
        g_zerobased = 1;
        break;
      case 'x':
        g_scanfmodifier = "%x";
        break;
      case 'i':
        g_immediatelinenums = optarg;
        break;
      case 'n':
        g_echolinenr = 1;
        break;
      case 'G':
        g_fromgrepverbatim = 1;
      case 'g':
        g_fromgrep = 1;
        break;
      case 'h':
      case '?':
      default:
        usage();
        exit(1);
    }
  }
  argc -= optind;
  argv += optind;

  if( argc != 1 ) { usage(); exit(1); }

  // Map text file read only
  if( (textfile = map_file( argv[0], 1 )) == NULL ) exit(1);

  indexsize = textfile->size < 32 ? 32 : textfile->size / 32;
  if( (index = malloc( sizeof(char *) * indexsize )) == NULL ) {
    fputs( "Could not allocate memory, exiting.\n", stderr);
    // unmap file and zero pointer
    unmap_file( &textfile );
    exit ( 1 );
 }

  // First line starts at begin of file.
  index[0] = textfile->addr;

  while( (c = nextchar()) != EOF ) {
    //         get linenumber, pass on eof test char
    long slen, lineno = acquire_lineno(c);
    unsigned char *line = scanforline( textfile, lineno, &slen );

    if( line && slen )
      fwrite( line, slen, 1, stdout );
    else
      putchar('\n');
  }

  // unmap file and zero pointer
  unmap_file( &textfile );
  return 0;
}