]> git.lizzy.rs Git - rust.git/blob - src/librustc_llvm/archive_ro.rs
auto merge of #15421 : catharsis/rust/doc-ffi-minor-fixes, r=alexcrichton
[rust.git] / src / librustc_llvm / archive_ro.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A wrapper around LLVM's archive (.a) code
12
13 use libc;
14 use ArchiveRef;
15
16 use std::raw;
17 use std::mem;
18
19 pub struct ArchiveRO {
20     ptr: ArchiveRef,
21 }
22
23 impl ArchiveRO {
24     /// Opens a static archive for read-only purposes. This is more optimized
25     /// than the `open` method because it uses LLVM's internal `Archive` class
26     /// rather than shelling out to `ar` for everything.
27     ///
28     /// If this archive is used with a mutable method, then an error will be
29     /// raised.
30     pub fn open(dst: &Path) -> Option<ArchiveRO> {
31         unsafe {
32             let ar = dst.with_c_str(|dst| {
33                 ::LLVMRustOpenArchive(dst)
34             });
35             if ar.is_null() {
36                 None
37             } else {
38                 Some(ArchiveRO { ptr: ar })
39             }
40         }
41     }
42
43     /// Reads a file in the archive
44     pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
45         unsafe {
46             let mut size = 0 as libc::size_t;
47             let ptr = file.with_c_str(|file| {
48                 ::LLVMRustArchiveReadSection(self.ptr, file, &mut size)
49             });
50             if ptr.is_null() {
51                 None
52             } else {
53                 Some(mem::transmute(raw::Slice {
54                     data: ptr,
55                     len: size as uint,
56                 }))
57             }
58         }
59     }
60 }
61
62 impl Drop for ArchiveRO {
63     fn drop(&mut self) {
64         unsafe {
65             ::LLVMRustDestroyArchive(self.ptr);
66         }
67     }
68 }