<commit_before>/*
 * Copyright (c) 2019 Arm Limited
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "mbed_interface.h"
#include "mbed_wait_api.h"
#include "mbed_assert.h"
#include "netsocket/nsapi_types.h"
#include "events/mbed_shared_queues.h"

#include "smsc9220_emac.h"
#include "smsc9220_eth_drv.h"

#ifndef SMSC9220_ETH
#error "SMSC9220_ETH should be defined, check device_cfg.h!"
#endif

#ifndef SMSC9220_Ethernet_Interrupt_Handler
#error "SMSC9220_Ethernet_Interrupt_Handler should be defined to platform's \
Ethernet IRQ handler!"
#endif

static SMSC9220_EMAC *board_emac_pointer = NULL;
const struct smsc9220_eth_dev_t* SMSC9220_EMAC::dev = &SMSC9220_ETH_DEV;

extern "C" void SMSC9220_Ethernet_Interrupt_Handler(void)
{
    if (smsc9220_get_interrupt(SMSC9220_EMAC::dev,
                                 SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL)) {
        board_emac_pointer->rx_isr();
        smsc9220_clear_interrupt(SMSC9220_EMAC::dev,
                                 SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);
        smsc9220_disable_interrupt(SMSC9220_EMAC::dev,
                                   SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);
    }
}

SMSC9220_EMAC::SMSC9220_EMAC() : receiver_thread(LINK_STATUS_THREAD_PRIORITY,
                                       (uint32_t)LINK_STATUS_THREAD_STACKSIZE)
{
}

/** \brief Ethernet receive interrupt handler
 *
 *  This function handles the receive interrupt.
 */
void SMSC9220_EMAC::rx_isr()
{
    receiver_thread.flags_set(FLAG_RX);
}

/** \brief  Allocates a emac_mem_buf_t and returns the data from the incoming
 * packet.
 *
 *  \return a emac_mem_buf_t filled with the received packet
 * (including MAC header)
 */
emac_mem_buf_t *SMSC9220_EMAC::low_level_input()
{
    emac_mem_buf_t *p = NULL;
    uint32_t message_length = 0;
    uint32_t received_bytes = 0;

    message_length = smsc9220_peek_next_packet_size(dev);
    if (message_length == 0) {
        return p;
    } else {
        /* The Ethernet controller cannot remove CRC from the end of the
         * incoming packet, thus it should be taken into account when
         * calculating the actual message length.*/
        message_length -= CRC_LENGTH_BYTES;
    }

    p = _memory_manager->alloc_heap(SMSC9220_ETH_MAX_FRAME_SIZE,
                                    SMSC9220_BUFF_ALIGNMENT);

    if (p != NULL) {
        _RXLockMutex.lock();
        received_bytes = smsc9220_receive_by_chunks(dev,
                                  (char*)_memory_manager->get_ptr(p),
                                  _memory_manager->get_len(p));
        if(received_bytes == 0){
            _memory_manager->free(p);
            p = nullptr;
        } else {
            _memory_manager->set_len(p, received_bytes);
        }
        _RXLockMutex.unlock();
    }

    return p;
}

/** \brief  Receiver thread.
 *
 * Woken by thread flags to receive packets or clean up transmit
 *
 *  \param[in] params pointer to the interface data
 */
void SMSC9220_EMAC::receiver_thread_function(void* params)
{
    struct SMSC9220_EMAC *smsc9220_enet = static_cast<SMSC9220_EMAC *>(params);

    while(1) {
        uint32_t flags = ThisThread::flags_wait_any(FLAG_RX);

        if (flags & FLAG_RX) {
            smsc9220_enet->packet_rx();
        }
    }
}

/** \brief  Packet reception task
 *
 * This task is called when a packet is received. It will
 * pass the packet to the Network Stack.
 */
void SMSC9220_EMAC::packet_rx()
{
    emac_mem_buf_t *p;
    p = low_level_input();
    if(p != NULL) {
        _emac_link_input_cb(p);
    }
    smsc9220_enable_interrupt(dev, SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);
}

bool SMSC9220_EMAC::link_out(emac_mem_buf_t *buf)
{
    if(buf == NULL) {
        return false;
    } else {
        uint32_t buffer_chain_length = 0;
        enum smsc9220_error_t error = SMSC9220_ERROR_NONE;
        /* If buffer is chained or not aligned then
         * make a contiguous aligned copy of it */
        if (_memory_manager->get_next(buf) ||
            reinterpret_cast<uint32_t>(_memory_manager->get_ptr(buf)) %
                                                      SMSC9220_BUFF_ALIGNMENT) {
            emac_mem_buf_t *copy_buf;
            copy_buf = _memory_manager->alloc_heap(
                                             _memory_manager->get_total_len(buf),
                                             SMSC9220_BUFF_ALIGNMENT);
            if (NULL == copy_buf) {
                _memory_manager->free(buf);
                return false;
            }

            /* Copy to new buffer and free original */
            _memory_manager->copy(copy_buf, buf);
            _memory_manager->free(buf);
            buf = copy_buf;
        }

        buffer_chain_length = _memory_manager->get_total_len(buf);

        _TXLockMutex.lock();
        error = smsc9220_send_by_chunks(dev,
                                      buffer_chain_length,
                                      true,
                                      (const char*)_memory_manager->get_ptr(buf),
                                      _memory_manager->get_len(buf));
        _memory_manager->free(buf);
        _TXLockMutex.unlock();
        return (error == SMSC9220_ERROR_NONE);
    }
}

void SMSC9220_EMAC::link_status_task()
{
    uint32_t phy_basic_status_reg_value = 0;
    bool current_link_status_up = false;

    /* Get current status */
    smsc9220_phy_regread(dev, SMSC9220_PHY_REG_OFFSET_BSTATUS,
                         &phy_basic_status_reg_value);

    current_link_status_up = (bool)(phy_basic_status_reg_value &
                          (1ul << (PHY_REG_BSTATUS_LINK_STATUS_INDEX)));

    /* Compare with the previous state */
    if (current_link_status_up != _prev_link_status_up) {
        _emac_link_state_cb(current_link_status_up);
        _prev_link_status_up = current_link_status_up;
    }

}

bool SMSC9220_EMAC::power_up()
{
    board_emac_pointer = this;
    receiver_thread.start(callback(&SMSC9220_EMAC::receiver_thread_function,
                                   this));

    /* Initialize the hardware */
    enum smsc9220_error_t init_successful = smsc9220_init(dev, &thread_sleep_for);
    if (init_successful != SMSC9220_ERROR_NONE) {
        return false;
    }

    /* Init FIFO level interrupts: use Rx status level irq to trigger
     * interrupts for any non-processed packets, while Tx is not irq driven */
    smsc9220_set_fifo_level_irq(dev, SMSC9220_FIFO_LEVEL_IRQ_RX_STATUS_POS,
            SMSC9220_FIFO_LEVEL_IRQ_LEVEL_MIN);
    smsc9220_set_fifo_level_irq(dev, SMSC9220_FIFO_LEVEL_IRQ_TX_STATUS_POS,
            SMSC9220_FIFO_LEVEL_IRQ_LEVEL_MIN);
    smsc9220_set_fifo_level_irq(dev, SMSC9220_FIFO_LEVEL_IRQ_TX_DATA_POS,
            SMSC9220_FIFO_LEVEL_IRQ_LEVEL_MAX);

    /* Enable Ethernet interrupts in NVIC */
    NVIC_EnableIRQ(ETHERNET_IRQn);
    smsc9220_enable_interrupt(dev, SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);

    /* Trigger thread to deal with any RX packets that arrived
     * before receiver_thread was started */
    rx_isr();
    _prev_link_status_up = PHY_STATE_LINK_DOWN;
    mbed::mbed_event_queue()->call(mbed::callback(this,
                                             &SMSC9220_EMAC::link_status_task));

    /* Allow the Link Status task to detect the initial link state */
    ThisThread::sleep_for(10ms);
    _link_status_task_handle = mbed::mbed_event_queue()->call_every(
                              LINK_STATUS_TASK_PERIOD_MS,
                              mbed::callback(this,
                                             &SMSC9220_EMAC::link_status_task));

    return true;
}

uint32_t SMSC9220_EMAC::get_mtu_size() const
{
    return SMSC9220_ETH_MTU_SIZE;
}

uint32_t SMSC9220_EMAC::get_align_preference() const
{
    return SMSC9220_BUFF_ALIGNMENT;
}

void SMSC9220_EMAC::get_ifname(char *name, uint8_t size) const
{
    memcpy(name, SMSC9220_ETH_IF_NAME, (size < sizeof(SMSC9220_ETH_IF_NAME)) ?
                                           size : sizeof(SMSC9220_ETH_IF_NAME));
}

uint8_t SMSC9220_EMAC::get_hwaddr_size() const
{
    return SMSC9220_HWADDR_SIZE;
}

bool SMSC9220_EMAC::get_hwaddr(uint8_t *addr) const
{
    if(smsc9220_read_mac_address(dev, (char*)addr) == SMSC9220_ERROR_NONE) {
        return true;
    } else {
        return false;
    }
}

void SMSC9220_EMAC::set_hwaddr(const uint8_t *addr)
{
    if (!addr) {
        return;
    }

    memcpy(_hwaddr, addr, sizeof _hwaddr);
    uint32_t mac_low = 0;
    uint32_t mac_high = 0;

    /* Using local variables to make sure the right alignment is used */
    memcpy((void*)&mac_low, (void*)addr, 4);
    memcpy((void*)&mac_high, (void*)(addr+4), 2);

    if (smsc9220_mac_regwrite(dev, SMSC9220_MAC_REG_OFFSET_ADDRL, mac_low)) {
        return;
    }
    if (smsc9220_mac_regwrite(dev, SMSC9220_MAC_REG_OFFSET_ADDRH, mac_high)) {
        return;
    }
}

void SMSC9220_EMAC::set_link_input_cb(emac_link_input_cb_t input_cb)
{
    _emac_link_input_cb = input_cb;
}

void SMSC9220_EMAC::set_link_state_cb(emac_link_state_change_cb_t state_cb)
{
    _emac_link_state_cb = state_cb;
}

void SMSC9220_EMAC::add_multicast_group(const uint8_t *addr)
{
    // No action for now
}

void SMSC9220_EMAC::remove_multicast_group(const uint8_t *addr)
{
    // No action for now
}

void SMSC9220_EMAC::set_all_multicast(bool all)
{
    // No action for now
}

void SMSC9220_EMAC::power_down()
{
    // No action for now
}

void SMSC9220_EMAC::set_memory_manager(EMACMemoryManager &mem_mngr)
{
    _memory_manager = &mem_mngr;
}

SMSC9220_EMAC &SMSC9220_EMAC::get_instance() {
    static SMSC9220_EMAC emac;
    return emac;
}

/* Weak so a module can override */
MBED_WEAK EMAC &EMAC::get_default_instance() {
    return SMSC9220_EMAC::get_instance();
}
<commit_msg>MPS2 CM3DS ethernet fix heap bug<commit_after>/*
 * Copyright (c) 2019 Arm Limited
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "mbed_interface.h"
#include "mbed_wait_api.h"
#include "mbed_assert.h"
#include "netsocket/nsapi_types.h"
#include "events/mbed_shared_queues.h"

#include "smsc9220_emac.h"
#include "smsc9220_eth_drv.h"

#ifndef SMSC9220_ETH
#error "SMSC9220_ETH should be defined, check device_cfg.h!"
#endif

#ifndef SMSC9220_Ethernet_Interrupt_Handler
#error "SMSC9220_Ethernet_Interrupt_Handler should be defined to platform's \
Ethernet IRQ handler!"
#endif

static SMSC9220_EMAC *board_emac_pointer = NULL;
const struct smsc9220_eth_dev_t* SMSC9220_EMAC::dev = &SMSC9220_ETH_DEV;

extern "C" void SMSC9220_Ethernet_Interrupt_Handler(void)
{
    if (smsc9220_get_interrupt(SMSC9220_EMAC::dev,
                                 SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL)) {
        board_emac_pointer->rx_isr();
        smsc9220_clear_interrupt(SMSC9220_EMAC::dev,
                                 SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);
        smsc9220_disable_interrupt(SMSC9220_EMAC::dev,
                                   SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);
    }
}

SMSC9220_EMAC::SMSC9220_EMAC() : receiver_thread(LINK_STATUS_THREAD_PRIORITY,
                                       (uint32_t)LINK_STATUS_THREAD_STACKSIZE)
{
}

/** \brief Ethernet receive interrupt handler
 *
 *  This function handles the receive interrupt.
 */
void SMSC9220_EMAC::rx_isr()
{
    receiver_thread.flags_set(FLAG_RX);
}

/** \brief  Allocates a emac_mem_buf_t and returns the data from the incoming
 * packet.
 *
 *  \return a emac_mem_buf_t filled with the received packet
 * (including MAC header)
 */
emac_mem_buf_t *SMSC9220_EMAC::low_level_input()
{
    emac_mem_buf_t *p = NULL;
    uint32_t message_length = 0;
    uint32_t received_bytes = 0;

    message_length = smsc9220_peek_next_packet_size(dev);
    if (message_length == 0) {
        return p;
    } else {
        /* The Ethernet controller cannot remove CRC from the end of the
         * incoming packet, thus it should be taken into account when
         * calculating the actual message length.*/
        message_length -= CRC_LENGTH_BYTES;
    }

    p = _memory_manager->alloc_heap(message_length,
                                    SMSC9220_BUFF_ALIGNMENT);

    if (p != NULL) {
        _RXLockMutex.lock();
        received_bytes = smsc9220_receive_by_chunks(dev,
                                  (char*)_memory_manager->get_ptr(p),
                                  _memory_manager->get_len(p));
        if(received_bytes == 0){
            _memory_manager->free(p);
            p = nullptr;
        } else {
            _memory_manager->set_len(p, received_bytes);
        }
        _RXLockMutex.unlock();
    }

    return p;
}

/** \brief  Receiver thread.
 *
 * Woken by thread flags to receive packets or clean up transmit
 *
 *  \param[in] params pointer to the interface data
 */
void SMSC9220_EMAC::receiver_thread_function(void* params)
{
    struct SMSC9220_EMAC *smsc9220_enet = static_cast<SMSC9220_EMAC *>(params);

    while(1) {
        uint32_t flags = ThisThread::flags_wait_any(FLAG_RX);

        if (flags & FLAG_RX) {
            smsc9220_enet->packet_rx();
        }
    }
}

/** \brief  Packet reception task
 *
 * This task is called when a packet is received. It will
 * pass the packet to the Network Stack.
 */
void SMSC9220_EMAC::packet_rx()
{
    emac_mem_buf_t *p;
    p = low_level_input();
    if(p != NULL) {
        _emac_link_input_cb(p);
    }
    smsc9220_enable_interrupt(dev, SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);
}

bool SMSC9220_EMAC::link_out(emac_mem_buf_t *buf)
{
    if(buf == NULL) {
        return false;
    } else {
        uint32_t buffer_chain_length = 0;
        enum smsc9220_error_t error = SMSC9220_ERROR_NONE;
        /* If buffer is chained or not aligned then
         * make a contiguous aligned copy of it */
        if (_memory_manager->get_next(buf) ||
            reinterpret_cast<uint32_t>(_memory_manager->get_ptr(buf)) %
                                                      SMSC9220_BUFF_ALIGNMENT) {
            emac_mem_buf_t *copy_buf;
            copy_buf = _memory_manager->alloc_heap(
                                             _memory_manager->get_total_len(buf),
                                             SMSC9220_BUFF_ALIGNMENT);
            if (NULL == copy_buf) {
                _memory_manager->free(buf);
                return false;
            }

            /* Copy to new buffer and free original */
            _memory_manager->copy(copy_buf, buf);
            _memory_manager->free(buf);
            buf = copy_buf;
        }

        buffer_chain_length = _memory_manager->get_total_len(buf);

        _TXLockMutex.lock();
        error = smsc9220_send_by_chunks(dev,
                                      buffer_chain_length,
                                      true,
                                      (const char*)_memory_manager->get_ptr(buf),
                                      _memory_manager->get_len(buf));
        _memory_manager->free(buf);
        _TXLockMutex.unlock();
        return (error == SMSC9220_ERROR_NONE);
    }
}

void SMSC9220_EMAC::link_status_task()
{
    uint32_t phy_basic_status_reg_value = 0;
    bool current_link_status_up = false;

    /* Get current status */
    smsc9220_phy_regread(dev, SMSC9220_PHY_REG_OFFSET_BSTATUS,
                         &phy_basic_status_reg_value);

    current_link_status_up = (bool)(phy_basic_status_reg_value &
                          (1ul << (PHY_REG_BSTATUS_LINK_STATUS_INDEX)));

    /* Compare with the previous state */
    if (current_link_status_up != _prev_link_status_up) {
        _emac_link_state_cb(current_link_status_up);
        _prev_link_status_up = current_link_status_up;
    }

}

bool SMSC9220_EMAC::power_up()
{
    board_emac_pointer = this;
    receiver_thread.start(callback(&SMSC9220_EMAC::receiver_thread_function,
                                   this));

    /* Initialize the hardware */
    enum smsc9220_error_t init_successful = smsc9220_init(dev, &thread_sleep_for);
    if (init_successful != SMSC9220_ERROR_NONE) {
        return false;
    }

    /* Init FIFO level interrupts: use Rx status level irq to trigger
     * interrupts for any non-processed packets, while Tx is not irq driven */
    smsc9220_set_fifo_level_irq(dev, SMSC9220_FIFO_LEVEL_IRQ_RX_STATUS_POS,
            SMSC9220_FIFO_LEVEL_IRQ_LEVEL_MIN);
    smsc9220_set_fifo_level_irq(dev, SMSC9220_FIFO_LEVEL_IRQ_TX_STATUS_POS,
            SMSC9220_FIFO_LEVEL_IRQ_LEVEL_MIN);
    smsc9220_set_fifo_level_irq(dev, SMSC9220_FIFO_LEVEL_IRQ_TX_DATA_POS,
            SMSC9220_FIFO_LEVEL_IRQ_LEVEL_MAX);

    /* Enable Ethernet interrupts in NVIC */
    NVIC_EnableIRQ(ETHERNET_IRQn);
    smsc9220_enable_interrupt(dev, SMSC9220_INTERRUPT_RX_STATUS_FIFO_LEVEL);

    /* Trigger thread to deal with any RX packets that arrived
     * before receiver_thread was started */
    rx_isr();
    _prev_link_status_up = PHY_STATE_LINK_DOWN;
    mbed::mbed_event_queue()->call(mbed::callback(this,
                                             &SMSC9220_EMAC::link_status_task));

    /* Allow the Link Status task to detect the initial link state */
    ThisThread::sleep_for(10ms);
    _link_status_task_handle = mbed::mbed_event_queue()->call_every(
                              LINK_STATUS_TASK_PERIOD_MS,
                              mbed::callback(this,
                                             &SMSC9220_EMAC::link_status_task));

    return true;
}

uint32_t SMSC9220_EMAC::get_mtu_size() const
{
    return SMSC9220_ETH_MTU_SIZE;
}

uint32_t SMSC9220_EMAC::get_align_preference() const
{
    return SMSC9220_BUFF_ALIGNMENT;
}

void SMSC9220_EMAC::get_ifname(char *name, uint8_t size) const
{
    memcpy(name, SMSC9220_ETH_IF_NAME, (size < sizeof(SMSC9220_ETH_IF_NAME)) ?
                                           size : sizeof(SMSC9220_ETH_IF_NAME));
}

uint8_t SMSC9220_EMAC::get_hwaddr_size() const
{
    return SMSC9220_HWADDR_SIZE;
}

bool SMSC9220_EMAC::get_hwaddr(uint8_t *addr) const
{
    if(smsc9220_read_mac_address(dev, (char*)addr) == SMSC9220_ERROR_NONE) {
        return true;
    } else {
        return false;
    }
}

void SMSC9220_EMAC::set_hwaddr(const uint8_t *addr)
{
    if (!addr) {
        return;
    }

    memcpy(_hwaddr, addr, sizeof _hwaddr);
    uint32_t mac_low = 0;
    uint32_t mac_high = 0;

    /* Using local variables to make sure the right alignment is used */
    memcpy((void*)&mac_low, (void*)addr, 4);
    memcpy((void*)&mac_high, (void*)(addr+4), 2);

    if (smsc9220_mac_regwrite(dev, SMSC9220_MAC_REG_OFFSET_ADDRL, mac_low)) {
        return;
    }
    if (smsc9220_mac_regwrite(dev, SMSC9220_MAC_REG_OFFSET_ADDRH, mac_high)) {
        return;
    }
}

void SMSC9220_EMAC::set_link_input_cb(emac_link_input_cb_t input_cb)
{
    _emac_link_input_cb = input_cb;
}

void SMSC9220_EMAC::set_link_state_cb(emac_link_state_change_cb_t state_cb)
{
    _emac_link_state_cb = state_cb;
}

void SMSC9220_EMAC::add_multicast_group(const uint8_t *addr)
{
    // No action for now
}

void SMSC9220_EMAC::remove_multicast_group(const uint8_t *addr)
{
    // No action for now
}

void SMSC9220_EMAC::set_all_multicast(bool all)
{
    // No action for now
}

void SMSC9220_EMAC::power_down()
{
    // No action for now
}

void SMSC9220_EMAC::set_memory_manager(EMACMemoryManager &mem_mngr)
{
    _memory_manager = &mem_mngr;
}

SMSC9220_EMAC &SMSC9220_EMAC::get_instance() {
    static SMSC9220_EMAC emac;
    return emac;
}

/* Weak so a module can override */
MBED_WEAK EMAC &EMAC::get_default_instance() {
    return SMSC9220_EMAC::get_instance();
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/api/atom_api_auto_updater.h"

#include "base/time/time.h"
#include "base/values.h"
#include "browser/auto_updater.h"
#include "common/v8/native_type_conversions.h"

#include "common/v8/node_common.h"

namespace atom {

namespace api {

AutoUpdater::AutoUpdater(v8::Handle<v8::Object> wrapper)
    : EventEmitter(wrapper) {
  auto_updater::AutoUpdater::SetDelegate(this);
}

AutoUpdater::~AutoUpdater() {
  auto_updater::AutoUpdater::SetDelegate(NULL);
}

void AutoUpdater::OnError(const std::string& error) {
  base::ListValue args;
  args.AppendString(error);
  Emit("error", &args);
}

void AutoUpdater::OnCheckingForUpdate() {
  Emit("checking-for-update");
}

void AutoUpdater::OnUpdateAvailable() {
  Emit("update-available");
}

void AutoUpdater::OnUpdateNotAvailable() {
  Emit("update-not-available");
}

void AutoUpdater::OnUpdateDownloaded(const std::string& release_notes,
                                     const std::string& release_name,
                                     const base::Time& release_date,
                                     const std::string& update_url,
                                     const base::Closure& quit_and_install) {
  quit_and_install_ = quit_and_install;

  base::ListValue args;
  args.AppendString(release_notes);
  args.AppendString(release_name);
  args.AppendDouble(release_date.ToJsTime());
  args.AppendString(update_url);
  Emit("update-downloaded-raw", &args);
}

// static
void AutoUpdater::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (!args.IsConstructCall())
    return node::ThrowError("Require constructor call");

  new AutoUpdater(args.This());
}

// static
void AutoUpdater::SetFeedURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
  auto_updater::AutoUpdater::SetFeedURL(FromV8Value(args[0]));
}

// static
void AutoUpdater::CheckForUpdates(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  auto_updater::AutoUpdater::CheckForUpdates();
}

// static
void AutoUpdater::QuitAndInstall(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  AutoUpdater* self = AutoUpdater::Unwrap<AutoUpdater>(args.This());
  self->quit_and_install_.Run();
}

// static
void AutoUpdater::Initialize(v8::Handle<v8::Object> target) {
  v8::Local<v8::FunctionTemplate> t(
      v8::FunctionTemplate::New(AutoUpdater::New));
  t->InstanceTemplate()->SetInternalFieldCount(1);
  t->SetClassName(v8::String::NewSymbol("AutoUpdater"));

  NODE_SET_PROTOTYPE_METHOD(t, "setFeedUrl", SetFeedURL);
  NODE_SET_PROTOTYPE_METHOD(t, "checkForUpdates", CheckForUpdates);
  NODE_SET_PROTOTYPE_METHOD(t, "quitAndInstall", QuitAndInstall);

  target->Set(v8::String::NewSymbol("AutoUpdater"), t->GetFunction());
}

}  // namespace api

}  // namespace atom

NODE_MODULE(atom_browser_auto_updater, atom::api::AutoUpdater::Initialize)
<commit_msg>Fix crash when calling quitAndUpdate without any update.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/api/atom_api_auto_updater.h"

#include "base/time/time.h"
#include "base/values.h"
#include "browser/auto_updater.h"
#include "common/v8/native_type_conversions.h"

#include "common/v8/node_common.h"

namespace atom {

namespace api {

AutoUpdater::AutoUpdater(v8::Handle<v8::Object> wrapper)
    : EventEmitter(wrapper) {
  auto_updater::AutoUpdater::SetDelegate(this);
}

AutoUpdater::~AutoUpdater() {
  auto_updater::AutoUpdater::SetDelegate(NULL);
}

void AutoUpdater::OnError(const std::string& error) {
  base::ListValue args;
  args.AppendString(error);
  Emit("error", &args);
}

void AutoUpdater::OnCheckingForUpdate() {
  Emit("checking-for-update");
}

void AutoUpdater::OnUpdateAvailable() {
  Emit("update-available");
}

void AutoUpdater::OnUpdateNotAvailable() {
  Emit("update-not-available");
}

void AutoUpdater::OnUpdateDownloaded(const std::string& release_notes,
                                     const std::string& release_name,
                                     const base::Time& release_date,
                                     const std::string& update_url,
                                     const base::Closure& quit_and_install) {
  quit_and_install_ = quit_and_install;

  base::ListValue args;
  args.AppendString(release_notes);
  args.AppendString(release_name);
  args.AppendDouble(release_date.ToJsTime());
  args.AppendString(update_url);
  Emit("update-downloaded-raw", &args);
}

// static
void AutoUpdater::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (!args.IsConstructCall())
    return node::ThrowError("Require constructor call");

  new AutoUpdater(args.This());
}

// static
void AutoUpdater::SetFeedURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
  auto_updater::AutoUpdater::SetFeedURL(FromV8Value(args[0]));
}

// static
void AutoUpdater::CheckForUpdates(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  auto_updater::AutoUpdater::CheckForUpdates();
}

// static
void AutoUpdater::QuitAndInstall(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  AutoUpdater* self = AutoUpdater::Unwrap<AutoUpdater>(args.This());

  if (!self->quit_and_install_.is_null()) {
    self->quit_and_install_.Run();
    self->quit_and_install_.Reset();
  }
}

// static
void AutoUpdater::Initialize(v8::Handle<v8::Object> target) {
  v8::Local<v8::FunctionTemplate> t(
      v8::FunctionTemplate::New(AutoUpdater::New));
  t->InstanceTemplate()->SetInternalFieldCount(1);
  t->SetClassName(v8::String::NewSymbol("AutoUpdater"));

  NODE_SET_PROTOTYPE_METHOD(t, "setFeedUrl", SetFeedURL);
  NODE_SET_PROTOTYPE_METHOD(t, "checkForUpdates", CheckForUpdates);
  NODE_SET_PROTOTYPE_METHOD(t, "quitAndInstall", QuitAndInstall);

  target->Set(v8::String::NewSymbol("AutoUpdater"), t->GetFunction());
}

}  // namespace api

}  // namespace atom

NODE_MODULE(atom_browser_auto_updater, atom::api::AutoUpdater::Initialize)
<|endoftext|>


<commit_before>// Copyright 2016 The Brave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "brave/renderer/brave_content_renderer_client.h"

#include "atom/renderer/content_settings_manager.h"
#include "brave/renderer/printing/brave_print_web_view_helper_delegate.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/secure_origin_whitelist.h"
#include "chrome/renderer/chrome_render_frame_observer.h"
#include "chrome/renderer/chrome_render_thread_observer.h"
#include "chrome/renderer/chrome_render_view_observer.h"
#include "chrome/renderer/content_settings_observer.h"
#include "chrome/renderer/net/net_error_helper.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "content/public/common/content_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include "components/autofill/content/renderer/password_generation_agent.h"
#include "components/network_hints/renderer/prescient_networking_dispatcher.h"
#include "components/printing/renderer/print_web_view_helper.h"
#include "components/visitedlink/renderer/visitedlink_slave.h"
#include "components/web_cache/renderer/web_cache_impl.h"
#include "third_party/WebKit/public/platform/URLConversion.h"
#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPlugin.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#if defined(OS_WIN)
#include <Shobjidl.h>
#include "base/command_line.h"
#include "atom/common/options_switches.h"
#endif

#if defined(ENABLE_EXTENSIONS)
#include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
#endif

using autofill::AutofillAgent;
using autofill::PasswordAutofillAgent;
using autofill::PasswordGenerationAgent;
using blink::WebLocalFrame;
using blink::WebPlugin;
using blink::WebPluginParams;
using blink::WebSecurityOrigin;
using blink::WebSecurityPolicy;
using blink::WebString;

namespace brave {

BraveContentRendererClient::BraveContentRendererClient() {
}

void BraveContentRendererClient::RenderThreadStarted() {
  content::RenderThread* thread = content::RenderThread::Get();

  content_settings_manager_ = atom::ContentSettingsManager::GetInstance();
  #if defined(OS_WIN)
    // Set ApplicationUserModelID in renderer process.
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    base::string16 app_id =
        command_line->GetSwitchValueNative(atom::switches::kAppUserModelId);
    if (!app_id.empty()) {
      SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
    }
  #endif

  chrome_observer_.reset(new ChromeRenderThreadObserver());
  web_cache_impl_.reset(new web_cache::WebCacheImpl());

#if defined(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderThreadStarted();
#endif

  prescient_networking_dispatcher_.reset(
      new network_hints::PrescientNetworkingDispatcher());
  visited_link_slave_.reset(new visitedlink::VisitedLinkSlave());
  thread->AddObserver(chrome_observer_.get());
  thread->AddObserver(visited_link_slave_.get());

  std::set<GURL> origins;
  GetSecureOriginWhitelist(&origins);
  for (const GURL& origin : origins) {
    WebSecurityPolicy::addOriginTrustworthyWhiteList(
        WebSecurityOrigin::create(origin));
  }

  std::set<std::string> schemes;
  GetSchemesBypassingSecureContextCheckWhitelist(&schemes);
  for (const std::string& scheme : schemes) {
    WebSecurityPolicy::addSchemeToBypassSecureContextWhitelist(
        WebString::fromUTF8(scheme));
  }
}

unsigned long long BraveContentRendererClient::VisitedLinkHash(  // NOLINT
    const char* canonical_url, size_t length) {
  return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
}

bool BraveContentRendererClient::IsLinkVisited(unsigned long long link_hash) {  // NOLINT
  return visited_link_slave_->IsVisited(link_hash);
}

blink::WebPrescientNetworking*
BraveContentRendererClient::GetPrescientNetworking() {
  return prescient_networking_dispatcher_.get();
}

void BraveContentRendererClient::RenderFrameCreated(
    content::RenderFrame* render_frame) {
  bool should_whitelist_for_content_settings = false;
  extensions::Dispatcher* ext_dispatcher = NULL;
#if defined(ENABLE_EXTENSIONS)
  ext_dispatcher =
      ChromeExtensionsRendererClient::GetInstance()->extension_dispatcher();
#endif
  ContentSettingsObserver* content_settings = new ContentSettingsObserver(
      render_frame, ext_dispatcher, should_whitelist_for_content_settings);
  if (chrome_observer_.get()) {
    content_settings->SetContentSettingRules(
        chrome_observer_->content_setting_rules());
  }

  if (content_settings_manager_) {
    content_settings->SetContentSettingsManager(content_settings_manager_);
  }

#if defined(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderFrameCreated(
      render_frame);
#endif

#if defined(ENABLE_PLUGINS)
  new PepperHelper(render_frame);
#endif

  new NetErrorHelper(render_frame);

  PasswordAutofillAgent* password_autofill_agent =
      new PasswordAutofillAgent(render_frame);
  PasswordGenerationAgent* password_generation_agent =
      new PasswordGenerationAgent(render_frame, password_autofill_agent);
  new AutofillAgent(render_frame, password_autofill_agent,
                    password_generation_agent);
}

void BraveContentRendererClient::RenderViewCreated(
    content::RenderView* render_view) {
#if defined(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderViewCreated(render_view);
#endif
#if defined(ENABLE_PRINTING)
  new printing::PrintWebViewHelper(
      render_view, std::unique_ptr<printing::PrintWebViewHelper::Delegate>(
                       new BravePrintWebViewHelperDelegate()));
#endif
  new ChromeRenderViewObserver(render_view, web_cache_impl_.get());
}

bool BraveContentRendererClient::OverrideCreatePlugin(
    content::RenderFrame* render_frame,
    WebLocalFrame* frame,
    const WebPluginParams& params,
    WebPlugin** plugin) {
  std::string orig_mime_type = params.mimeType.utf8();
  if (orig_mime_type == content::kBrowserPluginMimeType)
    return false;

  GURL url(params.url);
#if defined(ENABLE_PLUGINS)
  ChromeViewHostMsg_GetPluginInfo_Output output;
  WebString top_origin = frame->top()->getSecurityOrigin().toString();
  render_frame->Send(new ChromeViewHostMsg_GetPluginInfo(
      render_frame->GetRoutingID(), url, blink::WebStringToGURL(top_origin),
      orig_mime_type, &output));

  *plugin = CreatePlugin(render_frame, frame, params, output);
#else  // !defined(ENABLE_PLUGINS)
  PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
  *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
                render_frame, frame, params)->plugin();
#endif  // defined(ENABLE_PLUGINS)
  return true;
}

}  // namespace brave
<commit_msg>Better choice of include file (idl files are generated)<commit_after>// Copyright 2016 The Brave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "brave/renderer/brave_content_renderer_client.h"

#include "atom/renderer/content_settings_manager.h"
#include "brave/renderer/printing/brave_print_web_view_helper_delegate.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/secure_origin_whitelist.h"
#include "chrome/renderer/chrome_render_frame_observer.h"
#include "chrome/renderer/chrome_render_thread_observer.h"
#include "chrome/renderer/chrome_render_view_observer.h"
#include "chrome/renderer/content_settings_observer.h"
#include "chrome/renderer/net/net_error_helper.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "content/public/common/content_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include "components/autofill/content/renderer/password_generation_agent.h"
#include "components/network_hints/renderer/prescient_networking_dispatcher.h"
#include "components/printing/renderer/print_web_view_helper.h"
#include "components/visitedlink/renderer/visitedlink_slave.h"
#include "components/web_cache/renderer/web_cache_impl.h"
#include "third_party/WebKit/public/platform/URLConversion.h"
#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPlugin.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#if defined(OS_WIN)
#include <shlobj.h>
#include "base/command_line.h"
#include "atom/common/options_switches.h"
#endif

#if defined(ENABLE_EXTENSIONS)
#include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
#endif

using autofill::AutofillAgent;
using autofill::PasswordAutofillAgent;
using autofill::PasswordGenerationAgent;
using blink::WebLocalFrame;
using blink::WebPlugin;
using blink::WebPluginParams;
using blink::WebSecurityOrigin;
using blink::WebSecurityPolicy;
using blink::WebString;

namespace brave {

BraveContentRendererClient::BraveContentRendererClient() {
}

void BraveContentRendererClient::RenderThreadStarted() {
  content::RenderThread* thread = content::RenderThread::Get();

  content_settings_manager_ = atom::ContentSettingsManager::GetInstance();
  #if defined(OS_WIN)
    // Set ApplicationUserModelID in renderer process.
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    base::string16 app_id =
        command_line->GetSwitchValueNative(atom::switches::kAppUserModelId);
    if (!app_id.empty()) {
      SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
    }
  #endif

  chrome_observer_.reset(new ChromeRenderThreadObserver());
  web_cache_impl_.reset(new web_cache::WebCacheImpl());

#if defined(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderThreadStarted();
#endif

  prescient_networking_dispatcher_.reset(
      new network_hints::PrescientNetworkingDispatcher());
  visited_link_slave_.reset(new visitedlink::VisitedLinkSlave());
  thread->AddObserver(chrome_observer_.get());
  thread->AddObserver(visited_link_slave_.get());

  std::set<GURL> origins;
  GetSecureOriginWhitelist(&origins);
  for (const GURL& origin : origins) {
    WebSecurityPolicy::addOriginTrustworthyWhiteList(
        WebSecurityOrigin::create(origin));
  }

  std::set<std::string> schemes;
  GetSchemesBypassingSecureContextCheckWhitelist(&schemes);
  for (const std::string& scheme : schemes) {
    WebSecurityPolicy::addSchemeToBypassSecureContextWhitelist(
        WebString::fromUTF8(scheme));
  }
}

unsigned long long BraveContentRendererClient::VisitedLinkHash(  // NOLINT
    const char* canonical_url, size_t length) {
  return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
}

bool BraveContentRendererClient::IsLinkVisited(unsigned long long link_hash) {  // NOLINT
  return visited_link_slave_->IsVisited(link_hash);
}

blink::WebPrescientNetworking*
BraveContentRendererClient::GetPrescientNetworking() {
  return prescient_networking_dispatcher_.get();
}

void BraveContentRendererClient::RenderFrameCreated(
    content::RenderFrame* render_frame) {
  bool should_whitelist_for_content_settings = false;
  extensions::Dispatcher* ext_dispatcher = NULL;
#if defined(ENABLE_EXTENSIONS)
  ext_dispatcher =
      ChromeExtensionsRendererClient::GetInstance()->extension_dispatcher();
#endif
  ContentSettingsObserver* content_settings = new ContentSettingsObserver(
      render_frame, ext_dispatcher, should_whitelist_for_content_settings);
  if (chrome_observer_.get()) {
    content_settings->SetContentSettingRules(
        chrome_observer_->content_setting_rules());
  }

  if (content_settings_manager_) {
    content_settings->SetContentSettingsManager(content_settings_manager_);
  }

#if defined(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderFrameCreated(
      render_frame);
#endif

#if defined(ENABLE_PLUGINS)
  new PepperHelper(render_frame);
#endif

  new NetErrorHelper(render_frame);

  PasswordAutofillAgent* password_autofill_agent =
      new PasswordAutofillAgent(render_frame);
  PasswordGenerationAgent* password_generation_agent =
      new PasswordGenerationAgent(render_frame, password_autofill_agent);
  new AutofillAgent(render_frame, password_autofill_agent,
                    password_generation_agent);
}

void BraveContentRendererClient::RenderViewCreated(
    content::RenderView* render_view) {
#if defined(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderViewCreated(render_view);
#endif
#if defined(ENABLE_PRINTING)
  new printing::PrintWebViewHelper(
      render_view, std::unique_ptr<printing::PrintWebViewHelper::Delegate>(
                       new BravePrintWebViewHelperDelegate()));
#endif
  new ChromeRenderViewObserver(render_view, web_cache_impl_.get());
}

bool BraveContentRendererClient::OverrideCreatePlugin(
    content::RenderFrame* render_frame,
    WebLocalFrame* frame,
    const WebPluginParams& params,
    WebPlugin** plugin) {
  std::string orig_mime_type = params.mimeType.utf8();
  if (orig_mime_type == content::kBrowserPluginMimeType)
    return false;

  GURL url(params.url);
#if defined(ENABLE_PLUGINS)
  ChromeViewHostMsg_GetPluginInfo_Output output;
  WebString top_origin = frame->top()->getSecurityOrigin().toString();
  render_frame->Send(new ChromeViewHostMsg_GetPluginInfo(
      render_frame->GetRoutingID(), url, blink::WebStringToGURL(top_origin),
      orig_mime_type, &output));

  *plugin = CreatePlugin(render_frame, frame, params, output);
#else  // !defined(ENABLE_PLUGINS)
  PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
  *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
                render_frame, frame, params)->plugin();
#endif  // defined(ENABLE_PLUGINS)
  return true;
}

}  // namespace brave
<|endoftext|>


<commit_before>// Semmle test case for rule TaintedCondition.ql (Untrusted input for a condition).
// Associated with CWE-807: Reliance on Untrusted Inputs in a Security Decision
// http://cwe.mitre.org/data/definitions/807.html

///// Library functions //////
extern int strcmp(const char *s1, const char *s2);
extern char *getenv(const char *name);
extern int strlen(const char *s);

//// Test code /////
int adminPrivileges;
extern const char* adminCookie;

const char *currentUser;

void processRequest()
{
     const char *userName = getenv("USER_NAME");

     // BAD: the condition is controllable by the user, and
     // the body of the if makes a security decision.
     if (!strcmp(userName, "admin")) {
        adminPrivileges = 1;
     }

     // OK, since the comparison is not to a constant
     const char *cookie = getenv("COOKIE");
     if (!strcmp(cookie, adminCookie)) {
        adminPrivileges = 1;
     }

     if (!strcmp(userName, "nobody")) {
        adminPrivileges = 0; // OK, since it's a 0 and not a 1
     }

     // BAD, but it requires pointer analysis to catch
     const char** userp = &currentUser;
     *userp = userName;
     if (!strcmp(currentUser, "admin")) {
       adminPrivileges = 1;
     }
}

void bugWithBinop() {
     const char *userName = getenv("USER_NAME");

     // The following is tainted, but should not cause
     // the whole program to be considered tainted.
     int bytes = strlen(userName) + 1;
}
<commit_msg>C++: Update comment.<commit_after>// Semmle test case for rule TaintedCondition.ql (Untrusted input for a condition).
// Associated with CWE-807: Reliance on Untrusted Inputs in a Security Decision
// http://cwe.mitre.org/data/definitions/807.html

///// Library functions //////
extern int strcmp(const char *s1, const char *s2);
extern char *getenv(const char *name);
extern int strlen(const char *s);

//// Test code /////
int adminPrivileges;
extern const char* adminCookie;

const char *currentUser;

void processRequest()
{
     const char *userName = getenv("USER_NAME");

     // BAD: the condition is controllable by the user, and
     // the body of the if makes a security decision.
     if (!strcmp(userName, "admin")) {
        adminPrivileges = 1;
     }

     // OK, since the comparison is not to a constant
     const char *cookie = getenv("COOKIE");
     if (!strcmp(cookie, adminCookie)) {
        adminPrivileges = 1;
     }

     if (!strcmp(userName, "nobody")) {
        adminPrivileges = 0; // OK, since it's a 0 and not a 1
     }

     // BAD (requires pointer analysis to catch)
     const char** userp = &currentUser;
     *userp = userName;
     if (!strcmp(currentUser, "admin")) {
       adminPrivileges = 1;
     }
}

void bugWithBinop() {
     const char *userName = getenv("USER_NAME");

     // The following is tainted, but should not cause
     // the whole program to be considered tainted.
     int bytes = strlen(userName) + 1;
}
<|endoftext|>


<commit_before>#include "crypto.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include "sha256.h"

const int PACKET_DATA_LENGTH = 32;    //bytes
const int PACKET_CHECKSUM_LENGTH = 32;
const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;

char* OTP(unsigned long long* index, const unsigned long long amount);
char* xorCharArray(const char* first, const char* second, unsigned long long length);
unsigned long long unsignedLongLongRand();
char* longToCharArray(unsigned long long num, int size);
unsigned long long charArrayToLong(const char* data, int size);
bool charArrayEquals(const char* data1, const char* data2, int size);
char* concat(const char* left, const char* right, int sizel, int sizer);
char* sha_256(char* buf);

// send command
ssize_t cwrite(int fd, const void *buf, size_t count) {
	//long indexOfPad = random integer from 0 to size of OTP in bytes
	unsigned long long* indexOfPad = unsignedLongLongRand();
	//char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);
	char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);
	//send nonce to reciever
	int n;
	n = write(fd, nonce, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//1
	//long myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));
	unsigned long long myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH));
	//2
	//byte* response = response from receiver
	char buffer[PACKET_LENGTH];
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if (n == 0) {
		//error - no message
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {
		//myChecksum != response
		return -1;
	}
	//send ok to reciever
	n = write(fd, "OK", PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2.1
	//2.2
	//for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
	for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
		//char* toSend = buf[bufferIndex];
		char* toSend = buf[bufferIndex];
		//char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(indexOfPad, PACKET_LENGTH);
		//char* mac = sha-256(concat(toSend, key));
		char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		//char* message = concat(toSend, mac);
		char* message = concat(toSend, mac, bufferIndex, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);
		//char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(indexOfPad, PACKET_LENGTH);
		//send xor(message, pad) to reciever
		n = write(fd, xorCharArray(message, pad), PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		//3
	}
}

// recv command
ssize_t cread(int fd, void *buf, size_t count) {
	//1
	//wait for nonce from sender
	char buffer[PACKET_LENGTH];
	int n;
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	//long indexOfPad;
	//indexOfPad = charArrayToLong(message recieved from sender);
	unsigned long long indexOfPad = charArrayToLong(buffer);
	//byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* message = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* pad = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* reply = xor(message, pad);
	char* reply = xorCharArray(message, pad, PACKET_LENGTH);
	//send reply to sender
	n = write(fd, reply, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2
	//2.1
	//recieve ok, if not retry, abort, ignore?
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	else if(std::strcmp(buffer, "OK") != 0) {
		//error - not ok
		return -1;
	}
	//2.2
	//int amount_recv = 0;
	int amount_recv = 0;
	//while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {
	while(amount_recv + PACKET_DATA_LENGTH < len) {
		//3
		//byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender
		char data[PACKET_LENGTH];
		amount_recv += read(fd, data, PACKET_LENGTH);
		//byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(&indexOfPad, PACKET_LENGTH);
		//pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(&indexOfPad, PACKET_LENGTH);
		//byte* messsage = xor(data, pad);
		char* message = xorCharArray(data, pad, PACKET_LENGTH);
		//byte* checksum = data + PACKET_DATA_LENGTH;     checksum is last part after the data
		char* checksum = message + PACKET_DATA_LENGTH;
		//byte* mac = sha-256(concat(messsage, key));     recompute mac
		//std::string msgStr(message);
		//std::string keyStr(key);
		char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {
			//checksum != mac
			return -1;
		}

		//copy message into buffer
		for(int i = 0; i < PACKET_DATA_LENGTH; i++) {
			buf[i] = message[i];
		}
		buf += PACKET_DATA_LENGTH;
	}
	return amount_recv;
}

char* OTP(unsigned long long* index, const unsigned long long amount) {
	std::ifstream pad;
	pad.open("otp.key");
	pad.seekg(*index);
	char result[amount];
	pad.read(result, amount);
	pad.close();
	*index += amount;
	return result;
	//byte pad[amount];  allocate amount bytes to return
	//seek to index in OTP
	//for(long i = 0; i < amount; i++)
		//pad[i] = readByte();  read in each byte from the file
	//*index += amount;  increment index so we don't use the same pad twice
	//return pad;
}

char* xorCharArray(const char* first, const char* second, unsigned long long length) {
	//byte result[length];
	char result[length];
	//for(long i = 0; i < length; i++) {
	for(unsigned long long i = 0; i < length; i++) {
		result[i] = first[i] ^ second[i];
	}
	return result;
}

unsigned long long unsignedLongLongRand() {
    unsigned long long rand1 = abs(rand());
    unsigned long long rand2 = abs(rand());
    rand1 <<= (sizeof(int)*8);
    unsigned long long randULL = (rand1 | rand2);
    return randULL;
}

char* longToCharArray(unsigned long long num, int size) {
	return reinterpret_cast<char*>(num);
}

unsigned long long charArrayToLong(const char* data, int size){
	return reinterpret_cast<unsigned long long>(data);
}

bool charArrayEquals(const char* data1, const char* data2, int size) {
	for(int i = 0; i < size; i++) {
		if(data1[i] != data2[i]) return false;
	}
	return true;
}

char* concat(const char* left, const char* right, int sizel, int sizer) {
	char result[sizel + sizer];
	for(int i = 0; i < sizel; i++) {
		result[i] = left[i];
	}
	for(int i = 0; i < sizer; i++) {
		result[sizel + i] = right[i];
	}
	return result;
	//std::string msgStr(left);
	//std::string keyStr(right);
	//return &(left + right)[0];
}

char* sha_256(char* buf) {
	return &sha256(buf)[0];
}
<commit_msg>fixed buffer length<commit_after>#include "crypto.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include "sha256.h"

const int PACKET_DATA_LENGTH = 32;    //bytes
const int PACKET_CHECKSUM_LENGTH = 32;
const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;

char* OTP(unsigned long long* index, const unsigned long long amount);
char* xorCharArray(const char* first, const char* second, unsigned long long length);
unsigned long long unsignedLongLongRand();
char* longToCharArray(unsigned long long num, int size);
unsigned long long charArrayToLong(const char* data, int size);
bool charArrayEquals(const char* data1, const char* data2, int size);
char* concat(const char* left, const char* right, int sizel, int sizer);
char* sha_256(char* buf);

// send command
ssize_t cwrite(int fd, const void *buf, size_t count) {
	//long indexOfPad = random integer from 0 to size of OTP in bytes
	unsigned long long* indexOfPad = unsignedLongLongRand();
	//char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);
	char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);
	//send nonce to reciever
	int n;
	n = write(fd, nonce, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//1
	//long myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));
	unsigned long long myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH));
	//2
	//byte* response = response from receiver
	char buffer[PACKET_LENGTH];
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if (n == 0) {
		//error - no message
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {
		//myChecksum != response
		return -1;
	}
	//send ok to reciever
	n = write(fd, "OK", PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2.1
	//2.2
	//for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
	for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
		//char* toSend = buf[bufferIndex];
		char* toSend = buf[bufferIndex];
		//char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(indexOfPad, PACKET_LENGTH);
		//char* mac = sha-256(concat(toSend, key));
		char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		//char* message = concat(toSend, mac);
		char* message = concat(toSend, mac, bufferIndex, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);
		//char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(indexOfPad, PACKET_LENGTH);
		//send xor(message, pad) to reciever
		n = write(fd, xorCharArray(message, pad), PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		//3
	}
}

// recv command
ssize_t cread(int fd, void *buf, size_t count) {
	//1
	//wait for nonce from sender
	char buffer[PACKET_LENGTH];
	int n;
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	//long indexOfPad;
	//indexOfPad = charArrayToLong(message recieved from sender);
	unsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH);
	//byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* message = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* pad = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* reply = xor(message, pad);
	char* reply = xorCharArray(message, pad, PACKET_LENGTH);
	//send reply to sender
	n = write(fd, reply, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2
	//2.1
	//recieve ok, if not retry, abort, ignore?
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	else if(std::strcmp(buffer, "OK") != 0) {
		//error - not ok
		return -1;
	}
	//2.2
	//int amount_recv = 0;
	int amount_recv = 0;
	//while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {
	while(amount_recv + PACKET_DATA_LENGTH < len) {
		//3
		//byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender
		char data[PACKET_LENGTH];
		amount_recv += read(fd, data, PACKET_LENGTH);
		//byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(&indexOfPad, PACKET_LENGTH);
		//pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(&indexOfPad, PACKET_LENGTH);
		//byte* messsage = xor(data, pad);
		char* message = xorCharArray(data, pad, PACKET_LENGTH);
		//byte* checksum = data + PACKET_DATA_LENGTH;     checksum is last part after the data
		char* checksum = message + PACKET_DATA_LENGTH;
		//byte* mac = sha-256(concat(messsage, key));     recompute mac
		//std::string msgStr(message);
		//std::string keyStr(key);
		char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {
			//checksum != mac
			return -1;
		}

		//copy message into buffer
		for(int i = 0; i < PACKET_DATA_LENGTH; i++) {
			buf[i] = message[i];
		}
		buf += PACKET_DATA_LENGTH;
	}
	return amount_recv;
}

char* OTP(unsigned long long* index, const unsigned long long amount) {
	std::ifstream pad;
	pad.open("otp.key");
	pad.seekg(*index);
	char result[amount];
	pad.read(result, amount);
	pad.close();
	*index += amount;
	return result;
	//byte pad[amount];  allocate amount bytes to return
	//seek to index in OTP
	//for(long i = 0; i < amount; i++)
		//pad[i] = readByte();  read in each byte from the file
	//*index += amount;  increment index so we don't use the same pad twice
	//return pad;
}

char* xorCharArray(const char* first, const char* second, unsigned long long length) {
	//byte result[length];
	char result[length];
	//for(long i = 0; i < length; i++) {
	for(unsigned long long i = 0; i < length; i++) {
		result[i] = first[i] ^ second[i];
	}
	return result;
}

unsigned long long unsignedLongLongRand() {
    unsigned long long rand1 = abs(rand());
    unsigned long long rand2 = abs(rand());
    rand1 <<= (sizeof(int)*8);
    unsigned long long randULL = (rand1 | rand2);
    return randULL;
}

char* longToCharArray(unsigned long long num, int size) {
	return reinterpret_cast<char*>(num);
}

unsigned long long charArrayToLong(const char* data, int size){
	return reinterpret_cast<unsigned long long>(data);
}

bool charArrayEquals(const char* data1, const char* data2, int size) {
	for(int i = 0; i < size; i++) {
		if(data1[i] != data2[i]) return false;
	}
	return true;
}

char* concat(const char* left, const char* right, int sizel, int sizer) {
	char result[sizel + sizer];
	for(int i = 0; i < sizel; i++) {
		result[i] = left[i];
	}
	for(int i = 0; i < sizer; i++) {
		result[sizel + i] = right[i];
	}
	return result;
	//std::string msgStr(left);
	//std::string keyStr(right);
	//return &(left + right)[0];
}

char* sha_256(char* buf) {
	return &sha256(buf)[0];
}
<|endoftext|>


<commit_before>
#include "numerics/cbrt.hpp"

#include <pmmintrin.h>

#include <limits>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/double_precision.hpp"
#include "testing_utilities/almost_equals.hpp"

namespace principia {
namespace numerics {

using ::testing::AllOf;
using ::testing::Eq;
using ::testing::Gt;
using ::testing::Lt;
using ::testing::Truly;

class CubeRootTest : public ::testing::Test {
 protected:
  static std::uint64_t Bits(double const x) {
    return _mm_cvtsi128_si64(_mm_castpd_si128(_mm_set_sd(x)));
  }

  static double FromBits(std::uint64_t const x) {
    return _mm_cvtsd_f64(_mm_castsi128_pd(_mm_cvtsi64_si128(x)));
  }

  static double ULP(double const x) {
    return FromBits(Bits(x) + 1) - x;
  }
};

TEST_F(CubeRootTest, Cbrt2) {
  EXPECT_THAT(Cbrt(2), Eq(0x1.4'28A2'F98D'728Bp0));
  EXPECT_THAT(Cbrt(2) * Cbrt(2) * Cbrt(2), Eq(2));
}

TEST_F(CubeRootTest, Rescaling) {
  EXPECT_THAT(0x1p-340 * Cbrt(0x1p1021), Eq(Cbrt(2)));
  EXPECT_THAT(0x1p341 * Cbrt(0x1p-1022), Eq(Cbrt(2)));
  EXPECT_THAT(0x1p358 * Cbrt(0x1p-1073), Eq(Cbrt(2)));
}

TEST_F(CubeRootTest, SpecialValues) {
  EXPECT_THAT(Bits(Cbrt(0)), Eq(0));
  EXPECT_THAT(Bits(Cbrt(-0.0)), Eq(0x8000'0000'0000'0000));
  EXPECT_THAT(Cbrt(std::numeric_limits<double>::infinity()),
              Eq(std::numeric_limits<double>::infinity()));
  EXPECT_THAT(Cbrt(-std::numeric_limits<double>::infinity()),
              Eq(-std::numeric_limits<double>::infinity()));
  EXPECT_THAT(Cbrt(std::numeric_limits<double>::quiet_NaN()),
              Truly(&std::isnan<double>));
  EXPECT_THAT(Cbrt(-std::numeric_limits<double>::quiet_NaN()),
              Truly(&std::isnan<double>));
}

TEST_F(CubeRootTest, BoundsOfTheRescalingRange) {
  EXPECT_THAT(Cbrt(0x1p-225), Eq(0x1p-75));
  EXPECT_THAT(Cbrt(0x1.0'0000'0000'0002p-225),
              Eq(0x1p-75 * Cbrt(0x1.0'0000'0000'0002p0)));
  EXPECT_THAT(Cbrt(0x1p237), Eq(0x1p79));
  EXPECT_THAT(Cbrt(0x1.F'FFFF'FFFF'FFFFp236),
              Eq(0x1p79 * Cbrt(0x1.F'FFFF'FFFF'FFFFp-1)));
}

TEST_F(CubeRootTest, Sign) {
  EXPECT_THAT(Cbrt(-2), Eq(-Cbrt(2)));
}

TEST_F(CubeRootTest, ParticularlyBadRounding) {
  constexpr double y = 0x1.14E35E87EA5DFp0;
  double const x = Cbrt(y);
  DoublePrecision<double> x = TwoProduct(x, x);
  DoublePrecision<DoublePrecision<double>> x =
      TwoSum(TwoProduct(x.value, x), TwoProduct(x.error, x));
  CHECK_EQ(x.error.error, 0) << x;
  auto const long_y =
      DoublePrecision<DoublePrecision<double>>(DoublePrecision<double>(y));
  DoublePrecision<DoublePrecision<double>> numerator = long_y - x;
  DoublePrecision<DoublePrecision<double>> denominator =
      TwoSum(TwoProduct(x.value, 3), TwoProduct(x.error, 3));
  double const x_error = numerator.value.value / denominator.value.value +
                         numerator.value.error / denominator.value.value;
  double const x_ulps = x_error / ULP(x);
  EXPECT_THAT(x_ulps, AllOf(Gt(0.5000551), Lt(0.5000552))) << x_ulps - 0.5;
}

}  // namespace numerics
}  // namespace principia
<commit_msg>encoding<commit_after>
#include "numerics/cbrt.hpp"

#include <pmmintrin.h>

#include <limits>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/double_precision.hpp"
#include "testing_utilities/almost_equals.hpp"

namespace principia {
namespace numerics {

using ::testing::AllOf;
using ::testing::Eq;
using ::testing::Gt;
using ::testing::Lt;
using ::testing::Truly;

class CubeRootTest : public ::testing::Test {
 protected:
  static std::uint64_t Bits(double const x) {
    return _mm_cvtsi128_si64(_mm_castpd_si128(_mm_set_sd(x)));
  }

  static double FromBits(std::uint64_t const x) {
    return _mm_cvtsd_f64(_mm_castsi128_pd(_mm_cvtsi64_si128(x)));
  }

  static double ULP(double const x) {
    return FromBits(Bits(x) + 1) - x;
  }
};

TEST_F(CubeRootTest, Cbrt2) {
  EXPECT_THAT(Cbrt(2), Eq(0x1.4'28A2'F98D'728Bp0));
  EXPECT_THAT(Cbrt(2) * Cbrt(2) * Cbrt(2), Eq(2));
}

TEST_F(CubeRootTest, Rescaling) {
  EXPECT_THAT(0x1p-340 * Cbrt(0x1p1021), Eq(Cbrt(2)));
  EXPECT_THAT(0x1p341 * Cbrt(0x1p-1022), Eq(Cbrt(2)));
  EXPECT_THAT(0x1p358 * Cbrt(0x1p-1073), Eq(Cbrt(2)));
}

TEST_F(CubeRootTest, SpecialValues) {
  EXPECT_THAT(Bits(Cbrt(0)), Eq(0));
  EXPECT_THAT(Bits(Cbrt(-0.0)), Eq(0x8000'0000'0000'0000));
  EXPECT_THAT(Cbrt(std::numeric_limits<double>::infinity()),
              Eq(std::numeric_limits<double>::infinity()));
  EXPECT_THAT(Cbrt(-std::numeric_limits<double>::infinity()),
              Eq(-std::numeric_limits<double>::infinity()));
  EXPECT_THAT(Cbrt(std::numeric_limits<double>::quiet_NaN()),
              Truly(&std::isnan<double>));
  EXPECT_THAT(Cbrt(-std::numeric_limits<double>::quiet_NaN()),
              Truly(&std::isnan<double>));
}

TEST_F(CubeRootTest, BoundsOfTheRescalingRange) {
  EXPECT_THAT(Cbrt(0x1p-225), Eq(0x1p-75));
  EXPECT_THAT(Cbrt(0x1.0'0000'0000'0002p-225),
              Eq(0x1p-75 * Cbrt(0x1.0'0000'0000'0002p0)));
  EXPECT_THAT(Cbrt(0x1p237), Eq(0x1p79));
  EXPECT_THAT(Cbrt(0x1.F'FFFF'FFFF'FFFFp236),
              Eq(0x1p79 * Cbrt(0x1.F'FFFF'FFFF'FFFFp-1)));
}

TEST_F(CubeRootTest, Sign) {
  EXPECT_THAT(Cbrt(-2), Eq(-Cbrt(2)));
}

TEST_F(CubeRootTest, ParticularlyBadRounding) {
  constexpr double y = 0x1.14E35E87EA5DFp0;
  double const x = Cbrt(y);
  DoublePrecision<double> x² = TwoProduct(x, x);
  DoublePrecision<DoublePrecision<double>> x³ =
      TwoSum(TwoProduct(x².value, x), TwoProduct(x².error, x));
  CHECK_EQ(x³.error.error, 0) << x³;
  auto const long_y =
      DoublePrecision<DoublePrecision<double>>(DoublePrecision<double>(y));
  DoublePrecision<DoublePrecision<double>> numerator = long_y - x³;
  DoublePrecision<DoublePrecision<double>> denominator =
      TwoSum(TwoProduct(x².value, 3), TwoProduct(x².error, 3));
  double const x_error = numerator.value.value / denominator.value.value +
                         numerator.value.error / denominator.value.value;
  double const x_ulps = x_error / ULP(x);
  EXPECT_THAT(x_ulps, AllOf(Gt(0.5000551), Lt(0.5000552))) << x_ulps - 0.5;
}

}  // namespace numerics
}  // namespace principia
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef tuple<int, int> edge;

int N, M;
vector<edge> V[100010];
stack<int> S;
int visited[100010];
bool loop = false;
int d[100010];

void visit(int n) {
  if (visited[n] == 1) {
    loop = true;
  } else if (visited[n] == 0) {
    visited[n] = 1;
    for (auto x : V[n]) {
      int m = get<0>(x);
      visit(m);
    }
    visited[n] = 2;
    S.push(n);
  }
}

int main () {
  cin >> N >> M;
  for (auto i = 0; i < M; ++i) {
    int L, R, D;
    cin >> L >> R >> D;
    L--;
    R--;
    V[L].push_back(edge(R, D));
  }
  for (auto i = 0; i < N; ++i) {
    visit(i);
  }
  if (loop) {
#if DEBUG == 1
    cerr << "loop" << endl;
#endif
    cout << "No" << endl;
    return 0;
  }
  fill(d, d+100010, -1);
  d[S.top()] = 0;
  while (!S.top()) {
    int now = S.top();
    // cerr << "now = " << now << endl;
    S.pop();
    for (auto x : V[now]) {
      int dst = get<0>(x);
      int dist = get<1>(x);
      if (d[dst] == -1) {
        d[dst] = dist + d[now];
      } else {
        if (d[dst] == dist + d[now]) {
          //
        } else {
#if DEBUG == 1
          cerr << "d[" << dst << "] = " << d[dst] << endl;
          cerr << "dist = " << dist
               << ", d[" << now << "] = " << d[now] << endl;
#endif
          cout << "No" << endl;
          return 0;
        }
      }
    }
  }
  cout << "Yes" << endl;
}
<commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 1 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef tuple<int, int> edge;

int N, M;
vector<edge> V[100010];
stack<int> S;
int visited[100010];
bool loop = false;
int d[100010];

void visit(int n) {
  if (visited[n] == 1) {
    loop = true;
  } else if (visited[n] == 0) {
    visited[n] = 1;
    for (auto x : V[n]) {
      int m = get<0>(x);
      visit(m);
    }
    visited[n] = 2;
    S.push(n);
  }
}

int main () {
  cin >> N >> M;
  for (auto i = 0; i < M; ++i) {
    int L, R, D;
    cin >> L >> R >> D;
    L--;
    R--;
    V[L].push_back(edge(R, D));
  }
  for (auto i = 0; i < N; ++i) {
    visit(i);
  }
  if (loop) {
#if DEBUG == 1
    cerr << "loop" << endl;
#endif
    cout << "No" << endl;
    return 0;
  }
  fill(d, d+100010, -1);
  d[S.top()] = 0;
  while (!S.top()) {
    int now = S.top();
    // cerr << "now = " << now << endl;
    S.pop();
    for (auto x : V[now]) {
      int dst = get<0>(x);
      int dist = get<1>(x);
      if (d[dst] == -1) {
        d[dst] = dist + d[now];
      } else {
        if (d[dst] == dist + d[now]) {
          //
        } else {
#if DEBUG == 1
          cerr << "d[" << dst << "] = " << d[dst] << endl;
          cerr << "dist = " << dist
               << ", d[" << now << "] = " << d[now] << endl;
#endif
          cout << "No" << endl;
          return 0;
        }
      }
    }
  }
  cout << "Yes" << endl;
}
<|endoftext|>


<commit_before>#include "PatternMatch.hpp"

PatternMatch::resultslist PatternMatch::patternMatch ( std::list<patternvector> allpatterns, const int findoption ) {

	/*
	patterns that are intended to be periodic may be overcounted, because we are not guaranteed to return
	to the same place in phase space
	*/

	// make sure findoption has allowable value
	const std::list<int> allowableoptions = {1,2,3};
	if ( std::find( allowableoptions.begin(), allowableoptions.end(), findoption ) == allowableoptions.end() ) {
		throw;
	}

	PatternMatch::resultslist results;
	patternvector oldpattern = allpatterns.front();
	PatternMatch::memoize keepcount ( oldpattern.size(), std::make_pair({},{}) ); // initializes vector of pairs of empty lists

	for ( auto pattern : allpatterns ) {
		// keep keys in keepcount that are going to be searched again
		_pruneRegister( pattern, oldpattern, keepcount );
		// perform the pattern match
		uint64_t nummatches = _patternMatch( pattern, findoption, keepcount );

		if ( nummatches > 0 ) {
			results.push_back( std::make_pair(pattern, nummatches) );
			if ( findoption == 1 ) {
				return results;
			}
		}
		oldpattern = pattern;
	}
	return results;
}

void PatternMatch::_pruneRegister( patternvector newpattern, patternvector oldpattern, PatternMatch::memoize& keepcount ) {
	std::reverse(newpattern.begin(),newpattern.end());
	std::reverse(oldpattern.begin(),oldpattern.end());
	uint64_t tailmatch = 0;

	for ( uint64_t i = 0; i < std::min(newpattern.size(),oldpattern.size()); ++i ) {
		if ( newpattern[ i ] == oldpattern[ i ] ) {
			tailmatch += 1;
		} else {
			break;
		}
	}

	if ( tailmatch == 0 ) {
		keepcount.assign ( newpattern.size(), std::make_pair({},{}) );
	} else {
		PatternMatch::memoize new_keepcount ( newpattern.size(), std::make_pair({},{}) );
		for ( int j = 0; j < tailmatch; ++j ) {
			new_keepcount[ j ] = keepcount[ j ];
		}
		keepcount = new_keepcount;
	}
}

uint64_t PatternMatch::_patternMatch ( const patternvector pattern, const int findoption, PatternMatch::memoize& keepcount ) {

	// require nonzero length pattern
	uint64_t N = pattern.size();
	if ( N < 1 ) {
		return 0;
	}

	// construct intermediate labels
	std::vector<std::string> temp = pattern;
	for ( auto& t : temp ) {
		std::replace(t.begin(),t.end(),'M','I');
		std::replace(t.begin(),t.end(),'m','D');
	}
	const std::vector<std::string> intermediates = temp;

	/* explicit initialize:
	 -- to return trivial results
	 -- to record top nodes for final counts
	 -- to avoid intermediate label on top nodes in while loop
	 **The initialization is recalculated in the while loop, unfortunately.
	*/
	std::stack< PatternMatch::node > nodes_to_visit = _initializeStack ( N, pattern.front() );
	// result for trivial pattern
	if ( N == 1 ) {
		return nodes_to_visit.size();
	}
	// record top nodes as list for later searching
	std::list<PatternMatch::node> top_nodes;
	auto tn = nodes_to_visit;
	// DEBUG
	std::cout << "\nTop nodes: ";
	// END DEBUG
	for ( int i = 0; i < tn.size(); ++i ) {
		// DEBUG
		std::cout << tn.top().first << " ";
		// END DEBUG
		top_nodes.push_back(tn.top());
		tn.pop();
	}
	// DEBUG
	std::cout << "\n";
	// END DEBUG

	// depth first search
	while ( !nodes_to_visit.empty() ) {

		// DEBUG
		std::cout << "\nNew loop: \n";
		for ( auto kvp : keepcount ) {
			std::cout << "wall " << ( kvp.first ).first << " has " << kvp.second << " matches.\n";
		}
		// END DEBUG

		auto thisnode = nodes_to_visit.top();
		nodes_to_visit.pop();

		auto wall = thisnode.first;
		auto patternlen = thisnode.second;
		auto walllabels = wallgraph[ wall ].labels;
		bool extremum_in_labels = _checkForWordInLabels( pattern[ N - patternlen ], walllabels );
		bool intermediate_in_labels = _checkForWordInLabels( intermediates[ N - patternlen ], walllabels );

		if ( !extremum_in_labels && !intermediate_in_labels ) {
			( keepcount[ patternlen ].first ).push_back( wall );
			( keepcount[ patternlen ].second ).push_back( 0 );
			continue;
		}

		bool in_top_nodes = _checkForNodeInTopNodes( thisnode, top_nodes );
		if ( intermediate_in_labels && !in_top_nodes ) {
			_addToStack( patternlen, thisnode, keepcount, nodes_to_visit );
		}

		if ( extremum_in_labels ) {
			if ( patternlen > 1 ) {
				_addToStack( patternlen-1, thisnode, keepcount, nodes_to_visit );
			// else if patternlen == 1 and extremum_in_labels, we have reached the final leaf in a path
			} else if ( findoption < 3 ) {
				return 1;
			} else {
				keepcount[ thisnode ] = 1;
			}
		}
	}

	if ( findoption < 3 ) {
		return 0;
	} else {
		uint64_t count = 0;
		for ( auto key : top_nodes ) {
			count += keepcount[ key ];
		}
		return count;
	}
}

std::stack<PatternMatch::node> PatternMatch::_initializeStack ( const uint64_t N, const std::string extremum ) {

	std::stack<PatternMatch::node> nodes_to_visit;

	for ( uint64_t i = 0; i < wallgraph.size(); ++i ) {
		if ( _checkForWordInLabels( extremum, wallgraph[ i ].labels ) ) {
			nodes_to_visit.push( std::make_pair( i, N ) );
		}
	}
	return nodes_to_visit;
}

bool PatternMatch::_checkForWordInLabels( const std::string word, const std::vector<std::set<char>> labels) {
	// match all
	for ( int i = 0; i < labels.size(); ++i ) {
		if ( labels[ i ].count( word[ i ] ) == 0 ) {
			return false;
		}
	}
	return true;
}

bool PatternMatch::_checkForNodeInTopNodes( const PatternMatch::node thisnode, const std::list<PatternMatch::node> top_nodes ) {
	// match any
	for ( auto topnode : top_nodes ) {
		if ( topnode == thisnode ) {
			return true;
		}
	}
	return false;
}

void PatternMatch::_addToStack ( const uint64_t patternlen, const PatternMatch::node thisnode, PatternMatch::memoize& keepcount, std::stack< PatternMatch::node >& nodes_to_visit ) {

	bool assign = true;
	uint64_t numpaths = 0;
	auto outedges = wallgraph[ thisnode.first ].outedges;
	PatternMatch::node new_node;

	for ( auto nextwall : outedges) {
		new_node = std::make_pair( nextwall, patternlen );
		// ( keepcount[ patternlen ].second ).push_back( 0 );
		if ( !keepcount.count( new_node ) ) {
			assign = false;
			nodes_to_visit.push( new_node );
		} else if ( assign ) {
			numpaths += keepcount[ new_node ];
		}
	}
	if ( assign ) {
		// if all children previously traversed, add together number of paths
		keepcount[ thisnode ] = numpaths;
	}
}

// void printMatch( std::list<uint64_t> match ) {
// 	for ( auto m : match ) {
// 		std::cout << m << " ";
// 	}
// 	std::cout << "\n";
// }

// std::list<uint64_t> match recursePattern_withmatch (uint64_t currentwallindex, patternvector pattern, const wallgraphvector& wallgraphptr, std::list<uint64_t> match) {

// 	if ( pattern.empty() ) {
// 		std::cout << "HAVE MATCH!!\n";
// 		printMatch( match );
// 		return true;
// 	} else {
// 		auto extremum = ( pattern.front() ).extremum;
// 		auto intermediate = ( pattern.front() ).intermediate;
// 		auto walllabels = wallgraphptr[ currentwallindex ].walllabels;

// 		bool extremum_in_labels = ( std::find(walllabels.begin(), walllabels.end(), extremum) != walllabels.end() );
// 		bool intermediate_in_labels = ( std::find(walllabels.begin(), walllabels.end(), intermediate) != walllabels.end() );

// 		auto outedges = wallgraphptr[ currentwallindex ].outedges;
// 		auto patterntail = pattern;
// 		patterntail.pop_front();

// 		match.push_back( currentwallindex );

// 		if ( extremum_in_labels ) {
// 			for ( auto nextwallindex : outedges) {
// 				if ( recursePattern_withmatch( nextwallindex, patterntail, wallgraphptr, match ) ) {
// 					return true;
// 				} // else, keep recursing
// 			}
// 		}
// 		if ( intermediate_in_labels ) {
// 			for ( auto nextwallindex : outedges) {
// 				if ( recursePattern_withmatch( nextwallindex, pattern, wallgraphptr, match ) ) {
// 					return true;
// 				} // else, keep recursing
// 			}
// 		}
// 	}

// 	// std::cout << "fall out\n";
// 	return false;

// }

<commit_msg>notes for what to do<commit_after>#include "PatternMatch.hpp"

PatternMatch::resultslist PatternMatch::patternMatch ( std::list<patternvector> allpatterns, const int findoption ) {

	/*
	patterns that are intended to be periodic may be overcounted, because we are not guaranteed to return
	to the same place in phase space
	*/

	// make sure findoption has allowable value
	const std::list<int> allowableoptions = {1,2,3};
	if ( std::find( allowableoptions.begin(), allowableoptions.end(), findoption ) == allowableoptions.end() ) {
		throw;
	}

	PatternMatch::resultslist results;
	patternvector oldpattern = allpatterns.front();
	PatternMatch::memoize keepcount ( oldpattern.size(), std::make_pair({},{}) ); // initializes vector of pairs of empty lists

	for ( auto pattern : allpatterns ) {
		// keep keys in keepcount that are going to be searched again
		_pruneRegister( pattern, oldpattern, keepcount );
		// perform the pattern match
		uint64_t nummatches = _patternMatch( pattern, findoption, keepcount );

		if ( nummatches > 0 ) {
			results.push_back( std::make_pair(pattern, nummatches) );
			if ( findoption == 1 ) {
				return results;
			}
		}
		oldpattern = pattern;
	}
	return results;
}

void PatternMatch::_pruneRegister( patternvector newpattern, patternvector oldpattern, PatternMatch::memoize& keepcount ) {
	std::reverse(newpattern.begin(),newpattern.end());
	std::reverse(oldpattern.begin(),oldpattern.end());
	uint64_t tailmatch = 0;

	for ( uint64_t i = 0; i < std::min(newpattern.size(),oldpattern.size()); ++i ) {
		if ( newpattern[ i ] == oldpattern[ i ] ) {
			tailmatch += 1;
		} else {
			break;
		}
	}

	if ( tailmatch == 0 ) {
		keepcount.assign ( newpattern.size(), std::make_pair({},{}) );
	} else {
		PatternMatch::memoize new_keepcount ( newpattern.size(), std::make_pair({},{}) );
		for ( int j = 0; j < tailmatch; ++j ) {
			new_keepcount[ j ] = keepcount[ j ];
		}
		keepcount = new_keepcount;
	}
}

uint64_t PatternMatch::_patternMatch ( const patternvector pattern, const int findoption, PatternMatch::memoize& keepcount ) {

	// require nonzero length pattern
	uint64_t N = pattern.size();
	if ( N < 1 ) {
		return 0;
	}

	// construct intermediate labels
	std::vector<std::string> temp = pattern;
	for ( auto& t : temp ) {
		std::replace(t.begin(),t.end(),'M','I');
		std::replace(t.begin(),t.end(),'m','D');
	}
	const std::vector<std::string> intermediates = temp;

	/* explicit initialize:
	 -- to return trivial results
	 -- to record top nodes for final counts
	 -- to avoid intermediate label on top nodes in while loop
	 **The initialization is recalculated in the while loop, unfortunately.
	*/
	std::stack< PatternMatch::node > nodes_to_visit = _initializeStack ( N, pattern.front() );
	// result for trivial pattern
	if ( N == 1 ) {
		return nodes_to_visit.size();
	}
	// record top nodes as list for later searching
	std::list<PatternMatch::node> top_nodes;
	auto tn = nodes_to_visit;
	// DEBUG
	std::cout << "\nTop nodes: ";
	// END DEBUG
	for ( int i = 0; i < tn.size(); ++i ) {
		// DEBUG
		std::cout << tn.top().first << " ";
		// END DEBUG
		top_nodes.push_back(tn.top());
		tn.pop();
	}
	// DEBUG
	std::cout << "\n";
	// END DEBUG

	// depth first search
	while ( !nodes_to_visit.empty() ) {

		// DEBUG
		std::cout << "\nNew loop: \n";
		for ( auto kvp : keepcount ) {
			std::cout << "wall " << ( kvp.first ).first << " has " << kvp.second << " matches.\n";
		}
		// END DEBUG

		auto thisnode = nodes_to_visit.top();
		nodes_to_visit.pop();

		auto wall = thisnode.first;
		auto patternlen = thisnode.second;
		auto walllabels = wallgraph[ wall ].labels;
		bool extremum_in_labels = _checkForWordInLabels( pattern[ N - patternlen ], walllabels );
		bool intermediate_in_labels = _checkForWordInLabels( intermediates[ N - patternlen ], walllabels );

		if ( !extremum_in_labels && !intermediate_in_labels ) {
			( keepcount[ patternlen ].first ).push_back( wall );
			( keepcount[ patternlen ].second ).push_back( 0 );
			continue;
		}

		bool in_top_nodes = _checkForNodeInTopNodes( thisnode, top_nodes );
		if ( intermediate_in_labels && !in_top_nodes ) {
			_addToStack( patternlen, thisnode, keepcount, nodes_to_visit );
		}

		if ( extremum_in_labels ) {
			if ( patternlen > 1 ) {
				_addToStack( patternlen-1, thisnode, keepcount, nodes_to_visit );
			// else if patternlen == 1 and extremum_in_labels, we have reached the final leaf in a path
			} else if ( findoption < 3 ) {
				return 1;
			} else {
				keepcount[ thisnode ] = 1;
			}
		}
	}

	// FIXME: add backfill

	if ( findoption < 3 ) {
		return 0;
	} else {
		uint64_t count = 0;
		for ( auto key : top_nodes ) {
			count += keepcount[ key ];
		}
		return count;
	}
}

std::stack<PatternMatch::node> PatternMatch::_initializeStack ( const uint64_t N, const std::string extremum ) {

	std::stack<PatternMatch::node> nodes_to_visit;

	for ( uint64_t i = 0; i < wallgraph.size(); ++i ) {
		if ( _checkForWordInLabels( extremum, wallgraph[ i ].labels ) ) {
			nodes_to_visit.push( std::make_pair( i, N ) );
		}
	}
	return nodes_to_visit;
}

bool PatternMatch::_checkForWordInLabels( const std::string word, const std::vector<std::set<char>> labels) {
	// match all
	for ( int i = 0; i < labels.size(); ++i ) {
		if ( labels[ i ].count( word[ i ] ) == 0 ) {
			return false;
		}
	}
	return true;
}

bool PatternMatch::_checkForNodeInTopNodes( const PatternMatch::node thisnode, const std::list<PatternMatch::node> top_nodes ) {
	// match any
	for ( auto topnode : top_nodes ) {
		if ( topnode == thisnode ) {
			return true;
		}
	}
	return false;
}

void PatternMatch::_addToStack ( const uint64_t patternlen, const PatternMatch::node thisnode, PatternMatch::memoize& keepcount, std::stack< PatternMatch::node >& nodes_to_visit ) {

	uint64_t numpaths = 0;
	auto outedges = wallgraph[ thisnode.first ].outedges;
	PatternMatch::node new_node;

	for ( auto nextwall : outedges) {
		auto walls = keepcount[ patternlen ].first;
		if ( std::find( walls.begin(), walls.end(), nextwall ) == walls.end() ) {
			nodes_to_visit.push( std::make_pair( nextwall, patternlen ) );
			( keepcount[ patternlen ].first ).push_back( nextwall );
			( keepcount[ patternlen ].second ).push_back( -1 );
		//FIXME with new memoization structure
		} else if ( assign ) {
			numpaths += keepcount[ new_node ];
		}
	}
	if ( assign ) {
		// if all children previously traversed, add together number of paths
		keepcount[ thisnode ] = numpaths;
	}
}

// void printMatch( std::list<uint64_t> match ) {
// 	for ( auto m : match ) {
// 		std::cout << m << " ";
// 	}
// 	std::cout << "\n";
// }

// std::list<uint64_t> match recursePattern_withmatch (uint64_t currentwallindex, patternvector pattern, const wallgraphvector& wallgraphptr, std::list<uint64_t> match) {

// 	if ( pattern.empty() ) {
// 		std::cout << "HAVE MATCH!!\n";
// 		printMatch( match );
// 		return true;
// 	} else {
// 		auto extremum = ( pattern.front() ).extremum;
// 		auto intermediate = ( pattern.front() ).intermediate;
// 		auto walllabels = wallgraphptr[ currentwallindex ].walllabels;

// 		bool extremum_in_labels = ( std::find(walllabels.begin(), walllabels.end(), extremum) != walllabels.end() );
// 		bool intermediate_in_labels = ( std::find(walllabels.begin(), walllabels.end(), intermediate) != walllabels.end() );

// 		auto outedges = wallgraphptr[ currentwallindex ].outedges;
// 		auto patterntail = pattern;
// 		patterntail.pop_front();

// 		match.push_back( currentwallindex );

// 		if ( extremum_in_labels ) {
// 			for ( auto nextwallindex : outedges) {
// 				if ( recursePattern_withmatch( nextwallindex, patterntail, wallgraphptr, match ) ) {
// 					return true;
// 				} // else, keep recursing
// 			}
// 		}
// 		if ( intermediate_in_labels ) {
// 			for ( auto nextwallindex : outedges) {
// 				if ( recursePattern_withmatch( nextwallindex, pattern, wallgraphptr, match ) ) {
// 					return true;
// 				} // else, keep recursing
// 			}
// 		}
// 	}

// 	// std::cout << "fall out\n";
// 	return false;

// }

<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCDataNoSqlModule.h
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCDataNoSqlModule
//    Row,Col; ; ; ; ; ; ;
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include <algorithm>
#include "NFCNoSqlModule.h"

NFCNoSqlModule::NFCNoSqlModule(NFIPluginManager* p)
{
    pPluginManager = p;
	m_pNoSqlDriver = NULL;
}

NFCNoSqlModule::~NFCNoSqlModule()
{

}

bool NFCNoSqlModule::Init()
{
    return true;
}

bool NFCNoSqlModule::Shut()
{
    delete m_pNoSqlDriver;
	m_pNoSqlDriver = NULL;

    return true;
}

bool NFCNoSqlModule::AfterInit()
{
    return true;
}

bool NFCNoSqlModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;
}

bool NFCNoSqlModule::ConnectSql(const std::string& strIP)
{
	if (!m_pNoSqlDriver)
	{
		m_pNoSqlDriver = new NFCNoSqlDriver();
		return m_pNoSqlDriver->Connect(strIP, 6379);
	}
	return false;
}

bool NFCNoSqlModule::ConnectSql(const std::string & strIP, const int nPort)
{
	if (!m_pNoSqlDriver)
	{
		m_pNoSqlDriver = new NFCNoSqlDriver();
		return m_pNoSqlDriver->Connect(strIP, nPort, "");
	}
	return false;
}

bool NFCNoSqlModule::ConnectSql(const std::string & strIP, const int nPort, const std::string & strPass)
{
	if (!m_pNoSqlDriver)
	{
		m_pNoSqlDriver = new NFCNoSqlDriver();
		return m_pNoSqlDriver->Connect(strIP, nPort, strPass);
	}
	return false;
}

NFINoSqlDriver * NFCNoSqlModule::GetDriver()
{
	return m_pNoSqlDriver;
}
NFINoSqlDriver* NFCNoSqlModule::GetDriverBySuit(const std::string& strHash)
{
	return nullptr;
}

NFINoSqlDriver* NFCNoSqlModule::GetDriverBySuit(const int strHash)
{
	return nullptr;
}

bool NFCNoSqlModule::AddConnectSql(const std::string& strID, const std::string& strIP)
{
	return false;
}

bool NFCNoSqlModule::AddConnectSql(const std::string& strID, const std::string& strIP, const int nPort)
{
	return false;
}

bool NFCNoSqlModule::AddConnectSql(const std::string& strID, const std::string& strIP, const int nPort, const std::string& strPass)
{
	return false;
}

NFINoSqlDriver* NFCNoSqlModule::GetDriver(const std::string& strID)
{
	return nullptr;
}

bool NFCNoSqlModule::RemoveConnectSql(const std::string& strID)
{
	return false;
}<commit_msg>used new consistent hash map class to implement distribution nosql database<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCDataNoSqlModule.h
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCDataNoSqlModule
//    Row,Col; ; ; ; ; ; ;
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include <algorithm>
#include "NFCNoSqlModule.h"

NFCNoSqlModule::NFCNoSqlModule(NFIPluginManager* p)
{
    pPluginManager = p;
	m_pNoSqlDriver = NULL;
}

NFCNoSqlModule::~NFCNoSqlModule()
{

}

bool NFCNoSqlModule::Init()
{
    return true;
}

bool NFCNoSqlModule::Shut()
{
    delete m_pNoSqlDriver;
	m_pNoSqlDriver = NULL;

    return true;
}

bool NFCNoSqlModule::AfterInit()
{
    return true;
}

bool NFCNoSqlModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;
}

bool NFCNoSqlModule::ConnectSql(const std::string& strIP)
{
	if (!m_pNoSqlDriver)
	{
		m_pNoSqlDriver = new NFCNoSqlDriver();
		return m_pNoSqlDriver->Connect(strIP, 6379);
	}
	return false;
}

bool NFCNoSqlModule::ConnectSql(const std::string & strIP, const int nPort)
{
	if (!m_pNoSqlDriver)
	{
		m_pNoSqlDriver = new NFCNoSqlDriver();
		return m_pNoSqlDriver->Connect(strIP, nPort, "");
	}
	return false;
}

bool NFCNoSqlModule::ConnectSql(const std::string & strIP, const int nPort, const std::string & strPass)
{
	if (!m_pNoSqlDriver)
	{
		m_pNoSqlDriver = new NFCNoSqlDriver();
		return m_pNoSqlDriver->Connect(strIP, nPort, strPass);
	}
	return false;
}

NFINoSqlDriver * NFCNoSqlModule::GetDriver()
{
	return m_pNoSqlDriver;
}
NFINoSqlDriver* NFCNoSqlModule::GetDriverBySuit(const std::string& strHash)
{
	return nullptr;
}

NFINoSqlDriver* NFCNoSqlModule::GetDriverBySuit(const int strHash)
{
	return nullptr;
}

bool NFCNoSqlModule::AddConnectSql(const std::string& strID, const std::string& strIP)
{
	if (!mxNoSqlDriver.ExistElement(strID))
	{
		NF_SHARE_PTR<NFINoSqlDriver> pNoSqlDriver(new NFCNoSqlDriver());
		pNoSqlDriver->Connect(strIP, 6379, "");
		return mxNoSqlDriver.AddElement(strID, pNoSqlDriver);
	}

	return false;
}

bool NFCNoSqlModule::AddConnectSql(const std::string& strID, const std::string& strIP, const int nPort)
{
	if (!mxNoSqlDriver.ExistElement(strID))
	{
		NF_SHARE_PTR<NFINoSqlDriver> pNoSqlDriver(new NFCNoSqlDriver());
		pNoSqlDriver->Connect(strIP, nPort, "");
		return mxNoSqlDriver.AddElement(strID, pNoSqlDriver);
	}

	return false;
}

bool NFCNoSqlModule::AddConnectSql(const std::string& strID, const std::string& strIP, const int nPort, const std::string& strPass)
{
	if (!mxNoSqlDriver.ExistElement(strID))
	{
		NF_SHARE_PTR<NFINoSqlDriver> pNoSqlDriver(new NFCNoSqlDriver());
		pNoSqlDriver->Connect(strIP, nPort, strPass);
		return mxNoSqlDriver.AddElement(strID, pNoSqlDriver);
	}

	return false;
}

NFINoSqlDriver* NFCNoSqlModule::GetDriver(const std::string& strID)
{
	return nullptr;
}

bool NFCNoSqlModule::RemoveConnectSql(const std::string& strID)
{
	return mxNoSqlDriver.RemoveElement(strID);
}<|endoftext|>


<commit_before>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-3-25 21:07:52
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int A, B;
bool ans[100][100];

void flush()
{
  cout << 100 << " " << 100 << endl;
  for (auto i = 0; i < 100; i++)
  {
    for (auto j = 0; j < 100; j++)
    {
      cout << (ans[i][j] ? '#' : '.');
    }
    cout << endl;
  }
}

int main()
{
  cin >> A >> B;
  for (auto i = 0; i < 50; i++)
  {
    for (auto j = 0; j < 100; j++)
    {
      ans[i][j] = true;
    }
  }
  for (auto i = 50; i < 100; i++)
  {
    for (auto j = 0; j < 100; j++)
    {
      ans[i][j] = false;
    }
  }
  int nowa = 1;
  while (nowa < A)
  {
    for (auto i = 1; i < 100; i += 2)
    {
      for (auto j = 1; j < 100; j += 2)
      {
        ans[i][j] = false;
        nowa++;
        break;
      }
      break;
    }
  }
  int nowb = 1;
  while (nowb < B)
  {
    for (auto i = 51; i < 100; i += 2)
    {
      for (auto j = 1; j < 100; j += 2)
      {
        ans[i][j] = true;
        nowb++;
        break;
      }
      break;
    }
  }
  flush();
}<commit_msg>tried D.cpp to 'D'<commit_after>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-3-25 21:07:52
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int A, B;
bool ans[100][100];

void flush()
{
  cout << 100 << " " << 100 << endl;
  for (auto i = 0; i < 100; i++)
  {
    for (auto j = 0; j < 100; j++)
    {
      cout << (ans[i][j] ? '#' : '.');
    }
    cout << endl;
  }
}

int main()
{
  cin >> A >> B;
  for (auto i = 0; i < 50; i++)
  {
    for (auto j = 0; j < 100; j++)
    {
      ans[i][j] = true;
    }
  }
  for (auto i = 50; i < 100; i++)
  {
    for (auto j = 0; j < 100; j++)
    {
      ans[i][j] = false;
    }
  }
  int nowa = 1;
  while (nowa < A)
  {
    for (auto i = 1; i < 100; i += 2)
    {
      for (auto j = 1; j < 100; j += 2)
      {
        ans[i][j] = false;
        nowa++;
        if (nowa >= A)
        {
          break;
        }
      }
      if (nowa >= A)
      {
        break;
      }
    }
  }
  int nowb = 1;
  while (nowb < B)
  {
    for (auto i = 51; i < 100; i += 2)
    {
      for (auto j = 1; j < 100; j += 2)
      {
        ans[i][j] = true;
        nowb++;
        if (nowb >= B)
        {
          break;
        }
      }
      if (nowb >= B)
      {
        break;
      }
    }
  }
  flush();
}<|endoftext|>