]> git.lyx.org Git - lyx.git/blob - src/support/lyxsum.C
the mmap patch
[lyx.git] / src / support / lyxsum.C
1 /* This file is part of
2  * ======================================================
3  * 
4  *           LyX, The Document Processor
5  *           Copyright 2001 The LyX Team.
6  *
7  * ======================================================
8  */
9
10
11 #include <config.h>
12
13 #include <algorithm>
14 #include <boost/crc.hpp>
15
16 #include "support/lyxlib.h"
17
18
19 // Various implementations of lyx::sum(), depending on what methods
20 // are available. Order is faster to slowest.
21 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
22 #ifdef WITH_WARNINGS
23 #warning lyx::sum() using mmap (lightning fast)
24 #endif
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <sys/mman.h>
31
32 unsigned long lyx::sum(string const & file)
33 {
34         int fd = open(file.c_str(), O_RDONLY);
35         if(!fd)
36                 return 0;
37         
38         struct stat info;
39         fstat(fd, &info);
40         
41         void * mm = mmap(0, info.st_size, PROT_READ,
42                          MAP_PRIVATE, fd, 0);
43         if (mm == MAP_FAILED) {
44                 close(fd);
45                 return 0;
46         }
47         
48         char * beg = static_cast<char*>(mm);
49         char * end = beg + info.st_size;
50         
51         boost::crc_32_type crc;
52         crc.process_block(beg, end);
53         unsigned long result = crc.checksum();
54         
55         munmap(mm, info.st_size);
56         close(fd);
57         
58         return result;
59 }
60 #else // No mmap
61
62 #include <fstream>
63 #include <iterator>
64
65 namespace {
66
67 template<typename InputIterator>
68 inline
69 unsigned long do_crc(InputIterator first, InputIterator last)
70 {
71         boost::crc_32_type crc;
72         crc = std::for_each(first, last, crc);
73         return crc.checksum();
74 }
75
76 } // namespace
77
78 #if HAVE_DECL_ISTREAMBUF_ITERATOR
79 #ifdef WITH_WARNINGS
80 #warning lyx::sum() using istreambuf_iterator (fast)
81 #endif
82 unsigned long lyx::sum(string const & file)
83 {
84         std::ifstream ifs(file.c_str());
85         if (!ifs) return 0;
86         
87         std::istreambuf_iterator<char> beg(ifs);
88         std::istreambuf_iterator<char> end;
89         
90         return do_crc(beg,end);
91 }
92 #else
93 #ifdef WITH_WARNINGS
94 #warning lyx::sum() using istream_iterator (slow as a snail)
95 #endif
96 unsigned long lyx::sum(string const & file)
97 {
98         std::ifstream ifs(file.c_str());
99         if (!ifs) return 0;
100         
101         ifs.unsetf(std::ios::skipws);
102         std::istream_iterator<char> beg(ifs);
103         std::istream_iterator<char> end;
104         
105         return do_crc(beg,end);
106 }
107 #endif
108 #endif // mmap