<commit_before>use crate::core::{GitReference, PackageId, SourceId};
use crate::sources::git;
use crate::sources::registry::download;
use crate::sources::registry::MaybeLock;
use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
use crate::util::errors::CargoResult;
use crate::util::interning::InternedString;
use crate::util::{Config, Filesystem};
use anyhow::Context as _;
use cargo_util::paths;
use lazycell::LazyCell;
use log::{debug, trace};
use std::cell::{Cell, Ref, RefCell};
use std::fs::File;
use std::mem;
use std::path::Path;
use std::str;
use std::task::{ready, Poll};

/// A remote registry is a registry that lives at a remote URL (such as
/// crates.io). The git index is cloned locally, and `.crate` files are
/// downloaded as needed and cached locally.
pub struct RemoteRegistry<'cfg> {
    index_path: Filesystem,
    /// Path to the cache of `.crate` files (`$CARGO_HOME/registry/path/$REG-HASH`).
    cache_path: Filesystem,
    source_id: SourceId,
    index_git_ref: GitReference,
    config: &'cfg Config,
    tree: RefCell<Option<git2::Tree<'static>>>,
    repo: LazyCell<git2::Repository>,
    head: Cell<Option<git2::Oid>>,
    current_sha: Cell<Option<InternedString>>,
    needs_update: bool, // Does this registry need to be updated?
    updated: bool,      // Has this registry been updated this session?
}

impl<'cfg> RemoteRegistry<'cfg> {
    pub fn new(source_id: SourceId, config: &'cfg Config, name: &str) -> RemoteRegistry<'cfg> {
        RemoteRegistry {
            index_path: config.registry_index_path().join(name),
            cache_path: config.registry_cache_path().join(name),
            source_id,
            config,
            // TODO: we should probably make this configurable
            index_git_ref: GitReference::DefaultBranch,
            tree: RefCell::new(None),
            repo: LazyCell::new(),
            head: Cell::new(None),
            current_sha: Cell::new(None),
            needs_update: false,
            updated: false,
        }
    }

    fn repo(&self) -> CargoResult<&git2::Repository> {
        self.repo.try_borrow_with(|| {
            let path = self.config.assert_package_cache_locked(&self.index_path);

            // Fast path without a lock
            if let Ok(repo) = git2::Repository::open(&path) {
                trace!("opened a repo without a lock");
                return Ok(repo);
            }

            // Ok, now we need to lock and try the whole thing over again.
            trace!("acquiring registry index lock");
            match git2::Repository::open(&path) {
                Ok(repo) => Ok(repo),
                Err(_) => {
                    drop(paths::remove_dir_all(&path));
                    paths::create_dir_all(&path)?;

                    // Note that we'd actually prefer to use a bare repository
                    // here as we're not actually going to check anything out.
                    // All versions of Cargo, though, share the same CARGO_HOME,
                    // so for compatibility with older Cargo which *does* do
                    // checkouts we make sure to initialize a new full
                    // repository (not a bare one).
                    //
                    // We should change this to `init_bare` whenever we feel
                    // like enough time has passed or if we change the directory
                    // that the folder is located in, such as by changing the
                    // hash at the end of the directory.
                    //
                    // Note that in the meantime we also skip `init.templatedir`
                    // as it can be misconfigured sometimes or otherwise add
                    // things that we don't want.
                    let mut opts = git2::RepositoryInitOptions::new();
                    opts.external_template(false);
                    Ok(git2::Repository::init_opts(&path, &opts).with_context(|| {
                        format!("failed to initialize index git repository (in {:?})", path)
                    })?)
                }
            }
        })
    }

    fn head(&self) -> CargoResult<git2::Oid> {
        if self.head.get().is_none() {
            let repo = self.repo()?;
            let oid = self.index_git_ref.resolve(repo)?;
            self.head.set(Some(oid));
        }
        Ok(self.head.get().unwrap())
    }

    fn tree(&self) -> CargoResult<Ref<'_, git2::Tree<'_>>> {
        {
            let tree = self.tree.borrow();
            if tree.is_some() {
                return Ok(Ref::map(tree, |s| s.as_ref().unwrap()));
            }
        }
        let repo = self.repo()?;
        let commit = repo.find_commit(self.head()?)?;
        let tree = commit.tree()?;

        // Unfortunately in libgit2 the tree objects look like they've got a
        // reference to the repository object which means that a tree cannot
        // outlive the repository that it came from. Here we want to cache this
        // tree, though, so to accomplish this we transmute it to a static
        // lifetime.
        //
        // Note that we don't actually hand out the static lifetime, instead we
        // only return a scoped one from this function. Additionally the repo
        // we loaded from (above) lives as long as this object
        // (`RemoteRegistry`) so we then just need to ensure that the tree is
        // destroyed first in the destructor, hence the destructor on
        // `RemoteRegistry` below.
        let tree = unsafe { mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) };
        *self.tree.borrow_mut() = Some(tree);
        Ok(Ref::map(self.tree.borrow(), |s| s.as_ref().unwrap()))
    }

    fn current_version(&self) -> Option<InternedString> {
        if let Some(sha) = self.current_sha.get() {
            return Some(sha);
        }
        let sha = InternedString::new(&self.head().ok()?.to_string());
        self.current_sha.set(Some(sha));
        Some(sha)
    }
}

const LAST_UPDATED_FILE: &str = ".last-updated";

impl<'cfg> RegistryData for RemoteRegistry<'cfg> {
    fn prepare(&self) -> CargoResult<()> {
        self.repo()?; // create intermediate dirs and initialize the repo
        Ok(())
    }

    fn index_path(&self) -> &Filesystem {
        &self.index_path
    }

    fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path {
        self.config.assert_package_cache_locked(path)
    }

    // `index_version` Is a string representing the version of the file used to construct the cached copy.
    // Older versions of Cargo used the single value of the hash of the HEAD commit as a `index_version`.
    // This is technically correct but a little too conservative. If a new commit is fetched all cached
    // files need to be regenerated even if a particular file was not changed.
    // However if an old cargo has written such a file we still know how to read it, as long as we check for that hash value.
    //
    // Cargo now uses a hash of the file's contents as provided by git.
    fn load(
        &mut self,
        _root: &Path,
        path: &Path,
        index_version: Option<&str>,
    ) -> Poll<CargoResult<LoadResponse>> {
        if self.needs_update {
            return Poll::Pending;
        }
        // Check if the cache is valid.
        let git_commit_hash = self.current_version();
        if index_version.is_some() && index_version == git_commit_hash.as_deref() {
            // This file was written by an old version of cargo, but it is still up-to-date.
            return Poll::Ready(Ok(LoadResponse::CacheValid));
        }
        // Note that the index calls this method and the filesystem is locked
        // in the index, so we don't need to worry about an `update_index`
        // happening in a different process.
        fn load_helper(
            registry: &RemoteRegistry<'_>,
            path: &Path,
            index_version: Option<&str>,
        ) -> CargoResult<LoadResponse> {
            let repo = registry.repo()?;
            let tree = registry.tree()?;
            let entry = tree.get_path(path);
            let entry = entry?;
            let git_file_hash = Some(entry.id().to_string());

            // Check if the cache is valid.
            if index_version.is_some() && index_version == git_file_hash.as_deref() {
                return Ok(LoadResponse::CacheValid);
            }

            let object = entry.to_object(repo)?;
            let blob = match object.as_blob() {
                Some(blob) => blob,
                None => anyhow::bail!("path `{}` is not a blob in the git repo", path.display()),
            };

            Ok(LoadResponse::Data {
                raw_data: blob.content().to_vec(),
                index_version: git_file_hash,
            })
        }

        match load_helper(&self, path, index_version) {
            Ok(result) => Poll::Ready(Ok(result)),
            Err(_) if !self.updated => {
                // If git returns an error and we haven't updated the repo, return
                // pending to allow an update to try again.
                self.needs_update = true;
                Poll::Pending
            }
            Err(e)
                if e.downcast_ref::<git2::Error>()
                    .map(|e| e.code() == git2::ErrorCode::NotFound)
                    .unwrap_or_default() =>
            {
                // The repo has been updated and the file does not exist.
                Poll::Ready(Ok(LoadResponse::NotFound))
            }
            Err(e) => Poll::Ready(Err(e)),
        }
    }

    fn config(&mut self) -> Poll<CargoResult<Option<RegistryConfig>>> {
        debug!("loading config");
        self.prepare()?;
        self.config.assert_package_cache_locked(&self.index_path);
        match ready!(self.load(Path::new(""), Path::new("config.json"), None)?) {
            LoadResponse::Data { raw_data, .. } => {
                trace!("config loaded");
                Poll::Ready(Ok(Some(serde_json::from_slice(&raw_data)?)))
            }
            _ => Poll::Ready(Ok(None)),
        }
    }

    fn block_until_ready(&mut self) -> CargoResult<()> {
        if !self.needs_update {
            return Ok(());
        }

        self.updated = true;
        self.needs_update = false;

        if self.config.offline() {
            return Ok(());
        }
        if self.config.cli_unstable().no_index_update {
            return Ok(());
        }
        // Make sure the index is only updated once per session since it is an
        // expensive operation. This generally only happens when the resolver
        // is run multiple times, such as during `cargo publish`.
        if self.config.updated_sources().contains(&self.source_id) {
            return Ok(());
        }

        debug!("updating the index");

        // Ensure that we'll actually be able to acquire an HTTP handle later on
        // once we start trying to download crates. This will weed out any
        // problems with `.cargo/config` configuration related to HTTP.
        //
        // This way if there's a problem the error gets printed before we even
        // hit the index, which may not actually read this configuration.
        self.config.http()?;

        self.prepare()?;
        self.head.set(None);
        *self.tree.borrow_mut() = None;
        self.current_sha.set(None);
        let path = self.config.assert_package_cache_locked(&self.index_path);
        self.config
            .shell()
            .status("Updating", self.source_id.display_index())?;

        // Fetch the latest version of our `index_git_ref` into the index
        // checkout.
        let url = self.source_id.url();
        let repo = self.repo.borrow_mut().unwrap();
        git::fetch(repo, url.as_str(), &self.index_git_ref, self.config)
            .with_context(|| format!("failed to fetch `{}`", url))?;
        self.config.updated_sources().insert(self.source_id);

        // Create a dummy file to record the mtime for when we updated the
        // index.
        paths::create(&path.join(LAST_UPDATED_FILE))?;

        Ok(())
    }

    fn invalidate_cache(&mut self) {
        if !self.updated {
            self.needs_update = true;
        }
    }

    fn is_updated(&self) -> bool {
        self.updated
    }

    fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> {
        let registry_config = loop {
            match self.config()? {
                Poll::Pending => self.block_until_ready()?,
                Poll::Ready(cfg) => break cfg.unwrap(),
            }
        };

        download::download(
            &self.cache_path,
            &self.config,
            pkg,
            checksum,
            registry_config,
        )
    }

    fn finish_download(
        &mut self,
        pkg: PackageId,
        checksum: &str,
        data: &[u8],
    ) -> CargoResult<File> {
        download::finish_download(&self.cache_path, &self.config, pkg, checksum, data)
    }

    fn is_crate_downloaded(&self, pkg: PackageId) -> bool {
        download::is_crate_downloaded(&self.cache_path, &self.config, pkg)
    }
}

impl<'cfg> Drop for RemoteRegistry<'cfg> {
    fn drop(&mut self) {
        // Just be sure to drop this before our other fields
        self.tree.borrow_mut().take();
    }
}
<commit_msg>Auto merge of #11255 - epage:registry, r=arlosi<commit_after>use crate::core::{GitReference, PackageId, SourceId};
use crate::sources::git;
use crate::sources::registry::download;
use crate::sources::registry::MaybeLock;
use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
use crate::util::errors::CargoResult;
use crate::util::interning::InternedString;
use crate::util::{Config, Filesystem};
use anyhow::Context as _;
use cargo_util::paths;
use lazycell::LazyCell;
use log::{debug, trace};
use std::cell::{Cell, Ref, RefCell};
use std::fs::File;
use std::mem;
use std::path::Path;
use std::str;
use std::task::{ready, Poll};

/// A remote registry is a registry that lives at a remote URL (such as
/// crates.io). The git index is cloned locally, and `.crate` files are
/// downloaded as needed and cached locally.
pub struct RemoteRegistry<'cfg> {
    index_path: Filesystem,
    /// Path to the cache of `.crate` files (`$CARGO_HOME/registry/path/$REG-HASH`).
    cache_path: Filesystem,
    source_id: SourceId,
    index_git_ref: GitReference,
    config: &'cfg Config,
    tree: RefCell<Option<git2::Tree<'static>>>,
    repo: LazyCell<git2::Repository>,
    head: Cell<Option<git2::Oid>>,
    current_sha: Cell<Option<InternedString>>,
    needs_update: bool, // Does this registry need to be updated?
}

impl<'cfg> RemoteRegistry<'cfg> {
    pub fn new(source_id: SourceId, config: &'cfg Config, name: &str) -> RemoteRegistry<'cfg> {
        RemoteRegistry {
            index_path: config.registry_index_path().join(name),
            cache_path: config.registry_cache_path().join(name),
            source_id,
            config,
            // TODO: we should probably make this configurable
            index_git_ref: GitReference::DefaultBranch,
            tree: RefCell::new(None),
            repo: LazyCell::new(),
            head: Cell::new(None),
            current_sha: Cell::new(None),
            needs_update: false,
        }
    }

    fn repo(&self) -> CargoResult<&git2::Repository> {
        self.repo.try_borrow_with(|| {
            let path = self.config.assert_package_cache_locked(&self.index_path);

            // Fast path without a lock
            if let Ok(repo) = git2::Repository::open(&path) {
                trace!("opened a repo without a lock");
                return Ok(repo);
            }

            // Ok, now we need to lock and try the whole thing over again.
            trace!("acquiring registry index lock");
            match git2::Repository::open(&path) {
                Ok(repo) => Ok(repo),
                Err(_) => {
                    drop(paths::remove_dir_all(&path));
                    paths::create_dir_all(&path)?;

                    // Note that we'd actually prefer to use a bare repository
                    // here as we're not actually going to check anything out.
                    // All versions of Cargo, though, share the same CARGO_HOME,
                    // so for compatibility with older Cargo which *does* do
                    // checkouts we make sure to initialize a new full
                    // repository (not a bare one).
                    //
                    // We should change this to `init_bare` whenever we feel
                    // like enough time has passed or if we change the directory
                    // that the folder is located in, such as by changing the
                    // hash at the end of the directory.
                    //
                    // Note that in the meantime we also skip `init.templatedir`
                    // as it can be misconfigured sometimes or otherwise add
                    // things that we don't want.
                    let mut opts = git2::RepositoryInitOptions::new();
                    opts.external_template(false);
                    Ok(git2::Repository::init_opts(&path, &opts).with_context(|| {
                        format!("failed to initialize index git repository (in {:?})", path)
                    })?)
                }
            }
        })
    }

    fn head(&self) -> CargoResult<git2::Oid> {
        if self.head.get().is_none() {
            let repo = self.repo()?;
            let oid = self.index_git_ref.resolve(repo)?;
            self.head.set(Some(oid));
        }
        Ok(self.head.get().unwrap())
    }

    fn tree(&self) -> CargoResult<Ref<'_, git2::Tree<'_>>> {
        {
            let tree = self.tree.borrow();
            if tree.is_some() {
                return Ok(Ref::map(tree, |s| s.as_ref().unwrap()));
            }
        }
        let repo = self.repo()?;
        let commit = repo.find_commit(self.head()?)?;
        let tree = commit.tree()?;

        // Unfortunately in libgit2 the tree objects look like they've got a
        // reference to the repository object which means that a tree cannot
        // outlive the repository that it came from. Here we want to cache this
        // tree, though, so to accomplish this we transmute it to a static
        // lifetime.
        //
        // Note that we don't actually hand out the static lifetime, instead we
        // only return a scoped one from this function. Additionally the repo
        // we loaded from (above) lives as long as this object
        // (`RemoteRegistry`) so we then just need to ensure that the tree is
        // destroyed first in the destructor, hence the destructor on
        // `RemoteRegistry` below.
        let tree = unsafe { mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) };
        *self.tree.borrow_mut() = Some(tree);
        Ok(Ref::map(self.tree.borrow(), |s| s.as_ref().unwrap()))
    }

    fn current_version(&self) -> Option<InternedString> {
        if let Some(sha) = self.current_sha.get() {
            return Some(sha);
        }
        let sha = InternedString::new(&self.head().ok()?.to_string());
        self.current_sha.set(Some(sha));
        Some(sha)
    }

    fn is_updated(&self) -> bool {
        self.config.updated_sources().contains(&self.source_id)
    }

    fn mark_updated(&self) {
        self.config.updated_sources().insert(self.source_id);
    }
}

const LAST_UPDATED_FILE: &str = ".last-updated";

impl<'cfg> RegistryData for RemoteRegistry<'cfg> {
    fn prepare(&self) -> CargoResult<()> {
        self.repo()?; // create intermediate dirs and initialize the repo
        Ok(())
    }

    fn index_path(&self) -> &Filesystem {
        &self.index_path
    }

    fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path {
        self.config.assert_package_cache_locked(path)
    }

    // `index_version` Is a string representing the version of the file used to construct the cached copy.
    // Older versions of Cargo used the single value of the hash of the HEAD commit as a `index_version`.
    // This is technically correct but a little too conservative. If a new commit is fetched all cached
    // files need to be regenerated even if a particular file was not changed.
    // However if an old cargo has written such a file we still know how to read it, as long as we check for that hash value.
    //
    // Cargo now uses a hash of the file's contents as provided by git.
    fn load(
        &mut self,
        _root: &Path,
        path: &Path,
        index_version: Option<&str>,
    ) -> Poll<CargoResult<LoadResponse>> {
        if self.needs_update {
            return Poll::Pending;
        }
        // Check if the cache is valid.
        let git_commit_hash = self.current_version();
        if index_version.is_some() && index_version == git_commit_hash.as_deref() {
            // This file was written by an old version of cargo, but it is still up-to-date.
            return Poll::Ready(Ok(LoadResponse::CacheValid));
        }
        // Note that the index calls this method and the filesystem is locked
        // in the index, so we don't need to worry about an `update_index`
        // happening in a different process.
        fn load_helper(
            registry: &RemoteRegistry<'_>,
            path: &Path,
            index_version: Option<&str>,
        ) -> CargoResult<LoadResponse> {
            let repo = registry.repo()?;
            let tree = registry.tree()?;
            let entry = tree.get_path(path);
            let entry = entry?;
            let git_file_hash = Some(entry.id().to_string());

            // Check if the cache is valid.
            if index_version.is_some() && index_version == git_file_hash.as_deref() {
                return Ok(LoadResponse::CacheValid);
            }

            let object = entry.to_object(repo)?;
            let blob = match object.as_blob() {
                Some(blob) => blob,
                None => anyhow::bail!("path `{}` is not a blob in the git repo", path.display()),
            };

            Ok(LoadResponse::Data {
                raw_data: blob.content().to_vec(),
                index_version: git_file_hash,
            })
        }

        match load_helper(&self, path, index_version) {
            Ok(result) => Poll::Ready(Ok(result)),
            Err(_) if !self.is_updated() => {
                // If git returns an error and we haven't updated the repo, return
                // pending to allow an update to try again.
                self.needs_update = true;
                Poll::Pending
            }
            Err(e)
                if e.downcast_ref::<git2::Error>()
                    .map(|e| e.code() == git2::ErrorCode::NotFound)
                    .unwrap_or_default() =>
            {
                // The repo has been updated and the file does not exist.
                Poll::Ready(Ok(LoadResponse::NotFound))
            }
            Err(e) => Poll::Ready(Err(e)),
        }
    }

    fn config(&mut self) -> Poll<CargoResult<Option<RegistryConfig>>> {
        debug!("loading config");
        self.prepare()?;
        self.config.assert_package_cache_locked(&self.index_path);
        match ready!(self.load(Path::new(""), Path::new("config.json"), None)?) {
            LoadResponse::Data { raw_data, .. } => {
                trace!("config loaded");
                Poll::Ready(Ok(Some(serde_json::from_slice(&raw_data)?)))
            }
            _ => Poll::Ready(Ok(None)),
        }
    }

    fn block_until_ready(&mut self) -> CargoResult<()> {
        if !self.needs_update {
            return Ok(());
        }

        self.needs_update = false;

        // Make sure the index is only updated once per session since it is an
        // expensive operation. This generally only happens when the resolver
        // is run multiple times, such as during `cargo publish`.
        if self.is_updated() {
            return Ok(());
        }
        self.mark_updated();

        if self.config.offline() {
            return Ok(());
        }
        if self.config.cli_unstable().no_index_update {
            return Ok(());
        }

        debug!("updating the index");

        // Ensure that we'll actually be able to acquire an HTTP handle later on
        // once we start trying to download crates. This will weed out any
        // problems with `.cargo/config` configuration related to HTTP.
        //
        // This way if there's a problem the error gets printed before we even
        // hit the index, which may not actually read this configuration.
        self.config.http()?;

        self.prepare()?;
        self.head.set(None);
        *self.tree.borrow_mut() = None;
        self.current_sha.set(None);
        let path = self.config.assert_package_cache_locked(&self.index_path);
        self.config
            .shell()
            .status("Updating", self.source_id.display_index())?;

        // Fetch the latest version of our `index_git_ref` into the index
        // checkout.
        let url = self.source_id.url();
        let repo = self.repo.borrow_mut().unwrap();
        git::fetch(repo, url.as_str(), &self.index_git_ref, self.config)
            .with_context(|| format!("failed to fetch `{}`", url))?;

        // Create a dummy file to record the mtime for when we updated the
        // index.
        paths::create(&path.join(LAST_UPDATED_FILE))?;

        Ok(())
    }

    fn invalidate_cache(&mut self) {
        // To fully invalidate, undo `mark_updated`s work
        self.needs_update = true;
    }

    fn is_updated(&self) -> bool {
        self.is_updated()
    }

    fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> {
        let registry_config = loop {
            match self.config()? {
                Poll::Pending => self.block_until_ready()?,
                Poll::Ready(cfg) => break cfg.unwrap(),
            }
        };

        download::download(
            &self.cache_path,
            &self.config,
            pkg,
            checksum,
            registry_config,
        )
    }

    fn finish_download(
        &mut self,
        pkg: PackageId,
        checksum: &str,
        data: &[u8],
    ) -> CargoResult<File> {
        download::finish_download(&self.cache_path, &self.config, pkg, checksum, data)
    }

    fn is_crate_downloaded(&self, pkg: PackageId) -> bool {
        download::is_crate_downloaded(&self.cache_path, &self.config, pkg)
    }
}

impl<'cfg> Drop for RemoteRegistry<'cfg> {
    fn drop(&mut self) {
        // Just be sure to drop this before our other fields
        self.tree.borrow_mut().take();
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 Drew Short <drew@sothr.com>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::iter::range_step_inclusive;

/**
    Determines if a specified number is prime.

    # Arguments

    * 'num' - The number to check for primality

    # Examples

    ```rust
    use sothr_lib::prime_util::is_prime;
    assert_eq!(true, is_prime(1));
    assert_eq!(true, is_prime(5));
    assert_eq!(false, is_prime(6));
    assert_eq!(true, is_prime(6857));
    assert_eq!(false, is_prime(75031));
    ```
*/
pub fn is_prime(num: u64) -> bool {
    // 1-3 are prime numbers
    if num <= 3 {
        return true;
    }

    // numbers divisible by 2 and 3, but greater than 3 are not prime
    if num % 2 == 0 || num % 3 == 0 {
        return false;
    }

    // Check every number between i=5 and the square of i than is less than the
    // desired number
    let mut i = 5;
    while i*i < num {
    	// If the number is evenly divisible by i or i+2 it is not prime
        if num % i == 0 || num % (i+2) == 0 {
            return false;
        }
        // Increment by 6 because it is the product of 2 and 3. Therefore of
        // the numbers between 5 and 11 (i and i+6) only 5 and 7 could be prime
        // values. 6, 8, 9 and 10 are products or sums of 2 and 3.
        i += 6;
    }
    // If this far, then the number is definitively prime
    true
}

/**
  Generate a list of primes between 0 and the end value.

  # Arguments

  * 'look_until' - The end of the range to look for primes within

  # Examples

  ```rust
  use sothr_lib::prime_util::list_of_primes;
  let prime_list = vec![2,3,5,7,11];
  assert_eq!(prime_list, list_of_primes(12).expect("No Primes?!?!?"));
  ```
*/
pub fn list_of_primes(look_until: u64) -> Option<Vec<u64>> {
  if look_until < 2u64 {
    return None
  }

  let end = look_until as usize;

  //prepopulate the sieve
  let mut sieve: Vec<bool> = Vec::with_capacity(end/2);
  let mut i: usize = 0;
  while i < end {
    sieve.push(true);
    i += 1;
  }

  let f_look_until = look_until as f64;
  let estimate_of_primes = ((f_look_until / f_look_until.ln()) * (1f64 + (1.2762 / f_look_until.ln()))) as usize;
  let mut primes: Vec<u64> = Vec::with_capacity(estimate_of_primes);
  primes.push(2u64);

  let limit = ((f_look_until/2).sqrt() as usize) + 1;

  // in this lineup index 0 == 3
  // therefore index 1 == 5, 2 == 7, 3 == 9, etc...
  for i in 0..end/2 {
    if sieve[i] {
      primes.push((i+i+3) as u64);
      if i < limit {
        // selectively sieve out non primes. We're only concerned with odds as
        // we've already removed even values from the list.
        // i = 0, therefore i represents 3
        // i+i+3 = 3
        // simple proofs of odd counts
        // 0 1 2 3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
        //[3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49]
        //0,3,6,9,12 = <3>,9,15,21,27
        //1,6,11,16 = <5>,15,25,35
        //2,9,16,23 = <7>,21,35,49
        for j in range_step_inclusive(i+i+3, end-1, i+i+3) {
          sieve[j] = false;
        }
      }
    }
  }

  Some(primes)
}
<commit_msg>Fix for the division compilation error. Change was because we are only iterating over the odd items, we only need to look till the sqrt of half the end. The other half is ommited? Or maybe it was supposed to be half the square root. Will need to investigate this further.<commit_after>// Copyright 2015 Drew Short <drew@sothr.com>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::iter::range_step_inclusive;

/**
    Determines if a specified number is prime.

    # Arguments

    * 'num' - The number to check for primality

    # Examples

    ```rust
    use sothr_lib::prime_util::is_prime;
    assert_eq!(true, is_prime(1));
    assert_eq!(true, is_prime(5));
    assert_eq!(false, is_prime(6));
    assert_eq!(true, is_prime(6857));
    assert_eq!(false, is_prime(75031));
    ```
*/
pub fn is_prime(num: u64) -> bool {
    // 1-3 are prime numbers
    if num <= 3 {
        return true;
    }

    // numbers divisible by 2 and 3, but greater than 3 are not prime
    if num % 2 == 0 || num % 3 == 0 {
        return false;
    }

    // Check every number between i=5 and the square of i than is less than the
    // desired number
    let mut i = 5;
    while i*i < num {
    	// If the number is evenly divisible by i or i+2 it is not prime
        if num % i == 0 || num % (i+2) == 0 {
            return false;
        }
        // Increment by 6 because it is the product of 2 and 3. Therefore of
        // the numbers between 5 and 11 (i and i+6) only 5 and 7 could be prime
        // values. 6, 8, 9 and 10 are products or sums of 2 and 3.
        i += 6;
    }
    // If this far, then the number is definitively prime
    true
}

/**
  Generate a list of primes between 0 and the end value.

  # Arguments

  * 'look_until' - The end of the range to look for primes within

  # Examples

  ```rust
  use sothr_lib::prime_util::list_of_primes;
  let prime_list = vec![2,3,5,7,11];
  assert_eq!(prime_list, list_of_primes(12).expect("No Primes?!?!?"));
  ```
*/
pub fn list_of_primes(look_until: u64) -> Option<Vec<u64>> {
  if look_until < 2u64 {
    return None
  }

  let end = look_until as usize;

  //prepopulate the sieve
  let mut sieve: Vec<bool> = Vec::with_capacity(end/2);
  let mut i: usize = 0;
  while i < end {
    sieve.push(true);
    i += 1;
  }

  let f_look_until = look_until as f64;
  let estimate_of_primes = ((f_look_until / f_look_until.ln()) * (1f64 + (1.2762 / f_look_until.ln()))) as usize;
  let mut primes: Vec<u64> = Vec::with_capacity(estimate_of_primes);
  primes.push(2u64);

  let limit = (((look_until/2) as f64).sqrt() as usize) + 1;

  // in this lineup index 0 == 3
  // therefore index 1 == 5, 2 == 7, 3 == 9, etc...
  for i in 0..end/2 {
    if sieve[i] {
      primes.push((i+i+3) as u64);
      if i < limit {
        // selectively sieve out non primes. We're only concerned with odds as
        // we've already removed even values from the list.
        // i = 0, therefore i represents 3
        // i+i+3 = 3
        // simple proofs of odd counts
        // 0 1 2 3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
        //[3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49]
        //0,3,6,9,12 = <3>,9,15,21,27
        //1,6,11,16 = <5>,15,25,35
        //2,9,16,23 = <7>,21,35,49
        for j in range_step_inclusive(i+i+3, end-1, i+i+3) {
          sieve[j] = false;
        }
      }
    }
  }

  Some(primes)
}
<|endoftext|>


<commit_before>use crate::common::{Encoding, Format};
use crate::read::{Error, Reader, Result};

#[derive(Debug, Clone, Copy)]
pub(crate) struct ListsHeader {
    encoding: Encoding,
    offset_entry_count: u32,
}

impl Default for ListsHeader {
    fn default() -> Self {
        ListsHeader {
            encoding: Encoding {
                format: Format::Dwarf32,
                version: 5,
                address_size: 0,
            },
            offset_entry_count: 0,
        }
    }
}

impl ListsHeader {
    /// Return the serialized size of the table header.
    #[allow(dead_code)]
    #[inline]
    fn size(self) -> u8 {
        // initial_length + version + address_size + segment_selector_size + offset_entry_count
        ListsHeader::size_for_encoding(self.encoding)
    }

    /// Return the serialized size of the table header.
    #[inline]
    pub(crate) fn size_for_encoding(encoding: Encoding) -> u8 {
        // initial_length + version + address_size + segment_selector_size + offset_entry_count
        encoding.format.initial_length_size() + 2 + 1 + 1 + 4
    }
}

// TODO: add an iterator over headers in the appropriate sections section
#[allow(dead_code)]
fn parse_header<R: Reader>(input: &mut R) -> Result<ListsHeader> {
    let (length, format) = input.read_initial_length()?;
    input.truncate(length)?;

    let version = input.read_u16()?;
    if version != 5 {
        return Err(Error::UnknownVersion(u64::from(version)));
    }

    let address_size = input.read_u8()?;
    let segment_selector_size = input.read_u8()?;
    if segment_selector_size != 0 {
        return Err(Error::UnsupportedSegmentSize);
    }
    let offset_entry_count = input.read_u32()?;

    let encoding = Encoding {
        format,
        version,
        address_size,
    };
    Ok(ListsHeader {
        encoding,
        offset_entry_count,
    })
}
<commit_msg>Silence warning<commit_after>use crate::common::{Encoding, Format};
use crate::read::{Error, Reader, Result};

#[derive(Debug, Clone, Copy)]
pub(crate) struct ListsHeader {
    encoding: Encoding,
    #[allow(dead_code)]
    offset_entry_count: u32,
}

impl Default for ListsHeader {
    fn default() -> Self {
        ListsHeader {
            encoding: Encoding {
                format: Format::Dwarf32,
                version: 5,
                address_size: 0,
            },
            offset_entry_count: 0,
        }
    }
}

impl ListsHeader {
    /// Return the serialized size of the table header.
    #[allow(dead_code)]
    #[inline]
    fn size(self) -> u8 {
        // initial_length + version + address_size + segment_selector_size + offset_entry_count
        ListsHeader::size_for_encoding(self.encoding)
    }

    /// Return the serialized size of the table header.
    #[inline]
    pub(crate) fn size_for_encoding(encoding: Encoding) -> u8 {
        // initial_length + version + address_size + segment_selector_size + offset_entry_count
        encoding.format.initial_length_size() + 2 + 1 + 1 + 4
    }
}

// TODO: add an iterator over headers in the appropriate sections section
#[allow(dead_code)]
fn parse_header<R: Reader>(input: &mut R) -> Result<ListsHeader> {
    let (length, format) = input.read_initial_length()?;
    input.truncate(length)?;

    let version = input.read_u16()?;
    if version != 5 {
        return Err(Error::UnknownVersion(u64::from(version)));
    }

    let address_size = input.read_u8()?;
    let segment_selector_size = input.read_u8()?;
    if segment_selector_size != 0 {
        return Err(Error::UnsupportedSegmentSize);
    }
    let offset_entry_count = input.read_u32()?;

    let encoding = Encoding {
        format,
        version,
        address_size,
    };
    Ok(ListsHeader {
        encoding,
        offset_entry_count,
    })
}
<|endoftext|>


<commit_before>use std::fmt;
use rand::{Rng, thread_rng};

///
/// Abstraction for a single Entry for our log.
///
#[derive(Clone)]
pub struct Entry {
    pub index: usize,   // index of this Entry in the log
    pub term: u64,      // term for which this Entry is committed
    pub data: Vec<u8>,  // data blob containing client-defined command to
                        // apply to the client state machine.
}

#[cfg(test)]
fn random_entry_with_term(term: u64) -> Entry {
  assert_ne!(term, 0);

  let mut vec = vec![0; 8];
  thread_rng().fill_bytes(&mut vec);
  Entry {
      index: 0,
      term: term,
      data: vec,
  }
}

#[cfg(test)]
pub fn random_entry() -> Entry {
    random_entry_with_term(1)
}

impl fmt::Debug for Entry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Entry {{ term: {}, data: {:?} }}", self.term, self.data)
    }
}

impl PartialEq for Entry {
    fn eq(&self, other: &Entry) -> bool {
        self.term == other.term && self.data == other.data
    }
}

///
/// Abstraction for a log of "commands" to apply to the client state machine,
/// stored locally.
/// Small wrapper over a list of Entries-- eventually should also abstract away
/// automatically pushing to persistent storage / snapshotting (TODO)
///
pub trait Log: Sync + Send {
    ///
    /// Retrieves read-only reference to an Entry in the log, specified by |index|.
    /// Will panic if supplied an index exceeds the log length.
    ///
    fn get_entry(&self, index: usize) -> Option<&Entry>;

    ///
    /// Retrieves read-only reference to a slice of all Entries in the log past |start_index|.
    /// Will panic if supplied an index exceeds the log length.
    ///
    fn get_entries_from(&self, start_index: usize) -> &[Entry];

    ///
    /// Appends a copy of each entry in |entries| to log. Will correctly modify
    /// |index| field in each Entry to match its index in the log.
    /// Returns this log object.
    ///
    fn append_entries(&mut self, entries: Vec<Entry>) -> &Log;

    ///
    /// Appends a copy of |entry| to the log. Will correclty modify
    /// |index| field in |entry| to match its index in the log.
    /// Returns this log object.
    ///
    fn append_entry(&mut self, entry: Entry) -> &Log;

    ///
    /// Retrieves the index of the last entry in our log.
    ///
    fn get_last_entry_index(&self) -> usize;

    ///
    /// Retrieves the term of the last entry in our log.
    ///
    fn get_last_entry_term(&self) -> u64;

    ///
    /// Rolls back log so that the most recent entry is located at |index|.
    /// Panics if |index| is an invalid log index.
    /// Returns this log object.
    ///
    fn roll_back(&mut self, index: usize) -> &Log;

    ///
    /// Returns true if the log represented by other_log_index,other_log_term is at least as
    /// complete as this log object.
    ///
    /// Completeness is determined by whichever log has a later term. If both logs have the same
    /// last commited term, then whichever log's index is larger is considered more complete
    ///
    fn is_other_log_valid(&self, other_log_index: usize, other_log_term: u64) -> bool;
}

///
/// Simple implementation of Log that stores all logs in memory.
///
pub struct MemoryLog {
    entries: Vec<Entry>,
    start_index: usize
}

impl MemoryLog {
    pub fn new() -> MemoryLog {
        // start index is always 1, but will be dynamic after we implement snapshotting
        MemoryLog { entries: Vec::new(), start_index: 1}
    }
}

impl Log for MemoryLog {
    fn get_entry(&self, index: usize) -> Option<&Entry> {
        if index < self.start_index {
            return None;
        }

        self.entries.get(index - self.start_index)
    }

    // TODO(jason)
    fn get_entries_from(&self, start_index: usize) -> &[Entry] {
        &self.entries[start_index .. self.entries.len()]
    }

    fn append_entries(&mut self, entries: Vec<Entry>) -> &Log {
        let mut start_index = self.entries.len() + self.start_index;
        let indexed_entries = entries.into_iter().map(|mut entry| {
            debug_assert!(entry.term > 0); // can't commit in term 0
            entry.index = start_index;
            start_index += 1;
            entry
        }).collect::<Vec<Entry>>();
        self.entries.extend(indexed_entries);
        self
    }

    fn append_entry(&mut self, mut entry: Entry) -> &Log {
        debug_assert!(entry.term > 0); // can't commit in term 0
        entry.index = self.entries.len() + self.start_index;
        self.entries.push(entry);
        self
    }

    fn get_last_entry_index(&self) -> usize {
        self.entries.len() - (self.start_index - 1)
    }

    fn get_last_entry_term(&self) -> u64 {
        if self.entries.len() == 0 {
            return 0;
        }

        self.get_entry(self.get_last_entry_index())
            .map_or(0, |e| e.term)
    }

    ///
    /// Deletes all entries > index from the log
    ///
    /// #Panics
    /// Panics if you try to roll back entries that are < start_index
    /// because you should never try to roll back snapshotted entries
    ///
    fn roll_back(&mut self, index: usize) -> &Log {
        let start_index = index - self.start_index + 1;
        if start_index >= self.entries.len() {
            return self; // nothing to remove
        }

        self.entries.drain(start_index ..).collect::<Vec<_>>();
        self
    }

    fn is_other_log_valid (&self, other_log_index: usize, other_log_term: u64) -> bool {
        let last_log_term = self.get_last_entry_term();
        other_log_term > last_log_term ||
            (other_log_term == last_log_term &&
            other_log_index >= self.get_last_entry_index())
    }
}

/// Tests for the log-- these tests should pass for any Log (to test any log, just change the
/// type returned by the |create_log()| helper.
#[cfg(test)]
mod tests {
    use super::{Log, MemoryLog, random_entry, random_entry_with_term};
    fn create_log() -> MemoryLog { MemoryLog::new() } // Replace with other log types as needed

    fn create_filled_log(length: usize) -> MemoryLog {
        let mut log = create_log();
        log.append_entries( vec![random_entry(); length] );
        log
    }

    #[test]
    /// Makes sure we return None if the index is out of the log
    fn test_log_get_entry_out_of_index() {
        let mut log = create_log();
        log.append_entry(random_entry());
        assert!(log.get_entry(2).is_none());
    }

    #[test]
    fn test_log_0_is_none() {
        let mut log = create_log();
        assert!(log.get_entry(0).is_none());
        log.append_entry(random_entry());
        assert!(log.get_entry(0).is_none());
    }

    #[test]
    /// Tests that simple append and get works for a two-element array.
    fn test_log_append_get_simple() {
        let mut log = create_log();
        let entry1 = random_entry();
        let entry2 = random_entry();

        // Append operations
        log.append_entry(entry1.clone());
        log.append_entry(entry2.clone());

        // Data should be the same
        assert_eq!(entry1.data, log.get_entry(1).unwrap().data);
        assert_eq!(entry2.data, log.get_entry(2).unwrap().data);
    }

    #[test]
    /// Tests that indices stay valid after appending entries.
    fn test_log_append_indices_simple() {
        let length = 10;
        let log = create_filled_log(length);
        // Make sure the indices are correctly set
        for i in 1..length + 1 {
            assert_eq!(log.get_entry(i).unwrap().index, i);
        }
    }

    #[test]
    /// Tests that indices stay valid after appending entries.
    fn test_log_roll_back_simple() {
        let length = 10;
        let mut log = create_filled_log(length);
        let new_length = 5;
        log.roll_back(new_length);
        // make sure log has been rolled back!
        assert_eq!(log.get_last_entry_index(), new_length);
    }

    #[test]
    fn log_roll_back_works_with_nothing_to_roll_back() {
        let mut log = create_log();
        log.roll_back(1);
    }

    #[test]
    fn is_other_log_valid_rejects_previous_terms() {
        let mut log = create_log();
        log.append_entry(random_entry_with_term(1));
        log.append_entry(random_entry_with_term(2));
        assert!(!log.is_other_log_valid(3, 1));
    }

    #[test]
    fn is_other_log_valid_rejects_lower_indices() {
        let mut log = create_log();
        log.append_entry(random_entry_with_term(1));
        log.append_entry(random_entry_with_term(1));
        log.append_entry(random_entry_with_term(2));
        assert!(!log.is_other_log_valid(1, 2));
    }

    #[test]
    fn is_other_log_valid_accepts_same_index() {
        let mut log = create_log();
        log.append_entry(random_entry_with_term(1));
        assert!(log.is_other_log_valid(1, 1));
    }

    #[test]
    fn is_other_log_valid_accepts_with_empty_log() {
        let mut log = create_log();
        assert!(log.is_other_log_valid(0, 0));
    }

    #[test]
    #[ignore]
    /// TODO (sydli): Generate a bunch of random queries on the log and make
    ///               sure it stays consistent.
    fn test_fuzz() {
        unimplemented!();
    }
}
<commit_msg>fix(log): get_entries_from supports log entry indices<commit_after>use std::fmt;

///
/// Abstraction for a single Entry for our log.
///
#[derive(Clone)]
pub struct Entry {
    pub index: usize,   // index of this Entry in the log
    pub term: u64,      // term for which this Entry is committed
    pub data: Vec<u8>,  // data blob containing client-defined command to
                        // apply to the client state machine.
}

#[cfg(test)]
use rand::{thread_rng, Rng};
#[cfg(test)]
fn random_entry_with_term(term: u64) -> Entry {
  assert_ne!(term, 0);

  let mut vec = vec![0; 8];
  thread_rng().fill_bytes(&mut vec);
  Entry {
      index: 0,
      term: term,
      data: vec,
  }
}

#[cfg(test)]
pub fn random_entry() -> Entry {
    random_entry_with_term(1)
}

impl fmt::Debug for Entry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Entry {{ term: {}, data: {:?} }}", self.term, self.data)
    }
}

impl PartialEq for Entry {
    fn eq(&self, other: &Entry) -> bool {
        self.term == other.term && self.data == other.data
    }
}

///
/// Abstraction for a log of "commands" to apply to the client state machine,
/// stored locally.
/// Small wrapper over a list of Entries-- eventually should also abstract away
/// automatically pushing to persistent storage / snapshotting (TODO)
///
pub trait Log: Sync + Send {
    ///
    /// Retrieves read-only reference to an Entry in the log, specified by |index|.
    /// Returns None if the index is out of bounds
    ///
    fn get_entry(&self, index: usize) -> Option<&Entry>;

    ///
    /// Retrieves read-only reference to a slice of all Entries in the log past |start_index|.
    /// Slice does not include |start_index|
    ///
    fn get_entries_from(&self, start_index: usize) -> &[Entry];

    ///
    /// Appends a copy of each entry in |entries| to log. Will correctly modify
    /// |index| field in each Entry to match its index in the log.
    /// Returns this log object.
    ///
    fn append_entries(&mut self, entries: Vec<Entry>) -> &Log;

    ///
    /// Appends a copy of |entry| to the log. Will correclty modify
    /// |index| field in |entry| to match its index in the log.
    /// Returns this log object.
    ///
    fn append_entry(&mut self, entry: Entry) -> &Log;

    ///
    /// Retrieves the index of the last entry in our log.
    ///
    fn get_last_entry_index(&self) -> usize;

    ///
    /// Retrieves the term of the last entry in our log.
    ///
    fn get_last_entry_term(&self) -> u64;

    ///
    /// Rolls back log so that the most recent entry is located at |index|.
    /// Returns this log object.
    ///
    /// #Panics
    /// Panics if you try to roll back entries that are < start_index
    /// because you should never try to roll back snapshotted entries
    ///
    fn roll_back(&mut self, index: usize) -> &Log;

    ///
    /// Returns true if the log represented by other_log_index,other_log_term is at least as
    /// complete as this log object.
    ///
    /// Completeness is determined by whichever log has a later term. If both logs have the same
    /// last commited term, then whichever log's index is larger is considered more complete
    ///
    fn is_other_log_valid(&self, other_log_index: usize, other_log_term: u64) -> bool;
}

///
/// Simple implementation of Log that stores all logs in memory.
///
pub struct MemoryLog {
    entries: Vec<Entry>,
    start_index: usize
}

impl MemoryLog {
    pub fn new() -> MemoryLog {
        // start index is always 1, but will be dynamic after we implement snapshotting
        MemoryLog { entries: Vec::new(), start_index: 1}
    }
}

impl Log for MemoryLog {
    fn get_entry(&self, index: usize) -> Option<&Entry> {
        if index < self.start_index {
            return None;
        }

        self.entries.get(index - self.start_index)
    }

    fn get_entries_from(&self, mut start_index: usize) -> &[Entry] {
        if start_index < self.start_index {
            // We should return a slice containing the full memory log
            // TODO: Will we want snapshotted entries?
            start_index = self.start_index - 1;
        }

        start_index -= self.start_index - 1;
        if start_index > self.entries.len() {
            return &[];
        }

        &self.entries[start_index ..]
    }

    fn append_entries(&mut self, entries: Vec<Entry>) -> &Log {
        let mut start_index = self.entries.len() + self.start_index;
        let indexed_entries = entries.into_iter().map(|mut entry| {
            debug_assert!(entry.term > 0); // can't commit in term 0
            entry.index = start_index;
            start_index += 1;
            entry
        }).collect::<Vec<Entry>>();
        self.entries.extend(indexed_entries);
        self
    }

    fn append_entry(&mut self, mut entry: Entry) -> &Log {
        debug_assert!(entry.term > 0); // can't commit in term 0
        entry.index = self.entries.len() + self.start_index;
        self.entries.push(entry);
        self
    }

    fn get_last_entry_index(&self) -> usize {
        self.entries.len() - (self.start_index - 1)
    }

    fn get_last_entry_term(&self) -> u64 {
        if self.entries.len() == 0 {
            return 0;
        }

        self.get_entry(self.get_last_entry_index())
            .map_or(0, |e| e.term)
    }

    fn roll_back(&mut self, index: usize) -> &Log {
        let start_index = index - self.start_index + 1;
        if start_index >= self.entries.len() {
            return self; // nothing to remove
        }

        self.entries.drain(start_index ..).collect::<Vec<_>>();
        self
    }

    fn is_other_log_valid (&self, other_log_index: usize, other_log_term: u64) -> bool {
        let last_log_term = self.get_last_entry_term();
        other_log_term > last_log_term ||
            (other_log_term == last_log_term &&
            other_log_index >= self.get_last_entry_index())
    }
}

/// Tests for the log-- these tests should pass for any Log (to test any log, just change the
/// type returned by the |create_log()| helper.
#[cfg(test)]
mod tests {
    use super::{Log, MemoryLog, random_entry, random_entry_with_term};
    fn create_log() -> MemoryLog { MemoryLog::new() } // Replace with other log types as needed

    fn create_filled_log(length: usize) -> MemoryLog {
        let mut log = create_log();
        log.append_entries( vec![random_entry(); length] );
        log
    }

    #[test]
    /// Makes sure we return None if the index is out of the log
    fn get_entry_out_of_index() {
        let mut log = create_log();
        log.append_entry(random_entry());
        assert!(log.get_entry(2).is_none());
    }

    #[test]
    fn index_0_is_none() {
        let mut log = create_log();
        assert!(log.get_entry(0).is_none());
        log.append_entry(random_entry());
        assert!(log.get_entry(0).is_none());
    }

    #[test]
    /// Tests that simple append and get works for a two-element array.
    fn append_get_simple() {
        let mut log = create_log();
        let entry1 = random_entry();
        let entry2 = random_entry();

        // Append operations
        log.append_entry(entry1.clone());
        log.append_entry(entry2.clone());

        // Data should be the same
        assert_eq!(entry1.data, log.get_entry(1).unwrap().data);
        assert_eq!(entry2.data, log.get_entry(2).unwrap().data);
    }

    #[test]
    /// Tests that indices stay valid after appending entries.
    fn append_indices_simple() {
        let length = 10;
        let log = create_filled_log(length);
        // Make sure the indices are correctly set
        for i in 1..length + 1 {
            assert_eq!(log.get_entry(i).unwrap().index, i);
        }
    }

    #[test]
    /// Tests that get_entries can return a slice
    /// containing the second half of the log
    fn get_entries_from_simple() {
        let length = 10;
        let log = create_filled_log(length);
        assert_eq!(log.get_last_entry_index(), length);

        let mut curr_index = 6;
        let entries = log.get_entries_from(curr_index - 1);
        assert_eq!(entries.len(), length - (curr_index - 1));

        for entry in entries {
            assert_eq!(entry.index, curr_index);
            curr_index += 1;
        }
    }

    #[test]
    fn get_entries_from_out_of_bounds() {
        let log = create_log();
        assert_eq!(log.get_entries_from(0).len(), 0);
        assert_eq!(log.get_entries_from(1).len(), 0);

        let length = 10;
        let filled_log = create_filled_log(length);
        assert_eq!(log.get_entries_from(10).len(), 0);
        assert_eq!(log.get_entries_from(11).len(), 0);
    }

    #[test]
    fn get_entries_from_full() {
        let length = 100;
        let log = create_filled_log(length);
        assert_eq!(log.get_entries_from(0).len(), length);
    }

    #[test]
    /// Tests that indices stay valid after appending entries.
    fn roll_back_simple() {
        let length = 10;
        let mut log = create_filled_log(length);
        let new_length = 5;
        log.roll_back(new_length);
        // make sure log has been rolled back!
        assert_eq!(log.get_last_entry_index(), new_length);
    }

    #[test]
    fn roll_back_works_with_nothing_to_roll_back() {
        let mut log = create_log();
        log.roll_back(1);
    }

    #[test]
    fn is_other_log_valid_rejects_previous_terms() {
        let mut log = create_log();
        log.append_entry(random_entry_with_term(1));
        log.append_entry(random_entry_with_term(2));
        assert!(!log.is_other_log_valid(3, 1));
    }

    #[test]
    fn is_other_log_valid_rejects_lower_indices() {
        let mut log = create_log();
        log.append_entry(random_entry_with_term(1));
        log.append_entry(random_entry_with_term(1));
        log.append_entry(random_entry_with_term(2));
        assert!(!log.is_other_log_valid(1, 2));
    }

    #[test]
    fn is_other_log_valid_accepts_same_index() {
        let mut log = create_log();
        log.append_entry(random_entry_with_term(1));
        assert!(log.is_other_log_valid(1, 1));
    }

    #[test]
    fn is_other_log_valid_accepts_with_empty_log() {
        let log = create_log();
        assert!(log.is_other_log_valid(0, 0));
    }

    #[test]
    #[ignore]
    /// TODO (sydli): Generate a bunch of random queries on the log and make
    ///               sure it stays consistent.
    fn test_fuzz() {
        unimplemented!();
    }
}
<|endoftext|>


<commit_before>use std::sync::Arc;
use bifrost::raft::state_machine::master::ExecError;
use neb::client::{Client as NebClient, NebClientError};
use neb::server::{ServerOptions, NebServer, ServerError};

pub mod general;
pub mod schema;
pub mod traversal;

pub enum MorpheusServerError {
    ServerError(ServerError),
    ClientError(NebClientError),
    InitSchemaError(ExecError)
}

pub struct MorpheusServer {
    neb_server: Arc<NebServer>,
    neb_client: Arc<NebClient>
}

impl MorpheusServer {
    pub fn new(opts: &ServerOptions)
        -> Result<Arc<MorpheusServer>, MorpheusServerError> {
        let neb_server = match NebServer::new(opts) {
            Ok(server) => server,
            Err(e) => return Err(MorpheusServerError::ServerError(e))
        };
        let neb_client = match NebClient::new(
            &neb_server.rpc, &opts.meta_members,
            &opts.group_name) {
            Ok(client) => Arc::new(client),
            Err(e) => return Err(MorpheusServerError::ClientError(e))
        };
        if opts.is_meta {
            if let &Some(ref raft_service) = &neb_server.raft_service {
                schema::SchemaContainer::new_meta_service(raft_service);
            } else {
                panic!("raft service should be ready for meta server");
            }
        }
        let schema_container = match schema::SchemaContainer::new_client(&neb_client.raft_client) {
            Ok(container) => container,
            Err(e) => return Err(MorpheusServerError::InitSchemaError(e))
        };
        Ok(Arc::new(MorpheusServer {
            neb_server: neb_server,
            neb_client: neb_client,
        }))
    }
}<commit_msg>put schema container into server<commit_after>use std::sync::Arc;
use bifrost::raft::state_machine::master::ExecError;
use neb::client::{Client as NebClient, NebClientError};
use neb::server::{ServerOptions, NebServer, ServerError};

pub mod general;
pub mod schema;
pub mod traversal;

pub enum MorpheusServerError {
    ServerError(ServerError),
    ClientError(NebClientError),
    InitSchemaError(ExecError)
}

pub struct MorpheusServer {
    neb_server: Arc<NebServer>,
    neb_client: Arc<NebClient>,
    schema_container: Arc<schema::SchemaContainer>
}

impl MorpheusServer {
    pub fn new(opts: &ServerOptions)
        -> Result<Arc<MorpheusServer>, MorpheusServerError> {
        let neb_server = match NebServer::new(opts) {
            Ok(server) => server,
            Err(e) => return Err(MorpheusServerError::ServerError(e))
        };
        let neb_client = match NebClient::new(
            &neb_server.rpc, &opts.meta_members,
            &opts.group_name) {
            Ok(client) => Arc::new(client),
            Err(e) => return Err(MorpheusServerError::ClientError(e))
        };
        if opts.is_meta {
            if let &Some(ref raft_service) = &neb_server.raft_service {
                schema::SchemaContainer::new_meta_service(raft_service);
            } else {
                panic!("raft service should be ready for meta server");
            }
        }
        let schema_container = match schema::SchemaContainer::new_client(&neb_client.raft_client) {
            Ok(container) => container,
            Err(e) => return Err(MorpheusServerError::InitSchemaError(e))
        };
        Ok(Arc::new(MorpheusServer {
            neb_server: neb_server,
            neb_client: neb_client,
            schema_container: schema_container
        }))
    }
}<|endoftext|>


<commit_before>use super::{Open, Sink};
extern crate rodio;
extern crate cpal;
use std::{io, thread, time};
use std::process::exit;

pub struct RodioSink {
    rodio_sink: rodio::Sink,
}

fn list_formats(ref device: &rodio::Device) {
    let default_fmt = match device.default_output_format() {
        Ok(fmt) => cpal::SupportedFormat::from(fmt),
        Err(e) => {
            info!("Error getting default rodio::Sink format: {:?}", e);
            return;
        },
    };

    let mut output_formats = match device.supported_output_formats() {
        Ok(f) => f.peekable(),
        Err(e) => {
            info!("Error getting supported rodio::Sink formats: {:?}", e);
            return;
        },
    };

    if output_formats.peek().is_some() {
        debug!("  Available formats:");
        for format in output_formats {
            let s = format!("{}ch, {:?}, min {:?}, max {:?}", format.channels, format.data_type, format.min_sample_rate, format.max_sample_rate);
            if format == default_fmt {
                debug!("    (default) {}", s);
            } else {
                debug!("    {:?}", format);
            }
        }
    }
}

fn list_outputs() {
    let default_device = rodio::default_output_device().unwrap();
    println!("Default Audio Device:\n  {}", default_device.name());
    list_formats(&default_device);

    println!("Other Available Audio Devices:");
    for device in rodio::output_devices() {
        if device.name() != default_device.name() {
            println!("  {}", device.name());
            list_formats(&device);
        }
    }
}

impl Open for RodioSink {
    fn open(device: Option<String>) -> RodioSink {
        debug!("Using rodio sink");

        let mut rodio_device = rodio::default_output_device().expect("no output device available");
        if device.is_some() {
            let device_name = device.unwrap();

            if device_name == "?".to_string() {
                list_outputs();
                exit(0)
            }
            let mut found = false;
            for d in rodio::output_devices() {
                if d.name() == device_name {
                    rodio_device = d;
                    found = true;
                    break;
                }
            }
            if !found {
                println!("No output sink matching '{}' found.", device_name);
                exit(0)
            }
        }
        let sink = rodio::Sink::new(&rodio_device);

        RodioSink {
            rodio_sink: sink,
        }
    }
}

impl Sink for RodioSink {
    fn start(&mut self) -> io::Result<()> {
        // More similar to an "unpause" than "play". Doesn't undo "stop".
        // self.rodio_sink.play();
        Ok(())
    }

    fn stop(&mut self) -> io::Result<()> {
        // This will immediately stop playback, but the sink is then unusable.
        // We just have to let the current buffer play till the end.
        // self.rodio_sink.stop();
        Ok(())
    }

    fn write(&mut self, data: &[i16]) -> io::Result<()> {
        let source = rodio::buffer::SamplesBuffer::new(2, 44100, data);
        self.rodio_sink.append(source);

        // Chunk sizes seem to be about 256 to 3000 ish items long.
        // Assuming they're on average 1628 then a half second buffer is:
        // 44100 elements --> about 27 chunks
        while self.rodio_sink.len() > 26 {
            // sleep and wait for rodio to drain a bit
            thread::sleep(time::Duration::from_millis(10));
        }
        Ok(())
    }
}
<commit_msg>Warn when there's a Rodio failure accessing a default device formats.<commit_after>use super::{Open, Sink};
extern crate rodio;
extern crate cpal;
use std::{io, thread, time};
use std::process::exit;

pub struct RodioSink {
    rodio_sink: rodio::Sink,
}

fn list_formats(ref device: &rodio::Device) {
    let default_fmt = match device.default_output_format() {
        Ok(fmt) => cpal::SupportedFormat::from(fmt),
        Err(e) => {
            warn!("Error getting default rodio::Sink format: {:?}", e);
            return;
        },
    };

    let mut output_formats = match device.supported_output_formats() {
        Ok(f) => f.peekable(),
        Err(e) => {
            warn!("Error getting supported rodio::Sink formats: {:?}", e);
            return;
        },
    };

    if output_formats.peek().is_some() {
        debug!("  Available formats:");
        for format in output_formats {
            let s = format!("{}ch, {:?}, min {:?}, max {:?}", format.channels, format.data_type, format.min_sample_rate, format.max_sample_rate);
            if format == default_fmt {
                debug!("    (default) {}", s);
            } else {
                debug!("    {:?}", format);
            }
        }
    }
}

fn list_outputs() {
    let default_device = rodio::default_output_device().unwrap();
    println!("Default Audio Device:\n  {}", default_device.name());
    list_formats(&default_device);

    println!("Other Available Audio Devices:");
    for device in rodio::output_devices() {
        if device.name() != default_device.name() {
            println!("  {}", device.name());
            list_formats(&device);
        }
    }
}

impl Open for RodioSink {
    fn open(device: Option<String>) -> RodioSink {
        debug!("Using rodio sink");

        let mut rodio_device = rodio::default_output_device().expect("no output device available");
        if device.is_some() {
            let device_name = device.unwrap();

            if device_name == "?".to_string() {
                list_outputs();
                exit(0)
            }
            let mut found = false;
            for d in rodio::output_devices() {
                if d.name() == device_name {
                    rodio_device = d;
                    found = true;
                    break;
                }
            }
            if !found {
                println!("No output sink matching '{}' found.", device_name);
                exit(0)
            }
        }
        let sink = rodio::Sink::new(&rodio_device);

        RodioSink {
            rodio_sink: sink,
        }
    }
}

impl Sink for RodioSink {
    fn start(&mut self) -> io::Result<()> {
        // More similar to an "unpause" than "play". Doesn't undo "stop".
        // self.rodio_sink.play();
        Ok(())
    }

    fn stop(&mut self) -> io::Result<()> {
        // This will immediately stop playback, but the sink is then unusable.
        // We just have to let the current buffer play till the end.
        // self.rodio_sink.stop();
        Ok(())
    }

    fn write(&mut self, data: &[i16]) -> io::Result<()> {
        let source = rodio::buffer::SamplesBuffer::new(2, 44100, data);
        self.rodio_sink.append(source);

        // Chunk sizes seem to be about 256 to 3000 ish items long.
        // Assuming they're on average 1628 then a half second buffer is:
        // 44100 elements --> about 27 chunks
        while self.rodio_sink.len() > 26 {
            // sleep and wait for rodio to drain a bit
            thread::sleep(time::Duration::from_millis(10));
        }
        Ok(())
    }
}
<|endoftext|>


<commit_before>extern crate spidev;

use spidev::ioctl;

// get window size
pub const TIOCGWINSZ: u32 = 0x5413;

#[derive(Clone, Copy, Debug)]
struct Winsize {
    pub ws_row: u16,
    pub ws_col: u16,
    pub ws_xpixel: u16,
    pub ws_ypixel: u16,
}

fn main() {
    // 0 is stdout
    match ioctl::read::<Winsize>(0, TIOCGWINSZ) {
        Ok(winsize) => println!("{:?}", winsize),
        Err(err) => println!("{}", err),
    }
}
<commit_msg>ioctl: fix example by adding unsafe block<commit_after>extern crate spidev;

use spidev::ioctl;

// get window size
pub const TIOCGWINSZ: u32 = 0x5413;

#[derive(Clone, Copy, Debug)]
struct Winsize {
    pub ws_row: u16,
    pub ws_col: u16,
    pub ws_xpixel: u16,
    pub ws_ypixel: u16,
}

fn main() {
    // 0 is stdout
    match unsafe { ioctl::read::<Winsize>(0, TIOCGWINSZ) } {
        Ok(winsize) => println!("{:?}", winsize),
        Err(err) => println!("{}", err),
    }
}
<|endoftext|>


<commit_before>//! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications

#![feature(alloc)]
#![feature(arc_counts)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(drop_types_in_const)]
#![feature(heap_api)]
#![feature(integer_atomics)]
#![feature(never_type)]
#![feature(thread_local)]
#![no_std]

use arch::interrupt;

/// Architecture specific items (test)
#[cfg(test)]
#[macro_use]
extern crate arch_test as arch;

/// Architecture specific items (ARM)
#[cfg(all(not(test), target_arch = "arm"))]
#[macro_use]
extern crate arch_arm as arch;

/// Architecture specific items (x86_64)
#[cfg(all(not(test), target_arch = "x86_64"))]
#[macro_use]
extern crate arch_x86_64 as arch;

extern crate alloc;
#[macro_use]
extern crate collections;

#[macro_use]
extern crate bitflags;
extern crate goblin;
extern crate spin;

use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use scheme::FileHandle;

#[macro_use]
#[macro_export]
/// Shared data structures
pub mod common;

/// Context management
pub mod context;

/// ELF file parsing
pub mod elf;

/// Schemes, filesystem handlers
pub mod scheme;

/// Synchronization primitives
pub mod sync;

/// Syscall handlers
pub mod syscall;

/// Tests
#[cfg(test)]
pub mod tests;

/// A unique number that identifies the current CPU - used for scheduling
#[thread_local]
static CPU_ID: AtomicUsize = ATOMIC_USIZE_INIT;

/// Get the current CPU's scheduling ID
#[inline(always)]
pub fn cpu_id() -> usize {
    CPU_ID.load(Ordering::Relaxed)
}

/// The count of all CPUs that can have work scheduled
static CPU_COUNT : AtomicUsize = ATOMIC_USIZE_INIT;

/// Get the number of CPUs currently active
#[inline(always)]
pub fn cpu_count() -> usize {
    CPU_COUNT.load(Ordering::Relaxed)
}

/// Initialize userspace by running the initfs:bin/init process
/// This function will also set the CWD to initfs:bin and open debug: as stdio
pub extern fn userspace_init() {
    assert_eq!(syscall::chdir(b"initfs:"), Ok(0));

    assert_eq!(syscall::open(b"debug:", syscall::flag::O_RDONLY).map(FileHandle::into), Ok(0));
    assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(FileHandle::into), Ok(1));
    assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(FileHandle::into), Ok(2));

    syscall::exec(b"initfs:/bin/init", &[]).expect("failed to execute initfs:init");

    panic!("initfs:init returned")
}

/// Allow exception handlers to send signal to arch-independant kernel
#[no_mangle]
pub extern fn ksignal(signal: usize) {
    println!("SIGNAL {}, CPU {}, PID {:?}", signal, cpu_id(), context::context_id());
    {
        let contexts = context::contexts();
        if let Some(context_lock) = contexts.current() {
            let context = context_lock.read();
            println!("NAME {}", unsafe { ::core::str::from_utf8_unchecked(&context.name.lock()) });
        }
    }
    syscall::exit(signal & 0x7F);
}

/// This is the kernel entry point for the primary CPU. The arch crate is responsible for calling this
#[no_mangle]
pub extern fn kmain(cpus: usize) {
    CPU_ID.store(0, Ordering::SeqCst);
    CPU_COUNT.store(cpus, Ordering::SeqCst);

    context::init();

    let pid = syscall::getpid();
    println!("BSP: {:?} {}", pid, cpus);

    match context::contexts_mut().spawn(userspace_init) {
        Ok(context_lock) => {
            let mut context = context_lock.write();
            context.status = context::Status::Runnable;
        },
        Err(err) => {
            panic!("failed to spawn userspace_init: {:?}", err);
        }
    }

    loop {
        unsafe {
            interrupt::disable();
            if context::switch() {
                interrupt::enable_and_nop();
            } else {
                // Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
                interrupt::enable_and_halt();
            }
        }
    }
}

/// This is the main kernel entry point for secondary CPUs
#[no_mangle]
pub extern fn kmain_ap(id: usize) {
    CPU_ID.store(id, Ordering::SeqCst);

    context::init();

    let pid = syscall::getpid();
    println!("AP {}: {:?}", id, pid);

    // Disable APs for now
    loop {
        unsafe { interrupt::enable_and_halt(); }
    }
/*
    loop {
        unsafe {
            interrupt::disable();
            if context::switch() {
                interrupt::enable_and_nop();
            } else {
                // Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
                interrupt::enable_and_halt();
            }
        }
    }
*/
}
<commit_msg>More path cleanup<commit_after>//! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications

#![feature(alloc)]
#![feature(arc_counts)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(drop_types_in_const)]
#![feature(heap_api)]
#![feature(integer_atomics)]
#![feature(never_type)]
#![feature(thread_local)]
#![no_std]

use arch::interrupt;

/// Architecture specific items (test)
#[cfg(test)]
#[macro_use]
extern crate arch_test as arch;

/// Architecture specific items (ARM)
#[cfg(all(not(test), target_arch = "arm"))]
#[macro_use]
extern crate arch_arm as arch;

/// Architecture specific items (x86_64)
#[cfg(all(not(test), target_arch = "x86_64"))]
#[macro_use]
extern crate arch_x86_64 as arch;

extern crate alloc;
#[macro_use]
extern crate collections;

#[macro_use]
extern crate bitflags;
extern crate goblin;
extern crate spin;

use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use scheme::FileHandle;

#[macro_use]
#[macro_export]
/// Shared data structures
pub mod common;

/// Context management
pub mod context;

/// ELF file parsing
pub mod elf;

/// Schemes, filesystem handlers
pub mod scheme;

/// Synchronization primitives
pub mod sync;

/// Syscall handlers
pub mod syscall;

/// Tests
#[cfg(test)]
pub mod tests;

/// A unique number that identifies the current CPU - used for scheduling
#[thread_local]
static CPU_ID: AtomicUsize = ATOMIC_USIZE_INIT;

/// Get the current CPU's scheduling ID
#[inline(always)]
pub fn cpu_id() -> usize {
    CPU_ID.load(Ordering::Relaxed)
}

/// The count of all CPUs that can have work scheduled
static CPU_COUNT : AtomicUsize = ATOMIC_USIZE_INIT;

/// Get the number of CPUs currently active
#[inline(always)]
pub fn cpu_count() -> usize {
    CPU_COUNT.load(Ordering::Relaxed)
}

/// Initialize userspace by running the initfs:bin/init process
/// This function will also set the CWD to initfs:bin and open debug: as stdio
pub extern fn userspace_init() {
    assert_eq!(syscall::chdir(b"initfs:"), Ok(0));

    assert_eq!(syscall::open(b"debug:", syscall::flag::O_RDONLY).map(FileHandle::into), Ok(0));
    assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(FileHandle::into), Ok(1));
    assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(FileHandle::into), Ok(2));

    syscall::exec(b"/bin/init", &[]).expect("failed to execute init");

    panic!("init returned")
}

/// Allow exception handlers to send signal to arch-independant kernel
#[no_mangle]
pub extern fn ksignal(signal: usize) {
    println!("SIGNAL {}, CPU {}, PID {:?}", signal, cpu_id(), context::context_id());
    {
        let contexts = context::contexts();
        if let Some(context_lock) = contexts.current() {
            let context = context_lock.read();
            println!("NAME {}", unsafe { ::core::str::from_utf8_unchecked(&context.name.lock()) });
        }
    }
    syscall::exit(signal & 0x7F);
}

/// This is the kernel entry point for the primary CPU. The arch crate is responsible for calling this
#[no_mangle]
pub extern fn kmain(cpus: usize) {
    CPU_ID.store(0, Ordering::SeqCst);
    CPU_COUNT.store(cpus, Ordering::SeqCst);

    context::init();

    let pid = syscall::getpid();
    println!("BSP: {:?} {}", pid, cpus);

    match context::contexts_mut().spawn(userspace_init) {
        Ok(context_lock) => {
            let mut context = context_lock.write();
            context.status = context::Status::Runnable;
        },
        Err(err) => {
            panic!("failed to spawn userspace_init: {:?}", err);
        }
    }

    loop {
        unsafe {
            interrupt::disable();
            if context::switch() {
                interrupt::enable_and_nop();
            } else {
                // Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
                interrupt::enable_and_halt();
            }
        }
    }
}

/// This is the main kernel entry point for secondary CPUs
#[no_mangle]
pub extern fn kmain_ap(id: usize) {
    CPU_ID.store(id, Ordering::SeqCst);

    context::init();

    let pid = syscall::getpid();
    println!("AP {}: {:?}", id, pid);

    // Disable APs for now
    loop {
        unsafe { interrupt::enable_and_halt(); }
    }
/*
    loop {
        unsafe {
            interrupt::disable();
            if context::switch() {
                interrupt::enable_and_nop();
            } else {
                // Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
                interrupt::enable_and_halt();
            }
        }
    }
*/
}
<|endoftext|>


<commit_before>
use aster::AstBuilder;

use borealis::dom::{Handle, Node};

use syntax::ast::Expr;
use syntax::ext::base::ExtCtxt;
use syntax::ext::quote::rt::ExtParseUtils;
use syntax::ptr::P;

use expr::{string_expr, string_code_expr, str_expr, qualname_expr};

pub fn document_expression(cx: &ExtCtxt, builder: &AstBuilder, document: &Handle) -> P<Expr> {
    match *document.borrow() {
        (Node::Document(ref doctype, ref child), _) => {
            let child_expr = match *child {
                Some(ref child) => node_expression(cx, builder, child),
                None => quote_expr!(cx, {}),
            };

            match *doctype {
                Some(ref doctype) => {
                    let doctype = string_expr(builder, doctype);
                    quote_expr!(cx, {
                        let mut s = s.doctype($doctype).node();
                        $child_expr
                    })
                }
                None => {
                    quote_expr!(cx, {
                        let mut s = s.node();
                        $child_expr
                    })
                }
            }
        }
        _ => panic!("expected document, got: {:?}", document),
    }
}

pub fn node_expression(cx: &ExtCtxt, builder: &AstBuilder, node: &Handle) -> P<Expr> {
    match *node.borrow() {
        (Node::Comment(ref comment), _) => {
            let comment = string_expr(builder, comment);
            quote_expr!(cx, {
                s.comment($comment);
            })
        }
        (Node::Text(ref text), _) => text_node_expression(cx, builder, &text[..]),
        (Node::Element(ref name, ref attrs, ref children), _) => {
            let name = qualname_expr(cx, builder, name);

            let attrs_expr = attrs.iter().map(|a| {
                let key = qualname_expr(cx, builder, &a.0);
                let value = string_code_expr(cx, builder, &a.1);

                quote_expr!(cx, {
                    (&$key, $value)
                })
            });
            let attrs_expr = builder.expr().slice().with_exprs(attrs_expr).build();

            let child_exprs: Vec<_> = children.iter()
                                              .map(|c| node_expression(cx, builder, c))
                                              .collect();

            quote_expr!(cx, {
                let mut s = s.element_normal($name, $attrs_expr.iter());
                $child_exprs
            })
        }
        _ => panic!("expected comment, text or element, got {:?}", node),
    }
}

pub fn text_node_expression(cx: &ExtCtxt, builder: &AstBuilder, string: &str) -> P<Expr> {
    let regex = regex!(r#"\{{2}([^"]|"(\\"|[^"])*")*?(\}{2}|"([^"]|\\")*$|$)"#);
    let mut last_end = 0;
    let mut exprs = Vec::new();

    fn add_text_node_str(cx: &ExtCtxt, builder: &AstBuilder, exprs: &mut Vec<P<Expr>>, s: &str) {
        let text = str_expr(builder, s);
        exprs.push(quote_expr!(cx, {
            s.text($text);
        }));
    };

    for (start, end) in regex.find_iter(&string[..]) {
        if last_end != start {
            add_text_node_str(cx, builder, &mut exprs, &string[last_end..start]);
        }

        if !string[start + 2..end].ends_with("}}") {
            cx.span_err(cx.original_span(),
                        &format!("unmatched {} around: {}", "{{", &string[start..end]));
        } else {
            let expr = cx.parse_expr(string[start + 2..end - 2].to_owned());
            exprs.push(quote_expr!(cx, {
                #[allow(unused_imports)]
                use ::borealis::serializer::{SerializeNode, SerializeNodes};
                $expr.serialize_node(&mut s);
            }));
        }

        last_end = end;
    }

    if last_end != string.len() {
        add_text_node_str(cx, builder, &mut exprs, &string[last_end..]);
    }

    quote_expr!(cx, {
        $exprs
    })
}
<commit_msg>Fixed warnings about unused variables.<commit_after>
use aster::AstBuilder;

use borealis::dom::{Handle, Node};

use syntax::ast::Expr;
use syntax::ext::base::ExtCtxt;
use syntax::ext::quote::rt::ExtParseUtils;
use syntax::ptr::P;

use expr::{string_expr, string_code_expr, str_expr, qualname_expr};

pub fn document_expression(cx: &ExtCtxt, builder: &AstBuilder, document: &Handle) -> P<Expr> {
    match *document.borrow() {
        (Node::Document(ref doctype, ref child), _) => {
            let child_expr = match *child {
                Some(ref child) => node_expression(cx, builder, child),
                None => quote_expr!(cx, {}),
            };

            let doctype_expr = match *doctype {
                Some(ref doctype) => {
                    let doctype = string_expr(builder, doctype);
                    quote_expr!(cx, s.doctype($doctype).node())
                }
                None => {
                    quote_expr!(cx, s.node())
                }
            };

            match *child {
                Some(_) => {
                    quote_expr!(cx, {
                        let mut s = $doctype_expr;
                        $child_expr
                    })
                }
                None => {
                    quote_expr!(cx, {
                        $doctype_expr;
                    })
                }
            }
        }
        _ => panic!("expected document, got: {:?}", document),
    }
}

pub fn node_expression(cx: &ExtCtxt, builder: &AstBuilder, node: &Handle) -> P<Expr> {
    match *node.borrow() {
        (Node::Comment(ref comment), _) => {
            let comment = string_expr(builder, comment);
            quote_expr!(cx, {
                s.comment($comment);
            })
        }
        (Node::Text(ref text), _) => text_node_expression(cx, builder, &text[..]),
        (Node::Element(ref name, ref attrs, ref children), _) => {
            let name = qualname_expr(cx, builder, name);

            let attrs_expr = attrs.iter().map(|a| {
                let key = qualname_expr(cx, builder, &a.0);
                let value = string_code_expr(cx, builder, &a.1);

                quote_expr!(cx, {
                    (&$key, $value)
                })
            });
            let attrs_expr = builder.expr().slice().with_exprs(attrs_expr).build();

            let child_exprs: Vec<_> = children.iter()
                                              .map(|c| node_expression(cx, builder, c))
                                              .collect();
            let expr = quote_expr!(cx, {
                s.element_normal($name, $attrs_expr.iter())
            });

            if child_exprs.len() == 0 {
                quote_expr!(cx, {
                    $expr;
                })
            } else {
                quote_expr!(cx, {
                    let mut s = $expr;
                    $child_exprs
                })
            }
        }
        _ => panic!("expected comment, text or element, got {:?}", node),
    }
}

pub fn text_node_expression(cx: &ExtCtxt, builder: &AstBuilder, string: &str) -> P<Expr> {
    let regex = regex!(r#"\{{2}([^"]|"(\\"|[^"])*")*?(\}{2}|"([^"]|\\")*$|$)"#);
    let mut last_end = 0;
    let mut exprs = Vec::new();

    fn add_text_node_str(cx: &ExtCtxt, builder: &AstBuilder, exprs: &mut Vec<P<Expr>>, s: &str) {
        let text = str_expr(builder, s);
        exprs.push(quote_expr!(cx, {
            s.text($text);
        }));
    };

    for (start, end) in regex.find_iter(&string[..]) {
        if last_end != start {
            add_text_node_str(cx, builder, &mut exprs, &string[last_end..start]);
        }

        if !string[start + 2..end].ends_with("}}") {
            cx.span_err(cx.original_span(),
                        &format!("unmatched {} around: {}", "{{", &string[start..end]));
        } else {
            let expr = cx.parse_expr(string[start + 2..end - 2].to_owned());
            exprs.push(quote_expr!(cx, {
                #[allow(unused_imports)]
                use ::borealis::serializer::{SerializeNode, SerializeNodes};
                $expr.serialize_node(&mut s);
            }));
        }

        last_end = end;
    }

    if last_end != string.len() {
        add_text_node_str(cx, builder, &mut exprs, &string[last_end..]);
    }

    quote_expr!(cx, {
        $exprs
    })
}
<|endoftext|>