Source

dark-hammer / src / core / file-mgr.c

The branch '0.4.7' does not exist.
  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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
/***********************************************************************************
 * Copyright (c) 2012, Sepehr Taghdisian
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 *
 ***********************************************************************************/
#include <stdio.h>

#include "file-mgr.h"
#include "mem-mgr.h"
#include "err.h"
#include "numeric.h"
#include "str.h"
#include "pak-file.h"
#include "mutex.h"
#include "thread.h"
#include "log.h"
#include "hash-table.h"
#include "atomic.h"

#include "efsw/efsw.h"

#define MEM_BLOCK_SIZE  4096
#define MON_BUFFER_SIZE (256*1024)
#define MON_ITEM_SIZE 200
#define MON_DIR_MAX (DH_PATH_MAX/2)

/*************************************************************************************************
 * types 
 */
/* callbacks and declerations for read/write to different file types */
typedef size_t (*pfnio_file_read)(file_t f, void* buffer, size_t item_size, size_t items_cnt);
typedef size_t (*pfnio_file_write)(file_t f, const void* buffer, size_t item_size, size_t items_cnt);

struct vdir
{
    bool_t monitor;
    char path[DH_PATH_MAX];
    efsw_watchid watchid;
    mutex_t mtx;
    atomptr_t backbuff;
    atomptr_t frontbuff;
    struct array backarr;  /* item: char[DH_PATH_MAX] */
    struct array frontarr; /* item: char[DH_PATH_MAX] */
};

struct mon_item
{
    pfn_filechange_callback fn;
    reshandle_t hdl;    /* possible resource handle */
    uptr_t param1;
    uptr_t param2;
};

/**
 * file manager that handles virtual-filesystems and pool allocators for file io\n
 * virtual-filesystems are either virtual-directories or 'pak' file archives
 */
struct file_mgr
{
    bool_t init;
    struct pool_alloc diskfile_alloc;
    struct pool_alloc memfile_alloc;
    struct array vdirs;   /* item: vdir */
    struct array paks;    /* item: pak_file */
    mutex_t lock;   /* for multi-threaded file creation */
    struct hashtable_open mon_table;    /* key: filepath(hashed), value: pointer to mon_item */
    efsw_watcher watcher;
};

struct file_header
{
    enum file_type type;
    char path[DH_PATH_MAX];
    size_t size;
    enum file_mode mode;
    pfnio_file_read read_fn;
    pfnio_file_write write_fn;
};

struct disk_file
{
    FILE* file;
};

struct mem_file
{
    struct allocator* alloc;
    uint8* buffer;
    size_t offset;
    size_t max_size;
    uint32 mem_id;
};

/*************************************************************************************************/
/* callbacks for directory monitoring */
result_t io_mon_init(void* pt);
void io_mon_release(void* pt);
result_t io_mon_kernel(void* pt);

size_t io_file_readdisk(file_t f, void* buffer, size_t item_size, size_t items_cnt);
size_t io_file_writedisk(file_t f, const void* buffer, size_t item_size, size_t items_cnt);
size_t io_file_readmem(file_t f, void* buffer, size_t item_size, size_t items_cnt);
size_t io_file_writemem(file_t f, const void* buffer, size_t item_size, size_t items_cnt);

void io_init_vdir(struct vdir* vd, const char* directory, bool_t monitor);
void io_release_vdir(struct vdir* vd);

/* resolve and open a filepath from the disk */
FILE* open_resolvepath(const char* filepath);

bool_t io_find_file(const struct array* files, const char* filepath);

/*************************************************************************************************
 * globals 
 */
static struct file_mgr g_fmgr;

/*************************************************************************************************/
result_t io_initfilemgr()
{
    memset(&g_fmgr, 0x00, sizeof(struct file_mgr));

    result_t r;
    
    r = mem_pool_create(mem_heap(), &g_fmgr.diskfile_alloc, 
                        sizeof(struct file_header) + sizeof(struct disk_file), 20, 0);
    if (IS_FAIL(r))   {
        err_printn(__FILE__, __LINE__, r);
        return r;
    }
    
    r = mem_pool_create(mem_heap(), &g_fmgr.memfile_alloc, 
                        sizeof(struct file_header) + sizeof(struct mem_file), 20, 0);
    if (IS_FAIL(r))   {
        err_printn(__FILE__, __LINE__, r);
        return r;
    }
    
    r = arr_create(mem_heap(), &g_fmgr.vdirs, sizeof(struct vdir), 5, 5, 0);
    if (IS_FAIL(r))     {
        err_printn(__FILE__, __LINE__, r);
        return r;
    }
    
    r = arr_create(mem_heap(), &g_fmgr.paks, sizeof(struct pak_file*), 5, 5, 0);
    if (IS_FAIL(r))     {
        err_printn(__FILE__, __LINE__, r);
        return r;
    }

    r = hashtable_open_create(mem_heap(), &g_fmgr.mon_table, MON_ITEM_SIZE, MON_ITEM_SIZE, 0);
    if (IS_FAIL(r)) {
        err_printn(__FILE__, __LINE__, r);
        return r;
    }

    mt_createmutex(&g_fmgr.lock);
    g_fmgr.init = TRUE;
    return RET_OK;
}

void io_releasefilemgr()
{
    /* search for remaining registered monitor items and delete them */
    uint32 cnt = 0;
    for (uint32 i = 0; i < g_fmgr.mon_table.slots_cnt; i++) {
        struct hashtable_item* item = &g_fmgr.mon_table.slots[i];
        if (item->hash != 0)    {
            struct mon_item* mitem = (struct mon_item*)item->value;
            FREE(mitem);
            cnt ++;
        }
    }

#if defined(_DEBUG_)
    if (cnt > 0)
        log_printf(LOG_INFO, "file-mgr: destroyed %d file monitors", cnt);
#endif

    /* */
    io_clearvdirs();
    g_fmgr.init = FALSE;

    if (g_fmgr.watcher != NULL)
        efsw_destroy(g_fmgr.watcher);

    hashtable_open_destroy(&g_fmgr.mon_table);
    mt_destroymutex(&g_fmgr.lock);
    arr_destroy(&g_fmgr.vdirs);
    arr_destroy(&g_fmgr.paks);
    mem_pool_destroy(&g_fmgr.memfile_alloc);
    mem_pool_destroy(&g_fmgr.diskfile_alloc);
    memset(&g_fmgr, 0x00, sizeof(struct file_mgr));
}

void io_addvdir(const char* directory, bool_t monitor)
{
    ASSERT(directory);
    ASSERT(directory[0] != 0);
    ASSERT(g_fmgr.init);
    
    io_init_vdir((struct vdir*)arr_add(&g_fmgr.vdirs), directory, monitor);
}

void io_clearvdirs()
{
    for (uint32 i = 0; i < g_fmgr.vdirs.item_cnt; i++)  {
        struct vdir* vd = &((struct vdir*)g_fmgr.vdirs.buffer)[i];
        io_release_vdir(vd);
    }
    arr_clear(&g_fmgr.vdirs);
}

void io_addpak(struct pak_file* pak)
{
    ASSERT(pak);
    ASSERT(pak_isopen(pak));
    
    struct pak_file** ppaks = (struct pak_file**)arr_add(&g_fmgr.paks);
    ASSERT(ppaks);
    *ppaks = pak;
}

void io_clearpaks()
{
    arr_clear(&g_fmgr.paks);
}

file_t io_file_createmem(struct allocator* alloc, const char* name, uint32 mem_id)
{
    mt_lockmutex(&g_fmgr.lock);
    uint8* file_buf = (uint8*)mem_pool_alloc(&g_fmgr.memfile_alloc);
    mt_unlockmutex(&g_fmgr.lock);

    if (file_buf == NULL)   
        return FILE_NULL;
    memset(file_buf, 0x00, g_fmgr.memfile_alloc.item_sz);
    
    struct file_header* header = (struct file_header*)file_buf;
    struct mem_file* f = (struct mem_file*)(file_buf + sizeof(struct file_header));
    
    /* header */
    header->type = FILE_TYPE_MEM;
    strcpy(header->path, name);
    header->size = 0;
    header->mode = FILE_MODE_WRITE;
    header->write_fn = io_file_writemem;    
    
    /* data */
    f->buffer = (uint8*)A_ALLOC(alloc, MEM_BLOCK_SIZE, mem_id);
    if (f->buffer == NULL)  {
        mt_lockmutex(&g_fmgr.lock);
        mem_pool_free(&g_fmgr.memfile_alloc, file_buf);
        mt_unlockmutex(&g_fmgr.lock);
        return FILE_NULL;
    }
    f->alloc = alloc;
    f->max_size = MEM_BLOCK_SIZE;
    f->offset = 0;
    f->mem_id = mem_id;
    
    return file_buf;    
}

file_t io_file_openmem(struct allocator* alloc, const char* filepath, 
                       bool_t ignore_vfs, uint32 mem_id)
{
    /* if memory file is requested and we have pak files, first try loading from paks */
    if (!ignore_vfs && !arr_isempty(&g_fmgr.paks))    {
        struct pak_file** paks = (struct pak_file**)g_fmgr.paks.buffer;
        uint32 paks_cnt = g_fmgr.paks.item_cnt;
        for (uint32 i = 0; i < paks_cnt; i++)   {
            uint32 file_id = pak_findfile(paks[i], filepath);
            if (file_id != INVALID_INDEX)
                return pak_getfile(paks[i], alloc, mem_heap(), file_id, mem_id);
        }
    }
    
    /* continue opening a file from disk and load it into memory */
    mt_lockmutex(&g_fmgr.lock);
    uint8* file_buf = (uint8*)mem_pool_alloc(&g_fmgr.memfile_alloc);
    mt_unlockmutex(&g_fmgr.lock);

    if (file_buf == NULL)
    	return FILE_NULL;
    memset(file_buf, 0x00, g_fmgr.memfile_alloc.item_sz);
    
    struct file_header* header = (struct file_header*)file_buf;
    struct mem_file* f = (struct mem_file*)(file_buf + sizeof(struct file_header));

    FILE* ff = (!ignore_vfs && !arr_isempty(&g_fmgr.vdirs)) ? open_resolvepath(filepath) : 
               fopen(filepath, "rb");    
    if (ff == NULL)     {
        mt_lockmutex(&g_fmgr.lock);
        mem_pool_free(&g_fmgr.memfile_alloc, file_buf);
        mt_unlockmutex(&g_fmgr.lock);

        return FILE_NULL;
    }

    /* header */
    header->type = FILE_TYPE_MEM;
    strcpy(header->path, filepath);
    header->mode = FILE_MODE_READ;

    fseek(ff, 0, SEEK_END);
    header->size = ftell(ff);
    fseek(ff, 0, SEEK_SET);
    header->read_fn = io_file_readmem;
    
    /* data */
    f->buffer = (uint8*)A_ALLOC(alloc, header->size, mem_id);
    if (f->buffer == NULL)  {
        fclose(ff);
        mt_lockmutex(&g_fmgr.lock);
        mem_pool_free(&g_fmgr.memfile_alloc, file_buf);
        mt_unlockmutex(&g_fmgr.lock);
        return FILE_NULL;
    }
    fread(f->buffer, header->size, 1, ff);
    f->alloc = alloc;
    f->max_size = header->size;
    f->offset = 0;
    f->mem_id = mem_id;
    
    fclose(ff);    
    return file_buf;    
}

file_t io_file_attachmem(struct allocator* alloc, void* buffer, 
                         size_t size, const char* name, uint32 mem_id)
{
    mt_lockmutex(&g_fmgr.lock);
    uint8* file_buf = (uint8*)mem_pool_alloc(&g_fmgr.memfile_alloc);
    mt_unlockmutex(&g_fmgr.lock);

    if (file_buf == NULL)   
        return FILE_NULL;
    memset(file_buf, 0x00, g_fmgr.memfile_alloc.item_sz);
    
    struct file_header* header = (struct file_header*)file_buf;
    struct mem_file* f = (struct mem_file*)(file_buf + sizeof(struct file_header));
    
    /* header  */
    header->type = FILE_TYPE_MEM;
    strcpy(header->path, name);
    header->mode = FILE_MODE_READ;
    header->size = size;
    header->read_fn = io_file_readmem;
    
    /* data */
    f->alloc = alloc;
    f->mem_id = mem_id;
    f->buffer = (uint8*)buffer;
    f->max_size = size;
    f->offset = 0;
    
    return file_buf;
}

void* io_file_detachmem(file_t f, size_t* outsize, struct allocator** palloc)
{
    struct file_header* header = (struct file_header*)f;
    struct mem_file* fdata = (struct mem_file*)((uint8*)f + sizeof(struct file_header));
    
    if (fdata->buffer == NULL)      
        return NULL;
    
    void* buffer = fdata->buffer;
    *outsize = header->size;

    if (palloc != NULL)
        *palloc = fdata->alloc;

    memset(fdata, 0x00, sizeof(struct mem_file));    
    return buffer;
}

file_t io_file_createdisk(const char* filepath)
{
    mt_lockmutex(&g_fmgr.lock);
    uint8* file_buf = (uint8*)mem_pool_alloc(&g_fmgr.diskfile_alloc);
    mt_unlockmutex(&g_fmgr.lock);

    if (file_buf == NULL)   
        return FILE_NULL;
    memset(file_buf, 0x00, g_fmgr.diskfile_alloc.item_sz);
    
    struct file_header* header = (struct file_header*)file_buf;
    struct disk_file* f = (struct disk_file*)(file_buf + sizeof(struct file_header));
    
    /* header */
    header->type = FILE_TYPE_DSK;
    header->mode = FILE_MODE_WRITE;
    strcpy(header->path, filepath);
    header->size = 0;
    header->write_fn = io_file_writedisk;
    
    /* data */
    f->file = fopen(filepath, "wb");
    if (f->file == NULL)    {
        mt_lockmutex(&g_fmgr.lock);
        mem_pool_free(&g_fmgr.diskfile_alloc, file_buf);
        mt_unlockmutex(&g_fmgr.lock);
        return FILE_NULL;
    }
   
    return file_buf;
}

file_t io_file_opendisk(const char* filepath, bool_t ignore_vfs)
{
    mt_lockmutex(&g_fmgr.lock);
    uint8* file_buf = (uint8*)mem_pool_alloc(&g_fmgr.diskfile_alloc);
    mt_unlockmutex(&g_fmgr.lock);

    if (file_buf == NULL)   
        return FILE_NULL;
    memset(file_buf, 0x00, g_fmgr.diskfile_alloc.item_sz);
    
    struct file_header* header = (struct file_header*)file_buf;
    struct disk_file* f = (struct disk_file*)(file_buf + sizeof(struct file_header));
    
    /* header */
    header->type = FILE_TYPE_DSK;
    header->mode = FILE_MODE_READ;
    strcpy(header->path, filepath);
    header->read_fn = io_file_readdisk;
    
    /* data */
    f->file = (!ignore_vfs && !arr_isempty(&g_fmgr.vdirs)) ? open_resolvepath(filepath) : 
        fopen(filepath, "rb");
    if (f->file == NULL)    {
        mt_lockmutex(&g_fmgr.lock);
        mem_pool_free(&g_fmgr.diskfile_alloc, file_buf);
        mt_unlockmutex(&g_fmgr.lock);
        return FILE_NULL;
    }
    
    /* size */
    fseek(f->file, 0, SEEK_END);
    header->size = ftell(f->file);
    fseek(f->file, 0, SEEK_SET);
   
    return file_buf;    
}

FILE* open_resolvepath(const char* filepath)
{
    ASSERT(g_fmgr.init);
    struct vdir* vds = (struct vdir*)g_fmgr.vdirs.buffer;
    char testpath[DH_PATH_MAX];
    FILE* f = NULL;
    
    uint32 item_cnt = g_fmgr.vdirs.item_cnt;
    for (uint32 i = 0; i < item_cnt; i++)   {
        struct vdir* vd = &vds[i];
        path_join(testpath, vd->path, filepath, NULL);
        f = fopen(testpath, "rb");
        if (f != NULL)      
            return f;
    }
    
    return NULL;
}

void io_file_close(file_t f)
{
    ASSERT(f != NULL);
    
    struct file_header* header = (struct file_header*)f;

    mt_lockmutex(&g_fmgr.lock);
    if (header->type == FILE_TYPE_MEM)   {
        struct mem_file* fdata = (struct mem_file*)((uint8*)f + sizeof(struct file_header));
        if (fdata->buffer != NULL)  {
            A_FREE(fdata->alloc, fdata->buffer);
        }
        mem_pool_free(&g_fmgr.memfile_alloc, f);    
        memset(f, 0x00, g_fmgr.memfile_alloc.item_sz);
    }    else if (header->type == FILE_TYPE_DSK)    {
        struct disk_file* fdata = (struct disk_file*)((uint8*)f + sizeof(struct file_header));
        if (fdata->file != NULL)    {
            fclose(fdata->file);
        }
        mem_pool_free(&g_fmgr.diskfile_alloc, f);    
        memset(f, 0x00, g_fmgr.diskfile_alloc.item_sz);
    }
    mt_unlockmutex(&g_fmgr.lock);
}


void io_file_seek(file_t f, enum seek_mode seek, int32 offset)
{
    ASSERT(f != NULL);
    
    struct file_header* header = (struct file_header*)f;
    
    if (header->type == FILE_TYPE_MEM)   {
        struct mem_file* fdata = (struct mem_file*)((uint8*)f + sizeof(struct file_header));
        switch (seek)   {
            case SEEK_MODE_CUR:
                fdata->offset += offset;
                break;
            case SEEK_MODE_START:
                fdata->offset = offset;
                break;
            case SEEK_MODE_END:
                ASSERT(offset > 0);
                fdata->offset = header->size - offset;
                break;
        }
        fdata->offset = clampsz(fdata->offset, 0, header->size);
    }    else if (header->type == FILE_TYPE_DSK)    {
        struct disk_file* fdata = (struct disk_file*)((uint8*)f + sizeof(struct file_header));
        int32 seek_std;
        switch (seek)   {
            case SEEK_MODE_CUR:     seek_std = SEEK_CUR;    break;
            case SEEK_MODE_START:   seek_std = SEEK_SET;    break;
            case SEEK_MODE_END:     seek_std = SEEK_END;    break;
            default:				seek_std = SEEK_SET;	break;
        }
        fseek(fdata->file, offset, seek_std);       
    }
}

size_t io_file_read(file_t f, void* buffer, size_t item_size, size_t items_cnt)
{
    ASSERT(f != NULL);
    struct file_header* header = (struct file_header*)f;
    return header->read_fn(f, buffer, item_size, items_cnt);
}

size_t io_file_write(file_t f, const void* buffer, size_t item_size, size_t items_cnt)
{
    ASSERT(f != NULL);
    struct file_header* header = (struct file_header*)f;
    return header->write_fn(f, buffer, item_size, items_cnt);
}

size_t io_file_readdisk(file_t f, void* buffer, size_t item_size, size_t items_cnt)
{
    struct disk_file* fdata = (struct disk_file*)((uint8*)f + sizeof(struct file_header));
    return fread(buffer, item_size, items_cnt, fdata->file);
}

size_t io_file_writedisk(file_t f, const void* buffer, size_t item_size, size_t items_cnt)
{
    struct disk_file* fdata = (struct disk_file*)((uint8*)f + sizeof(struct file_header));
    return fwrite(buffer, item_size, items_cnt, fdata->file);
}

size_t io_file_readmem(file_t f, void* buffer, size_t item_size, size_t items_cnt)
{
    struct file_header* header = (struct file_header*)f;
    struct mem_file* fdata = (struct mem_file*)((uint8*)f + sizeof(struct file_header));
    size_t read_sz = item_size * items_cnt;
    if ((read_sz + fdata->offset) > header->size)   {
        read_sz = header->size - fdata->offset;
        read_sz -= (read_sz % item_size);
    }
    if (read_sz != 0)   {
        memcpy(buffer, fdata->buffer + fdata->offset, read_sz);
        fdata->offset += read_sz;
    }
    return (read_sz/item_size);
}

size_t io_file_writemem(file_t f, const void* buffer, size_t item_size, size_t items_cnt)
{
    struct file_header* header = (struct file_header*)f;
    struct mem_file* fdata = (struct mem_file*)((uint8*)f + sizeof(struct file_header));
    
    size_t write_sz = item_size * items_cnt;
    size_t offset = fdata->offset;    
    
    /* grow buffer if necessary */
    if ((write_sz + offset) > fdata->max_size)   {
        size_t grow_sz = write_sz + offset - fdata->max_size;
        size_t expand_sz = ((grow_sz/MEM_BLOCK_SIZE) + 1)*MEM_BLOCK_SIZE;
        
        void* tmp = A_ALLOC(fdata->alloc, expand_sz + fdata->max_size, fdata->mem_id);
        if (tmp == NULL)    return 0;
        memcpy(tmp, fdata->buffer, header->size);
        A_FREE(fdata->alloc, fdata->buffer);
        fdata->buffer = (uint8*)tmp;
        
        fdata->max_size += expand_sz;        
    }
    
    if ((offset + write_sz) > header->size)  {
        header->size = offset + write_sz;
    }

    memcpy(fdata->buffer + offset, buffer, write_sz);
    fdata->offset += write_sz;
    return items_cnt;
}

size_t io_file_getsize(file_t f)
{
    struct file_header* header = (struct file_header*)f;
    return header->size;
}

size_t io_file_getpos(file_t f)
{
    struct file_header* header = (struct file_header*)f;
    if (header->type == FILE_TYPE_MEM)   {
        struct mem_file* fdata = (struct mem_file*)((uint8*)f + sizeof(struct file_header));
        return fdata->offset;
    }    else if (header->type == FILE_TYPE_DSK)    {
        struct disk_file* fdata = (struct disk_file*)((uint8*)f + sizeof(struct file_header));
        return ftell(fdata->file);
    }
    return 0;
}

const char* io_file_getpath(file_t f)
{
    struct file_header* header = (struct file_header*)f;
    return header->path;
}

bool_t io_file_isopen(file_t f)
{
    struct file_header* header = (struct file_header*)f;
    if (header->type == FILE_TYPE_MEM)   {
        struct mem_file* fdata = (struct mem_file*)((uint8*)f + sizeof(struct file_header));
        return (fdata->buffer != NULL);
    }    else if (header->type == FILE_TYPE_DSK)    {
        struct disk_file* fdata = (struct disk_file*)((uint8*)f + sizeof(struct file_header));
        return (fdata->file != NULL);
    }
    return FALSE;
}

enum file_type io_file_gettype(file_t f)
{
    struct file_header* header = (struct file_header*)f;
    return header->type;
}

enum file_mode io_file_getmode(file_t f)
{
    struct file_header* header = (struct file_header*)f;
    return header->mode;
}

void io_mon_callback(efsw_watcher watcher,
    efsw_watchid watchid, const char* dir, const char* filename,
    enum efsw_action action, const char* old_filename, void* param)
{
    if (action == EFSW_MODIFIED || action == EFSW_MOVED)    {
        struct vdir* vd = (struct vdir*)param;
        
        mt_lockmutex(&vd->mtx);
        struct array* arr = (struct array*)vd->backbuff;
        char* filepath = (char*)arr_add(arr);
        ASSERT(filepath);
        path_tounix(filepath, filename);
        mt_unlockmutex(&vd->mtx);
    }
}

void io_init_vdir(struct vdir* vd, const char* directory, bool_t monitor)
{
    memset(vd, 0x00, sizeof(struct vdir));
    vd->monitor = monitor;
    path_norm(vd->path, directory);

    if (monitor)    {
        if (g_fmgr.watcher == NULL) {
            g_fmgr.watcher = efsw_create(FALSE);
            if (g_fmgr.watcher == NULL) {
                log_print(LOG_WARNING, "file-mgr: could not init file monitoring");
                return;
            }
        }

        mt_createmutex(&vd->mtx);

        arr_create(mem_heap(), &vd->backarr, DH_PATH_MAX, 10, 10, 0);
        arr_create(mem_heap(), &vd->frontarr, DH_PATH_MAX, 10, 10, 0);
        vd->frontbuff = &vd->frontarr;
        vd->backbuff = &vd->backarr;

        vd->watchid = efsw_addwatch(g_fmgr.watcher, vd->path, io_mon_callback, TRUE, vd);
        if (vd->watchid == -1)
            log_printf(LOG_WARNING, "file-mgr: %s", efsw_getlasterror());

        efsw_watch(g_fmgr.watcher);
    }
}

void io_release_vdir(struct vdir* vd)
{
    if (vd->monitor)    {
        ASSERT(g_fmgr.watcher);
        efsw_removewatch_byid(g_fmgr.watcher, vd->watchid);

        mt_destroymutex(&vd->mtx);

        arr_destroy(&vd->backarr);
        arr_destroy(&vd->frontarr);

        vd->frontbuff = NULL;
        vd->backbuff = NULL;
    }
}

void io_mon_update()
{
    /* move through vdirs and look for changes within their file-system */
    for (uint32 i = 0; i < g_fmgr.vdirs.item_cnt; i++)  {
        struct vdir* vd = &((struct vdir*)g_fmgr.vdirs.buffer)[i];
        if (!vd->monitor)
            continue;

        /* swap back_arr with front_arr
         * use mutex to ensure that we don't swap back/front in the middle of adding */
        mt_lockmutex(&vd->mtx);
        swapptr((void**)&vd->backbuff, (void**)&vd->frontbuff);
        mt_unlockmutex(&vd->mtx);

        /* check with registered file items and see we have a match */
        struct array* arr = (struct array*)vd->frontbuff;
        for (uint32 c = 0; c < arr->item_cnt; c++)  {
            const char* filepath = ((char*)arr->buffer) + c*DH_PATH_MAX;

            struct hashtable_item* item = hashtable_open_find(&g_fmgr.mon_table,
                hashtable_str(filepath));
            if (item != NULL)   {
                struct mon_item* mitem = (struct mon_item*)item->value;
                puts(filepath);
                mitem->fn(filepath, mitem->hdl, mitem->param1, mitem->param2);
            }
        }

        arr_clear(arr);
    }
}

bool_t io_find_file(const struct array* files, const char* filepath)
{
    for (uint32 i = 0; i < files->item_cnt; i++)    {
        const char* f = ((char*)files->buffer) + i*DH_PATH_MAX;
        if (str_isequal(f, filepath))
            return TRUE;
    }
    return FALSE;
}

void io_mon_reg(const char* filepath, pfn_filechange_callback fn, reshandle_t hdl, 
    uptr_t param1, uptr_t param2)
{
    struct mon_item* mitem = (struct mon_item*)ALLOC(sizeof(struct mon_item), 0);
    ASSERT(mitem);
    mitem->fn = fn;
    mitem->hdl = hdl;
    mitem->param1 = param1;
    mitem->param2 = param2;

    hashtable_open_add(&g_fmgr.mon_table, hashtable_str(filepath), (uint64)((uptr_t)mitem));
}

void io_mon_unreg(const char* filepath)
{
    struct hashtable_item* item = hashtable_open_find(&g_fmgr.mon_table, hashtable_str(filepath));
    if (item != NULL)   {
        hashtable_open_remove(&g_fmgr.mon_table, item);
        struct mon_item* mitem = (struct mon_item*)item->value;
        FREE(mitem);
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.