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.
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.
11 //! A wrapper around LLVM's archive (.a) code
15 use std::ffi::CString;
21 pub struct ArchiveRO { ptr: ArchiveRef }
24 archive: &'a ArchiveRO,
25 ptr: ::ArchiveIteratorRef,
28 pub struct Child<'a> {
29 ptr: ::ArchiveChildRef,
30 _data: marker::PhantomData<&'a ArchiveRO>,
34 /// Opens a static archive for read-only purposes. This is more optimized
35 /// than the `open` method because it uses LLVM's internal `Archive` class
36 /// rather than shelling out to `ar` for everything.
38 /// If this archive is used with a mutable method, then an error will be
40 pub fn open(dst: &Path) -> Option<ArchiveRO> {
42 let s = path2cstr(dst);
43 let ar = ::LLVMRustOpenArchive(s.as_ptr());
47 Some(ArchiveRO { ptr: ar })
52 fn path2cstr(p: &Path) -> CString {
53 use std::os::unix::prelude::*;
55 let p: &OsStr = p.as_ref();
56 CString::new(p.as_bytes()).unwrap()
59 fn path2cstr(p: &Path) -> CString {
60 CString::new(p.to_str().unwrap()).unwrap()
64 pub fn raw(&self) -> ArchiveRef { self.ptr }
66 pub fn iter(&self) -> Iter {
68 Iter { ptr: ::LLVMRustArchiveIteratorNew(self.ptr), archive: self }
73 impl Drop for ArchiveRO {
76 ::LLVMRustDestroyArchive(self.ptr);
81 impl<'a> Iterator for Iter<'a> {
82 type Item = Child<'a>;
84 fn next(&mut self) -> Option<Child<'a>> {
85 let ptr = unsafe { ::LLVMRustArchiveIteratorNext(self.ptr) };
89 Some(Child { ptr: ptr, _data: marker::PhantomData })
94 impl<'a> Drop for Iter<'a> {
97 ::LLVMRustArchiveIteratorFree(self.ptr);
103 pub fn name(&self) -> Option<&'a str> {
105 let mut name_len = 0;
106 let name_ptr = ::LLVMRustArchiveChildName(self.ptr, &mut name_len);
107 if name_ptr.is_null() {
110 let name = slice::from_raw_parts(name_ptr as *const u8,
112 str::from_utf8(name).ok().map(|s| s.trim())
117 pub fn data(&self) -> &'a [u8] {
119 let mut data_len = 0;
120 let data_ptr = ::LLVMRustArchiveChildData(self.ptr, &mut data_len);
121 if data_ptr.is_null() {
122 panic!("failed to read data from archive child");
124 slice::from_raw_parts(data_ptr as *const u8, data_len as usize)
128 pub fn raw(&self) -> ::ArchiveChildRef { self.ptr }
131 impl<'a> Drop for Child<'a> {
133 unsafe { ::LLVMRustArchiveChildFree(self.ptr); }