aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorLoïc Hoguin <[email protected]>2025-01-22 11:50:38 +0100
committerLoïc Hoguin <[email protected]>2025-01-22 11:59:23 +0100
commita136a1d063cc4e40e818726eab05adc827832684 (patch)
tree077e46315c7890a9fe7a18e1064b92300cc3f2fb /src
parent144c7eebe2eff19ed5ddc156a6d02941ce0aaee1 (diff)
downloadcowlib-a136a1d063cc4e40e818726eab05adc827832684.tar.gz
cowlib-a136a1d063cc4e40e818726eab05adc827832684.tar.bz2
cowlib-a136a1d063cc4e40e818726eab05adc827832684.zip
Add cow_deflate:inflate/3
This function can be used to safely inflate data up to a given limit. It has been extracted from the cowboy_decompress_h module.
Diffstat (limited to 'src')
-rw-r--r--src/cow_deflate.erl39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/cow_deflate.erl b/src/cow_deflate.erl
new file mode 100644
index 0000000..051c8e4
--- /dev/null
+++ b/src/cow_deflate.erl
@@ -0,0 +1,39 @@
+%% Copyright (c) 2024-2025, jdamanalo <[email protected]>
+%% Copyright (c) 2024-2025, Loïc Hoguin <[email protected]>
+%%
+%% Permission to use, copy, modify, and/or distribute this software for any
+%% purpose with or without fee is hereby granted, provided that the above
+%% copyright notice and this permission notice appear in all copies.
+%%
+%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+-module(cow_deflate).
+
+-export([inflate/3]).
+
+-spec inflate(zlib:zstream(), iodata(), non_neg_integer() | infinity)
+ -> {ok, binary()} | {error, data_error | size_error}.
+
+inflate(Z, Data, Limit) ->
+ try
+ {Status, Output} = zlib:safeInflate(Z, Data),
+ do_inflate(Z, iolist_size(Output), Limit, Status, [Output])
+ catch
+ error:data_error ->
+ {error, data_error}
+ end.
+
+do_inflate(_, Size, Limit, _, _) when Size > Limit ->
+ {error, size_error};
+do_inflate(Z, Size0, Limit, continue, Acc) ->
+ {Status, Output} = zlib:safeInflate(Z, []),
+ Size = Size0 + iolist_size(Output),
+ do_inflate(Z, Size, Limit, Status, [Output | Acc]);
+do_inflate(_, _, _, finished, Acc) ->
+ {ok, iolist_to_binary(lists:reverse(Acc))}.