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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. 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.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/encode/zlibstreams.h"
#include "gate/memalloc.h"
#include "gate/atomics.h"
#include "gate/results.h"
#include "gate/debugging.h"

#if defined(GATE_EXTLIB_ZLIB)
#	define GATE_ENCODE_ZLIBSTREAM_USE_ZLIB 1
#else
#	define GATE_ENCODE_ZLIBSTREAM_NO_IMPL 1
#endif

#if defined(GATE_ENCODE_ZLIBSTREAM_USE_ZLIB)

#include "zlib.h"

/* output stream encoder implementation */

static voidpf gate_zlibstream_alloc_func(voidpf opaque, uInt items, uInt size)
{
    voidpf ret;
    gate_size_t const mem_sz = (gate_size_t)items * (gate_size_t)size;
    (void)opaque;

    ret = gate_mem_alloc(mem_sz);
    if (!ret)
    {
        GATE_DEBUG_TRACE("ZLIB allocation failed");
    }
    else
    {
        gate_mem_clear(ret, mem_sz);
    }
    return ret;
}
static void gate_zlibstream_free_func(voidpf opaque, voidpf address)
{
    (void)opaque;
    if (address)
    {
        gate_mem_dealloc(address);
    }
}

static void gate_zlibencoder_release_impl(void* self);
static int gate_zlibencoder_retain_impl(void* self);
static char const* gate_zlibencoder_interface_name_impl(void* self)
{
    (void)self;
    return GATE_INTERFACE_NAME_STREAM;
}
static gate_result_t gate_zlibencoder_read_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned);
static gate_result_t gate_zlibencoder_peek_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned);
static gate_result_t gate_zlibencoder_write_impl(void* self, char const* buffer, gate_size_t bufferlength, gate_size_t* written);
static gate_result_t gate_zlibencoder_flush_impl(void* self);

static GATE_INTERFACE_VTBL(gate_stream) gate_zlibencoder_vtbl;
static void gate_init_zlibencoder_vtbl()
{
    if (!gate_zlibencoder_vtbl.get_interface_name)
    {
        GATE_INTERFACE_VTBL(gate_stream) const local_vtbl =
        {
            &gate_zlibencoder_interface_name_impl,
            &gate_zlibencoder_release_impl,
            &gate_zlibencoder_retain_impl,
            &gate_zlibencoder_read_impl,
            &gate_zlibencoder_peek_impl,
            &gate_zlibencoder_write_impl,
            &gate_zlibencoder_flush_impl
        };
        gate_zlibencoder_vtbl = local_vtbl;
    }
}

typedef struct gate_zlibencoder_impl
{
    GATE_INTERFACE_VTBL(gate_stream)* vtbl;

    gate_atomic_int_t	ref_counter;
    gate_stream_t* dest_stream;
    z_stream			zipper;
    char				data_buffer[GATE_MAX_BLOCK_COPYBUFFER_LENGTH];
    gate_size_t			data_buffer_used;

} gate_zlibencoder_impl_t;

gate_result_t gate_zlib_encoder_create(gate_stream_t* output, gate_bool_t gzformat, gate_int16_t compression, gate_stream_t** ptr2streamptr)
{
    gate_result_t ret;
    gate_zlibencoder_impl_t* impl;
    int zresult;
    int level = Z_DEFAULT_COMPRESSION;
#if defined(GATE_SYS_WINCE) || defined(GATE_SYS_DOS)
    int memlevel = MAX_MEM_LEVEL - 2;
    int window_bits = MAX_WBITS - 1;
#else
    int memlevel = MAX_MEM_LEVEL;
    int window_bits = MAX_WBITS;
#endif
    do
    {
        if ((output == NULL) || (ptr2streamptr == NULL))
        {
            GATE_DEBUG_TRACE("ZLIB encoder NULL pointer");
            ret = GATE_RESULT_NULLPOINTER;
            break;
        }
        impl = (gate_zlibencoder_impl_t*)gate_mem_alloc(sizeof(gate_zlibencoder_impl_t));
        if (impl == NULL)
        {
            GATE_DEBUG_TRACE("Failed to allocate ZLIB encoder");
            ret = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        gate_mem_clear(impl, sizeof(gate_zlibencoder_impl_t));
        gate_init_zlibencoder_vtbl();
        impl->vtbl = &gate_zlibencoder_vtbl;
        gate_atomic_int_init(&impl->ref_counter, 1);
        impl->dest_stream = output;

        switch (compression)
        {
        case GATE_ZLIB_COMPRESSION_MINIMUM:		level = Z_BEST_SPEED; break;
        case GATE_ZLIB_COMPRESSION_LOW:			level = (Z_BEST_SPEED + (Z_BEST_SPEED + Z_BEST_COMPRESSION) / 2) / 2; break;
        case GATE_ZLIB_COMPRESSION_MEDIUM:		level = (Z_BEST_SPEED + Z_BEST_COMPRESSION) / 2; break;
        case GATE_ZLIB_COMPRESSION_HIGH:		level = (Z_BEST_COMPRESSION + (Z_BEST_SPEED + Z_BEST_COMPRESSION) / 2) / 2; break;
        case GATE_ZLIB_COMPRESSION_MAXIMUM:		level = Z_BEST_COMPRESSION; break;
        }
        if (gzformat)
        {
            window_bits += 16;
        }

        impl->zipper.zalloc = &gate_zlibstream_alloc_func;
        impl->zipper.opaque = Z_NULL;
        impl->zipper.zfree = &gate_zlibstream_free_func;

        zresult = deflateInit2(&impl->zipper, level, Z_DEFLATED, window_bits, memlevel, Z_DEFAULT_STRATEGY);
        if (zresult != Z_OK)
        {
            GATE_DEBUG_TRACE_MSG_VALUE("deflateInit2() failed", zresult);
            gate_mem_dealloc(impl);
            ret = GATE_RESULT_FAILED;
            break;
        }

        impl->data_buffer_used = 0;

        gate_object_retain(impl->dest_stream);
        *ptr2streamptr = (gate_stream_t*)impl;

        ret = GATE_RESULT_OK;
    } while (0);

    return ret;

}

static void gate_zlibencoder_release_impl(void* self)
{
    gate_zlibencoder_impl_t* impl = (gate_zlibencoder_impl_t*)self;
    if (gate_atomic_int_dec(&impl->ref_counter) == 0)
    {
        gate_zlibencoder_flush_impl(self);
        deflateEnd(&impl->zipper);
        gate_object_release(impl->dest_stream);
        gate_mem_dealloc(impl);
    }
}
static int gate_zlibencoder_retain_impl(void* self)
{
    gate_zlibencoder_impl_t* impl = (gate_zlibencoder_impl_t*)self;
    return gate_atomic_int_inc(&impl->ref_counter);
}
static gate_result_t gate_zlibencoder_read_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned)
{
    (void)self;
    (void)buffer;
    (void)bufferlength;
    (void)returned;
    return GATE_RESULT_NOTSUPPORTED;
}
static gate_result_t gate_zlibencoder_peek_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned)
{
    (void)self;
    (void)buffer;
    (void)bufferlength;
    (void)returned;
    return GATE_RESULT_NOTSUPPORTED;
}
static gate_result_t gate_zlibencoder_write_impl(void* self, char const* buffer, gate_size_t bufferlength, gate_size_t* written)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_zlibencoder_impl_t* impl = (gate_zlibencoder_impl_t*)self;
    char compressed_buffer[GATE_MAX_STACK_COPYBUFFER_LENGTH];
    gate_size_t bytesavailable = sizeof(impl->data_buffer) - impl->data_buffer_used;
    gate_size_t bytesaccepted = bytesavailable < bufferlength ? bytesavailable : bufferlength;
    int zresult;
    gate_size_t bytescompressed;
    gate_size_t byteswritten;
    gate_size_t bytesremaining;

    do
    {
        gate_mem_copy(&impl->data_buffer[impl->data_buffer_used], buffer, bytesaccepted);
        if (written != NULL)
        {
            *written = bytesaccepted;
        }
        impl->data_buffer_used += bytesaccepted;

        if (impl->data_buffer_used == 0)
        {
            GATE_DEBUG_TRACE("zlibencoder_write data_buffer_used==0");
            ret = GATE_RESULT_INVALIDARG;
            break;
        }

        impl->zipper.avail_in = (uInt)impl->data_buffer_used;
        impl->zipper.next_in = (Bytef*)&impl->data_buffer[0];

        while (impl->zipper.avail_in != 0)
        {
            impl->zipper.avail_out = sizeof(compressed_buffer);
            impl->zipper.next_out = (Bytef*)&compressed_buffer[0];

            zresult = deflate(&impl->zipper, Z_NO_FLUSH);
            if ((zresult != Z_OK) && (zresult != Z_STREAM_END))
            {
                GATE_DEBUG_TRACE_MSG_VALUE("deflate() failed", zresult);
                ret = GATE_RESULT_FAILED;
                break;
            }
            bytescompressed = sizeof(compressed_buffer) - impl->zipper.avail_out;
            if (bytescompressed > 0)
            {
                ret = gate_stream_write_block(impl->dest_stream, &compressed_buffer[0], bytescompressed, &byteswritten);
                if (GATE_FAILED(ret))
                {
                    GATE_DEBUG_TRACE_MSG_VALUE("zlib_encoder_write write_block failed", ret);
                    break;
                }
            }
            else
            {
                break;
            }
        }

        if (impl->zipper.avail_in != 0)
        {
            bytesremaining = impl->zipper.avail_in;
            gate_mem_move(&impl->data_buffer[0], &impl->data_buffer[impl->data_buffer_used - bytesremaining], bytesremaining);
            impl->data_buffer_used = bytesremaining;
        }
        else
        {
            impl->data_buffer_used = 0;
        }
    } while (0);
    return ret;
}
static gate_result_t gate_zlibencoder_flush_impl(void* self)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_zlibencoder_impl_t* impl = (gate_zlibencoder_impl_t*)self;
    char compressed_buffer[GATE_MAX_STACK_COPYBUFFER_LENGTH];
    int zresult;
    gate_size_t bytescompressed;
    gate_size_t byteswritten;
    gate_size_t bytesoffset;

    do
    {
        impl->zipper.next_in = (Bytef*)&impl->data_buffer[0];
        impl->zipper.avail_in = (uInt)impl->data_buffer_used;

        impl->zipper.avail_out = sizeof(compressed_buffer);
        impl->zipper.next_out = (Bytef*)&compressed_buffer[0];

        zresult = deflate(&impl->zipper, Z_FINISH);
        if ((zresult != Z_OK) && (zresult != Z_STREAM_END))
        {
            GATE_DEBUG_TRACE_MSG_VALUE("deflate(FINISH) failed", zresult);
            ret = GATE_RESULT_FAILED;
            break;
        }

        bytescompressed = sizeof(compressed_buffer) - impl->zipper.avail_out;
        ret = gate_stream_write_block(impl->dest_stream, compressed_buffer, bytescompressed, &byteswritten);
        if (GATE_FAILED(ret))
        {
            GATE_DEBUG_TRACE_MSG_VALUE("zlibencoder_flush write_block failed", ret);
            break;
        }

        if (impl->zipper.avail_in < impl->data_buffer_used)
        {
            bytesoffset = impl->data_buffer_used - impl->zipper.avail_in;
            gate_mem_move(&impl->data_buffer[0], &impl->data_buffer[bytesoffset], impl->zipper.avail_in);
            impl->data_buffer_used = impl->zipper.avail_in;
        }
    } while (impl->zipper.avail_out == 0);
    if (GATE_SUCCEEDED(ret))
    {
        ret = gate_stream_flush(impl->dest_stream);
    }
    return ret;
}




/* input stream decoder implementation */

static void gate_zlibdecoder_release_impl(void* self);
static int gate_zlibdecoder_retain_impl(void* self);
static char const* gate_zlibdecoder_interface_name_impl(void* self);

static gate_result_t gate_zlibdecoder_read_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned);
static gate_result_t gate_zlibdecoder_peek_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned);
static gate_result_t gate_zlibdecoder_write_impl(void* self, char const* buffer, gate_size_t bufferlength, gate_size_t* written);
static gate_result_t gate_zlibdecoder_flush_impl(void* self);

static gate_result_t gate_zlibdecoder_get_resource_impl(void* self, gate_enumint_t resource_type, gate_uintptr_t* resource);

static gate_result_t gate_zlibdecoder_can_read_impl(void* self, gate_bool_t* return_value);
static gate_result_t gate_zlibdecoder_can_write_impl(void* self, gate_bool_t* return_value);
static gate_result_t gate_zlibdecoder_get_size_impl(void* self, gate_int64_t* return_value);
static gate_result_t gate_zlibdecoder_get_available_impl(void* self, gate_int64_t* return_value);
static gate_result_t gate_zlibdecoder_seek_impl(void* self, gate_int64_t position, gate_enumint_t origin, gate_int64_t* final_position);
static gate_result_t gate_zlibdecoder_reset_impl(void* self);
static gate_result_t gate_zlibdecoder_close_impl(void* self, gate_enumint_t close_type);

static GATE_INTERFACE_VTBL(gate_controlstream) gate_zlibdecoder_vtbl;
static void gate_init_zlibdecoder_vtbl()
{
    if (!gate_zlibdecoder_vtbl.get_interface_name)
    {
        static GATE_INTERFACE_VTBL(gate_controlstream) local_vtbl =
        {
            &gate_zlibdecoder_interface_name_impl,
            &gate_zlibdecoder_release_impl,
            &gate_zlibdecoder_retain_impl,

            &gate_zlibdecoder_read_impl,
            &gate_zlibdecoder_peek_impl,
            &gate_zlibdecoder_write_impl,
            &gate_zlibdecoder_flush_impl,

            &gate_zlibdecoder_get_resource_impl,

            &gate_zlibdecoder_can_read_impl,
            &gate_zlibdecoder_can_write_impl,
            &gate_zlibdecoder_get_size_impl,
            &gate_zlibdecoder_get_available_impl,
            &gate_zlibdecoder_seek_impl,
            &gate_zlibdecoder_reset_impl,
            &gate_zlibdecoder_close_impl
        };
        gate_zlibdecoder_vtbl = local_vtbl;
    }
}

typedef struct gate_zlibdecoder_impl
{
    GATE_INTERFACE_VTBL(gate_controlstream)* vtbl;

    gate_atomic_int_t	ref_counter;	/* reference counter */
    gate_stream_t* source_stream;	/* source stream to deliver compressed data */
    z_stream			unzipper;		/* unzip processing instance */
    char				source_buffer[GATE_MAX_BLOCK_COPYBUFFER_LENGTH];	/* internal source-stream input buffer */
    char				decoded_buffer[GATE_MAX_BLOCK_COPYBUFFER_LENGTH];	/* internal output buffer */
    gate_size_t			decoded_buffer_length;	/* current amount of valid bytes in decoded_buffer */
    gate_size_t			decoded_buffer_offset;	/* current start offset of valid bytes in decoded_buffer */
    gate_uint64_t		bytes_decoded_counter;	/* sum of bytes that were sucessfully decompressed */
    gate_uint64_t		total_bytes_uncompressed;	/* estimated total sum of bytes after decompression (incorrect if original data was greater 2^32 bytes) */

} gate_zlibdecoder_impl_t;

static gate_bool_t gate_zlib_decoder_get_content_length(gate_stream_t* stream, gate_uint64_t* ptr_length)
{
    gate_bool_t ret = false;
    gate_controlstream_t* ctrl = NULL;
    gate_int64_t start_pos;
    gate_int64_t avail;
    gate_int64_t end_pos;
    gate_result_t result;
    char header[10] = { 0 };
    char tail[8] = { 0 };
    gate_size_t received;
    gate_uint32_t uncompressed_size;

    do
    {
        if (!gate_object_implements_interface((gate_object_t*)stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
        {
            break;
        }

        ctrl = (gate_controlstream_t*)stream;

        result = gate_stream_peek(stream, header, sizeof(header), NULL);
        GATE_BREAK_IF_FAILED(result);

        if ((header[0] != (char)0x01f) || (header[1] != (char)0x08b) /*|| (header[0] != 8)*/)
        {
            break;
        }

        result = gate_stream_get_position(ctrl, &start_pos);
        GATE_BREAK_IF_FAILED(result);

        result = gate_stream_get_available(ctrl, &avail);
        GATE_BREAK_IF_FAILED(result);

        if (avail < sizeof(tail))
        {
            break;
        }

        end_pos = start_pos + avail;

        /* jump to end of file to read tail-bytes */
        result = gate_stream_seek(ctrl, end_pos - sizeof(tail), GATE_STREAM_SEEK_BEGIN, NULL);
        GATE_BREAK_IF_FAILED(result);

        result = gate_stream_peek(stream, tail, sizeof(tail), &received);<--- Variable 'result' is reassigned a value before the old one has been used.

        /* jump back to begin of stream */
        result = gate_stream_seek(ctrl, start_pos, GATE_STREAM_SEEK_BEGIN, NULL);<--- Variable 'result' is reassigned a value before the old one has been used.
        GATE_BREAK_IF_FAILED(result);

        uncompressed_size = ((gate_uint32_t)(gate_uint8_t)tail[4])
            | (((gate_uint32_t)(gate_uint8_t)tail[5]) << 8)
            | (((gate_uint32_t)(gate_uint8_t)tail[6]) << 16)
            | (((gate_uint32_t)(gate_uint8_t)tail[7]) << 24)
            ;
        *ptr_length = uncompressed_size;
        ret = true;
    } while (0);

    return ret;

}

gate_result_t gate_zlib_decoder_create(gate_stream_t* input, gate_bool_t gzformat, gate_stream_t** ptr2streamptr)
{
    gate_result_t ret;
    gate_zlibdecoder_impl_t* impl;
    int zresult;

    do
    {
        if ((input == NULL) || (ptr2streamptr == NULL))
        {
            ret = GATE_RESULT_NULLPOINTER;
            break;
        }
        impl = (gate_zlibdecoder_impl_t*)gate_mem_alloc(sizeof(gate_zlibdecoder_impl_t));
        if (impl == NULL)
        {
            GATE_DEBUG_TRACE("failed to allocate zlibdecoder");
            ret = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        gate_mem_clear(impl, sizeof(gate_zlibdecoder_impl_t));
        gate_init_zlibdecoder_vtbl();
        impl->vtbl = &gate_zlibdecoder_vtbl;
        gate_atomic_int_init(&impl->ref_counter, 1);
        impl->source_stream = input;

        gate_zlib_decoder_get_content_length(input, &impl->total_bytes_uncompressed);

        impl->unzipper.zalloc = &gate_zlibstream_alloc_func;
        impl->unzipper.opaque = Z_NULL;
        impl->unzipper.zfree = &gate_zlibstream_free_func;

        zresult = inflateInit2(&impl->unzipper, (gzformat == true ? MAX_WBITS + 32 : MAX_WBITS));
        if (zresult != Z_OK)
        {
            GATE_DEBUG_TRACE_MSG_VALUE("inflateInit2() failed", zresult);
            gate_mem_dealloc(impl);
            ret = GATE_RESULT_FAILED;
            break;
        }

        gate_object_retain(impl->source_stream);
        *ptr2streamptr = (gate_stream_t*)impl;

        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}


static char const* gate_zlibdecoder_interface_name_impl(void* self)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    if (gate_object_implements_interface((gate_object_t*)impl->source_stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
    {
        return GATE_INTERFACE_NAME_CONTROLSTREAM;
    }
    return GATE_INTERFACE_NAME_STREAM;
}

static void gate_zlibdecoder_release_impl(void* self)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    if (gate_atomic_int_dec(&impl->ref_counter) == 0)
    {
        inflateEnd(&impl->unzipper);
        gate_object_release(impl->source_stream);
        gate_mem_dealloc(impl);
    }
}
static int gate_zlibdecoder_retain_impl(void* self)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    return gate_atomic_int_inc(&impl->ref_counter);
}

static gate_result_t gate_zlibdecoder_peek_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;

    gate_bool_t end_of_stream = false;
    gate_size_t bytecount;
    gate_result_t result;
    gate_size_t diff;
    int zresult;

    while ((impl->decoded_buffer_length == 0) && (!end_of_stream))
    {
        if (impl->unzipper.avail_in == 0)
        {
            result = gate_stream_read(impl->source_stream, impl->source_buffer, sizeof(impl->source_buffer), &bytecount);
            if (GATE_FAILED(result))
            {
                GATE_DEBUG_TRACE_MSG_VALUE("zlibdecoder_peek stream_read failed", result);
                return result;
            }
            if (bytecount == 0)
            {
                break;
            }
            impl->unzipper.next_in = (Bytef*)&impl->source_buffer[0];
            impl->unzipper.avail_in = (uInt)bytecount;
        }


        impl->unzipper.avail_out = sizeof(impl->decoded_buffer);
        impl->unzipper.next_out = (Bytef*)(&impl->decoded_buffer[0]);

        zresult = inflate(&impl->unzipper, Z_NO_FLUSH);

        switch (zresult)
        {
        case Z_STREAM_ERROR:
        case Z_NEED_DICT:
        case Z_DATA_ERROR:
        case Z_MEM_ERROR:
        {
            GATE_DEBUG_TRACE_MSG_VALUE("inflate() failed", zresult);
            return GATE_RESULT_FAILED;
        }
        case Z_STREAM_END:
        {
            end_of_stream = true;
            break;
        }
        case Z_BUF_ERROR:
        {
            /* ignore */
            GATE_DEBUG_BREAKPOINT;
            break;
        }
        case Z_OK:
        {
            /* success -> continue */
            break;
        }
        }

        GATE_DEBUG_ASSERT(sizeof(impl->decoded_buffer) >= impl->unzipper.avail_out);
        diff = sizeof(impl->decoded_buffer) - impl->unzipper.avail_out;
        impl->decoded_buffer_length = diff;
        impl->decoded_buffer_offset = 0;
    }

    if (bufferlength < impl->decoded_buffer_length)
    {
        gate_mem_copy(buffer, &impl->decoded_buffer[impl->decoded_buffer_offset], bufferlength);
        if (returned != NULL)
        {
            *returned = bufferlength;
        }
    }
    else
    {
        if (impl->decoded_buffer_length > 0)
        {
            gate_mem_copy(buffer, &impl->decoded_buffer[impl->decoded_buffer_offset], impl->decoded_buffer_length);
        }
        if (returned != NULL)
        {
            *returned = impl->decoded_buffer_length;
        }
    }
    return GATE_RESULT_OK;
}

static gate_result_t gate_zlibdecoder_read_impl(void* self, char* buffer, gate_size_t bufferlength, gate_size_t* returned)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    gate_size_t tmp = 0;
    gate_result_t ret = gate_zlibdecoder_peek_impl(self, buffer, bufferlength, &tmp);
    if (returned != NULL)
    {
        *returned = tmp;
    }
    if (GATE_SUCCEEDED(ret))
    {
        impl->decoded_buffer_offset += tmp;
        impl->decoded_buffer_length -= tmp;
        impl->bytes_decoded_counter += tmp;
    }
    return ret;
}

static gate_result_t gate_zlibdecoder_write_impl(void* self, char const* buffer, gate_size_t bufferlength, gate_size_t* written)
{
    GATE_UNUSED_ARG(self);
    GATE_UNUSED_ARG(buffer);
    GATE_UNUSED_ARG(bufferlength);
    GATE_UNUSED_ARG(written);
    return GATE_RESULT_NOTSUPPORTED;
}

static gate_result_t gate_zlibdecoder_flush_impl(void* self)
{
    GATE_UNUSED_ARG(self);
    return GATE_RESULT_NOTSUPPORTED;
}

static gate_result_t gate_zlibdecoder_get_resource_impl(void* self, gate_enumint_t resource_type, gate_uintptr_t* resource)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    gate_controlstream_t* ctrl;

    if (gate_object_implements_interface((gate_object_t*)impl->source_stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
    {
        ctrl = (gate_controlstream_t*)impl->source_stream;
        return gate_stream_get_resource(ctrl, resource_type, resource);
    }
    return GATE_RESULT_NOTSUPPORTED;
}

static gate_result_t gate_zlibdecoder_can_read_impl(void* self, gate_bool_t* return_value)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    gate_controlstream_t* ctrl;

    if (gate_object_implements_interface((gate_object_t*)impl->source_stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
    {
        ctrl = (gate_controlstream_t*)impl->source_stream;
        return gate_stream_can_read(ctrl, return_value);
    }
    return GATE_RESULT_NOTSUPPORTED;
}

static gate_result_t gate_zlibdecoder_can_write_impl(void* self, gate_bool_t* return_value)
{
    GATE_UNUSED_ARG(self);
    if (return_value)
    {
        *return_value = false;
    }
    return GATE_RESULT_OK;
}

static gate_result_t gate_zlibdecoder_get_size_impl(void* self, gate_int64_t* return_value)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    gate_controlstream_t* ctrl;

    if (gate_object_implements_interface((gate_object_t*)impl->source_stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
    {
        ctrl = (gate_controlstream_t*)impl->source_stream;
        if (return_value)
        {
            *return_value = (gate_int64_t)impl->total_bytes_uncompressed;
        }
        return GATE_RESULT_OK;
    }
    return GATE_RESULT_NOTSUPPORTED;
}

static gate_result_t gate_zlibdecoder_get_available_impl(void* self, gate_int64_t* return_value)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    gate_controlstream_t* ctrl;

    if (gate_object_implements_interface((gate_object_t*)impl->source_stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
    {
        ctrl = (gate_controlstream_t*)impl->source_stream;
        if (return_value)
        {
            if (impl->total_bytes_uncompressed >= impl->bytes_decoded_counter)
            {
                *return_value = (gate_int64_t)impl->total_bytes_uncompressed - impl->bytes_decoded_counter;
            }
            else
            {
                *return_value = 0;
            }
        }
        return GATE_RESULT_OK;
    }
    return GATE_RESULT_NOTSUPPORTED;
}


static gate_result_t gate_zlibdecoder_seek_impl(void* self, gate_int64_t position, gate_enumint_t origin, gate_int64_t* final_position)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    if ((origin == GATE_STREAM_SEEK_CURRENT) && (position == 0))
    {
        /* special case: return current position in decoded stream (no change at all) */
        if (final_position)
        {
            *final_position = (gate_int64_t)impl->bytes_decoded_counter;
        }
        return GATE_RESULT_OK;
    }
    return GATE_RESULT_NOTSUPPORTED;
}


static gate_result_t gate_zlibdecoder_reset_impl(void* self)
{
    GATE_UNUSED_ARG(self);
    return GATE_RESULT_NOTSUPPORTED;
}


static gate_result_t gate_zlibdecoder_close_impl(void* self, gate_enumint_t close_type)
{
    gate_zlibdecoder_impl_t* impl = (gate_zlibdecoder_impl_t*)self;
    gate_controlstream_t* ctrl;

    if (gate_object_implements_interface((gate_object_t*)impl->source_stream, GATE_INTERFACE_NAME_CONTROLSTREAM))
    {
        ctrl = (gate_controlstream_t*)impl->source_stream;
        return gate_stream_close(ctrl, close_type);
    }
    return GATE_RESULT_NOTSUPPORTED;
}

#endif /* GATE_ENCODE_ZLIBSTREAM_USE_ZLIB */


#if defined(GATE_ENCODE_ZLIBSTREAM_NO_IMPL)

gate_result_t gate_zlib_encoder_create(gate_stream_t* output, gate_bool_t gzformat,
    gate_int16_t compression, gate_stream_t** ptr2streamptr)
{
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_zlib_decoder_create(gate_stream_t* input, gate_bool_t gzformat,
    gate_stream_t** ptr2streamptr)
{
    return GATE_RESULT_NOTIMPLEMENTED;
}

#endif /* GATE_ENCODE_ZLIBSTREAM_NO_IMPL */