-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompOriginal.erl
74 lines (62 loc) · 2.51 KB
/
compOriginal.erl
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
-module(comp).
-export([comp/1, comp/2 , decomp/1, decomp/2]).
-define(DEFAULT_CHUNK_SIZE, 1024*1024).
%%% File Compression
comp(File) -> %% Compress file to file.ch
comp(File, ?DEFAULT_CHUNK_SIZE).
comp(File, Chunk_Size) -> %% Starts a reader and a writer which run in separate processes
case file_service:start_file_reader(File, Chunk_Size) of
{ok, Reader} ->
case archive:start_archive_writer(File++".ch") of
{ok, Writer} ->
comp_loop(Reader, Writer);
{error, Reason} ->
io:format("Could not open output file: ~w~n", [Reason])
end;
{error, Reason} ->
io:format("Could not open input file: ~w~n", [Reason])
end.
comp_loop(Reader, Writer) -> %% Compression loop => get a chunk, compress it, send to writer
Reader ! {get_chunk, self()}, %% request a chunk from the file reader
receive
{chunk, Num, Offset, Data} -> %% got one, compress and send to writer
Comp_Data = compress:compress(Data),
Writer ! {add_chunk, Num, Offset, Comp_Data},
comp_loop(Reader, Writer);
eof -> %% end of file, stop reader and writer
Writer ! stop;
{error, Reason} ->
io:format("Error reading input file: ~w~n",[Reason]),
Reader ! stop,
Writer ! abort
end.
%% File Decompression
decomp(Archive) ->
decomp(Archive, string:replace(Archive, ".ch", "", trailing)).
decomp(Archive, Output_File) ->
case archive:start_archive_reader(Archive) of
{ok, Reader} ->
case file_service:start_file_writer(Output_File) of
{ok, Writer} ->
decomp_loop(Reader, Writer);
{error, Reason} ->
io:format("Could not open output file: ~w~n", [Reason])
end;
{error, Reason} ->
io:format("Could not open input file: ~w~n", [Reason])
end.
decomp_loop(Reader, Writer) ->
Reader ! {get_chunk, self()}, %% request a chunk from the reader
receive
{chunk, _Num, Offset, Comp_Data} -> %% got one
Data = compress:decompress(Comp_Data),
Writer ! {write_chunk, Offset, Data},
decomp_loop(Reader, Writer);
eof -> %% end of file => exit decompression
Reader ! stop,
Writer ! stop;
{error, Reason} ->
io:format("Error reading input file: ~w~n", [Reason]),
Writer ! abort,
Reader ! stop
end.