text:
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// Portions Copyright EBSNet , 2007
// See LICENSE file in the project root for full license information.
//

//
// enc28j60.C - device driver interface
//

#include <nanohal.h>

#include "enc28j60_lwip.h"

#include "lwip\netif.h"
#include "lwip\pbuf.h"
#include "lwip\mem.h"

extern void lwip_interrupt_continuation(void);

// FIXME
#define hal_printf(x)

/* ********************************************************************
   GLOBAL DATA
   ******************************************************************** */

extern HAL_TARGET_CONFIGURATION g_TargetConfiguration;

extern ENC28J60_LWIP_DEVICE_CONFIG g_ENC28J60_LWIP_Config;

/* Function Prototypes */

void enc28j60_lwip_soft_reset(uint32_t spiHandle);

void enc28j60_lwip_write_spi(
    uint32_t spiHandle,
    uint8_t opcode,
    uint8_t address,
    uint8_t perPacketCtrlByte,
    uint8_t *byteData,
    uint32_t numBytes);

void enc28j60_lwip_write_spi(uint32_t spiHandle, uint8_t opcode, uint8_t address, uint8_t byteData);

void enc28j60_lwip_read_spi(
    uint32_t spiHandle,
    uint8_t opcode,
    uint8_t address,
    uint8_t *byteData,
    uint32_t numBytes,
    uint8_t offset);

void enc28j60_lwip_select_bank(uint32_t spiHandle, uint8_t bankNumber);

void enc28j60_lwip_write_phy_register(uint32_t spiHandle, uint8_t registerAddress, unsigned short data);

bool enc28j60_lwip_setup_device(struct netif *pNetIF);

void enc28j60_lwip_destroy_device();

unsigned short enc28j60_lwip_read_phy_register(uint32_t spiHandle, uint8_t registerAddress);

/* keep track of the receive pointer */
static unsigned short s_ENC28J60_TRANSMIT_BUFFER_START = ENC28J60_TRANSMIT_BUFFER_START;
static unsigned short s_ENC28J60_RECEIVE_BUFFER_START = ENC28J60_RECEIVE_BUFFER_START;

/* ********************************************************************
   open the ENC28J60 driver interface.

   This routine opens a ENC28J60 device driver

   The address of this function must be placed into the "devices" table in
   iface.c either at compile time or before a device open is called.

  ******************************************************************** */
bool enc28j60_lwip_open(struct netif *pNetIF)

{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();

    return enc28j60_lwip_setup_device(pNetIF);
}

/* ********************************************************************
   close the packet driver interface.

   This routine is called when the device interface is no longer needed
   it should stop the driver from delivering packets to the upper levels
   and shut off packet delivery to the network.

   The address of this function must be placed into the "devices" table in
   iface.c either at compile time or before a device open is called.

 */
void enc28j60_lwip_close(struct netif *pNetIF)
{
    (void)pNetIF;

    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();

    enc28j60_lwip_destroy_device();
}

/* ********************************************************************
   Interrupt handling routine at the task level

   ******************************************************************** */
#define TRANSMIT_RETRIES 5
static uint8_t s_retriesTransmit = TRANSMIT_RETRIES;
#define RECEIVE_RETRIES 5
static uint8_t s_receiveRetries = 10;

void enc28j60_handle_recv_error(struct netif *pNetIF, uint32_t spiHandle)
{
    (void)pNetIF;

    uint8_t byteData;

    if (--s_receiveRetries <= 0)
    {
        s_receiveRetries = RECEIVE_RETRIES;
        enc28j60_lwip_setup_device(pNetIF);
        return;
    }

    /* Reset the receiver logic */
    byteData = (1 << ENC28J60_ECON1_RXRST_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_ECON1, byteData);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_ECON1, byteData);

    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ESTAT, &byteData, 1, 0);

    /* buffer is corrupted flush it */
    if (byteData & (1 << ENC28J60_ESTAT_BUFER))
    {
        enc28j60_lwip_setup_recv_buffer(pNetIF, spiHandle);
    }

    byteData = (1 << ENC28J60_EIR_RXERIF_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_EIR, byteData);

    byteData = ((1 << ENC28J60_EIE_RXERIE_BIT) | (1 << ENC28J60_EIE_INTIE_BIT));
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_EIE, byteData);

    byteData = (1 << ENC28J60_ECON1_RXEN_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_ECON1, byteData);

    /* Is there an interrupt pending */
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ESTAT, &byteData, 1, 0);

    s_ENC28J60_RECEIVE_BUFFER_START = ENC28J60_RECEIVE_BUFFER_START;
}

void enc28j60_handle_xmit_error(struct netif *pNetIF, uint32_t spiHandle)
{
    (void)pNetIF;

    uint8_t byteData;

    byteData = (1 << ENC28J60_ECON1_TXRST_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_ECON1, byteData);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_ECON1, byteData);

    byteData = (1 << ENC28J60_EIR_TXERIF_BIT) | (1 << ENC28J60_EIR_TXIF_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_EIR, byteData);

    byteData = ((1 << ENC28J60_EIE_TXERIE_BIT) | (1 << ENC28J60_EIE_INTIE_BIT));
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_EIE, byteData);

    byteData = (1 << ENC28J60_ECON1_TXRTS_BIT);

    /* CLEAR the TXRTS bit to cancel the last transmission */
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_ECON1, byteData);

    if (s_retriesTransmit--)
    {
        /* SET the TXRTS bit to retry the last transmission */
        enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_ECON1, byteData);
    }
    else
    {
        s_retriesTransmit = TRANSMIT_RETRIES;
    }
}

void enc28j60_lwip_pre_interrupt(GPIO_PIN Pin, bool PinState, void *pArg)
{
    (void)Pin;
    (void)PinState;

    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();

    struct netif *pNetIF = (struct netif *)pArg;
    uint8_t byteData;
    uint8_t eirData;

    uint32_t spiHandle = g_ENC28J60_LWIP_Config.DeviceConfigs[0].spiHandle;

    GLOBAL_LOCK();

    /* After an interrupt occurs, the host controller should
        clear the global enable bit for the interrupt pin before
        servicing the interrupt. Clearing the enable bit will
        cause the interrupt pin to return to the non-asserted
        state (high). Doing so will prevent the host controller
        from missing a falling edge should another interrupt
        occur while the immediate interrupt is being serviced.
     */

    byteData = (1 << ENC28J60_EIE_INTIE_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_EIE, byteData);

    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_EIR, &eirData, 1, 0);

    /* recover from tx error */
    if (eirData & (1 << ENC28J60_EIR_TXERIF_BIT))
    {
        enc28j60_handle_xmit_error(pNetIF, spiHandle);
    }

    lwip_interrupt_continuation();

    GLOBAL_UNLOCK();
}

/* ********************************************************************
   Interrupt handling routine at the task level

   ******************************************************************** */
void enc28j60_lwip_interrupt(struct netif *pNetIF)

{
    uint8_t byteData;
    uint8_t cntPkts;
    uint8_t eirData;
    uint8_t status;
    int packetsLeft = 0;

    GLOBAL_LOCK();

    if (!pNetIF)
    {
        return;
    }

    uint32_t spiHandle = g_ENC28J60_LWIP_Config.DeviceConfigs[0].spiHandle;

    /* Is there an interrupt pending */
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ESTAT, &status, 1, 0);

    /*  FROM ERRATA
        Module: Interrupts The Receive Packet Pending Interrupt Flag (EIR.PKTIF) does not reliably/accurately report
        the status of pending packets. Work around In the Interrupt Service Routine, if it is unknown if
        a packet is pending and the source of the interrupt is unknown, switch to Bank 1 and check the value
        in EPKTCNT. If polling to see if a packet is pending, check the value in EPKTCNT.

        //enc28j60_lwip_read_spi(spiHandle,  ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_EIR, &byteData, 1, 0);
        //if (byteData & (1 << ENC28J60_EIR_PKTIF_BIT))
    */

    /* Read the number of packets remaining */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK1);
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_BUFFER_MEMORY_OPCODE, ENC28J60_EPKTCNT, &cntPkts, 1, 0);

    if ((status & (1 << ENC28J60_ESTAT_INT)) || cntPkts)
    {
        enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_EIR, &eirData, 1, 0);

        if (eirData & (1 << ENC28J60_EIR_TXERIF_BIT))
        {
            enc28j60_handle_xmit_error(pNetIF, spiHandle);
        }
        else if (eirData & (1 << ENC28J60_EIR_TXIF_BIT)) /* A packet is xmited */
        {
            s_retriesTransmit = TRANSMIT_RETRIES;

            /* signal IP task that xmit has completed */
            /* JJM Eventually this should invoke enc28j60_lwip_xmit_done(); */
        }

        /* recover from rx error */
        if (eirData & (1 << ENC28J60_EIR_RXERIF_BIT))
        {
            enc28j60_handle_recv_error(pNetIF, spiHandle);
        }
        else
        {
            s_receiveRetries = RECEIVE_RETRIES;
        }

        if (cntPkts)
        {
            // FIXME - Restores an interrupt to its previous state, as stored by the SmartPtr_IRQ.Acquire method.
            //			irq.Release();
            packetsLeft = enc28j60_lwip_recv(pNetIF);
            // FIXME  - Disables interrupts if they are currently enabled, storing the previous interrupt state.
            //			irq.Acquire();
        }
    }

    /* enable packet reception */
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ECON1, &byteData, 1, 0);

    /* Is the receiver or transmitter in reset state */
    if ((byteData & (1 << ENC28J60_ECON1_TXRST_BIT)) || (byteData & (1 << ENC28J60_ECON1_RXRST_BIT)))
    {
        /* If so, take it out of reset */
        byteData &= ~((1 << ENC28J60_ECON1_TXRST_BIT) | (1 << ENC28J60_ECON1_RXRST_BIT));
    }

    byteData |= (1 << ENC28J60_ECON1_RXEN_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ECON1, byteData);

    /* clear errors if there are any */
    byteData = 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_ESTAT, byteData);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_EIR, byteData);

    /* re-enable interrupts when a packet is received and when transmit is done  */
    byteData = (1 << ENC28J60_EIE_INTIE_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_EIE, byteData);

    if (packetsLeft)
    {
        /* If there are more packets left re-queue the continuation */

        lwip_interrupt_continuation();
    }

    GLOBAL_UNLOCK();
}

/* ********************************************************************
   Receive. a packet over the packet driver interface.  This is called
   from the ISR or task ISR.

   This routine is called when a packet is received.

   Upon successful reading of received packet, the IP is
   signalled to process the packet.

   Returns the number of packets that remain to be processed

  ******************************************************************** */
int enc28j60_lwip_recv(struct netif *pNetIF)
{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();

    struct pbuf *pPBuf;
    uint8_t *dataRX;
    uint8_t nextPktAndRecvStatusVector[6];
    uint16_t length;
    uint8_t byteData;
    uint8_t packetsLeft;
    uint16_t lastReceiveBuffer;
    uint32_t spiHandle;

    int numPacketsProcessed = 0;

    if (!pNetIF)
    {
        return 1;
    }

    spiHandle = g_ENC28J60_LWIP_Config.DeviceConfigs[0].spiHandle;

    do
    {
        /* Disable interrupt for each loop and only each loop */
        GLOBAL_LOCK();

        /* Set the read buffer pointer to the beginning of the packet */
        enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK0);

        byteData = s_ENC28J60_RECEIVE_BUFFER_START & 0xFF;

        enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERDPTL, byteData);

        byteData = (s_ENC28J60_RECEIVE_BUFFER_START >> 8) & 0xFF;

        enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERDPTH, byteData);

        /* Get the next packet pointer */
        enc28j60_lwip_read_spi(
            spiHandle,
            ENC28J60_SPI_READ_BUFFER_MEMORY_OPCODE,
            ENC28J60_SPI_READ_BUFFER_MEMORY_ARGUMENT,
            nextPktAndRecvStatusVector,
            6,
            0);

        lastReceiveBuffer = (nextPktAndRecvStatusVector[1] << 8) | nextPktAndRecvStatusVector[0];
        length = (nextPktAndRecvStatusVector[3] << 8) | nextPktAndRecvStatusVector[2];

        /* corrupted */
        if (lastReceiveBuffer > ENC28J60_RECEIVE_BUFFER_END)
        {
            enc28j60_handle_recv_error(pNetIF, spiHandle);
            packetsLeft = 0;
            break;
        }
        else
        {
            s_ENC28J60_RECEIVE_BUFFER_START = lastReceiveBuffer;
        }

        if (length != 0)
        {
            // FIXME
            //				irq.Release();
            pPBuf = pbuf_alloc(PBUF_RAW, length, PBUF_RAM);
            // FIXME
            //				irq.Acquire();

            if (pPBuf)
            {
                dataRX = (uint8_t *)pPBuf->payload;

                // remove the checksum trailing bytes
                if (length > 63)
                {
                    length -= 4;
                }

                /* Get the packet */
                enc28j60_lwip_read_spi(
                    spiHandle,
                    ENC28J60_SPI_READ_BUFFER_MEMORY_OPCODE,
                    ENC28J60_SPI_READ_BUFFER_MEMORY_ARGUMENT,
                    dataRX,
                    length,
                    0);

                /* invoke stack ip input - the stack should free the buffer when it is done,
                                    so DON'T call pbuf_free on pPBuf!!!!!*/
                // FIXME
                //					irq.Release();
                pNetIF->input(pPBuf, pNetIF);
                // FIXME
                //					irq.Acquire();
            }
            else
            {
                hal_printf("enc28j60_lwip_recv: input alloc packet failed \r\n");
            }
        }
        else // no packets left - should we break??
        {
        }

        if (0 == (s_ENC28J60_RECEIVE_BUFFER_START % 2))
        {
            /* from errata rev.b5 - circular buffer doesn't handle even numbers well -> nextPkt is guarranteed to be
             * even */
            if (((s_ENC28J60_RECEIVE_BUFFER_START - 1) < ENC28J60_RECEIVE_BUFFER_START) ||
                ((s_ENC28J60_RECEIVE_BUFFER_START - 1) > ENC28J60_RECEIVE_BUFFER_END))
            {
                lastReceiveBuffer = ENC28J60_RECEIVE_BUFFER_END;
            }
            else
            {
                lastReceiveBuffer = s_ENC28J60_RECEIVE_BUFFER_START - 1;
            }
        }
        else
        {

            lastReceiveBuffer = s_ENC28J60_RECEIVE_BUFFER_START;
        }

        /* Free the packet from the ethernet */
        byteData = lastReceiveBuffer & 0xFF;
        enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXRDPTL, byteData);

        byteData = lastReceiveBuffer >> 8;
        enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXRDPTH, byteData);

        /* the host controller must write a 1 to the ECON2.PKTDEC bit.
                        Doing so will cause the EPKTCNT register to decrement by 1 */
        byteData = (1 << ENC28J60_ECON2_PKTDEC_BIT);
        enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_ECON2, byteData);

        /* Read the number of packets remaining*/
        enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK1);
        enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_BUFFER_MEMORY_OPCODE, ENC28J60_EPKTCNT, &packetsLeft, 1, 0);

        if ((++numPacketsProcessed > CFG_MAX_PACKETS_PROCESSED) && packetsLeft)
        {
            break;
        }

        GLOBAL_UNLOCK();
    } while (packetsLeft);

    return packetsLeft;
}

/* ********************************************************************
   Transmit. a packet over the packet driver interface.

   This routine is called when a packet needs sending. The packet contains a
   full ethernet frame to be transmitted. The length of the packet is
   provided.

   Returns 0 if successful or errno if unsuccessful

 */

err_t enc28j60_lwip_xmit(struct netif *pNetIF, struct pbuf *pPBuf)
{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();
    uint16_t length = 0;
    uint8_t perPacketControlByte;
    uint8_t dataByte;
    uint32_t spiHandle;
    struct pbuf *pTmp;
    uint8_t *pTx;
    int idx;
    int retries = 100;

    GLOBAL_LOCK();

    if (!pNetIF)
    {
        return ERR_ARG;
    }

    spiHandle = g_ENC28J60_LWIP_Config.DeviceConfigs[0].spiHandle;

    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ECON1, &dataByte, 1, 0);

    length = pPBuf->tot_len;

    if (length > ETHERSIZE) // (ETHERSIZE+4))
    {
        debug_printf("xmit - length is too large, truncated \r\n");
        ASSERT(FALSE);
        length = ETHERSIZE; // ETHERSIZE+4;         /* what a terriable hack! */
    }

    /* First see if there is enough space in the remainder of the transmit buffer */
    /* 7 for the status bytes and 1 for the control byte */
    if ((length + 7 + 1 + (uint16_t)s_ENC28J60_TRANSMIT_BUFFER_START) > ENC28J60_TRANSMIT_BUFFER_END)
    {
        s_ENC28J60_TRANSMIT_BUFFER_START = ENC28J60_TRANSMIT_BUFFER_START;
    }

    do
    {
        enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ECON1, &dataByte, 1, 0);
    } while (0 != (dataByte & (1 << ENC28J60_ECON1_TXRTS_BIT)) && retries-- > 0);

    /*  1. Appropriately program the ETXST pointer to
            point to an unused location in memory. It will
            point to the per packet control byte.
        2. Use the WBM SPI command to write the per
            packet control byte, the destination address, the
            source MAC address, the type/length and the
            data payload.
        3. Appropriately program the ETXND pointer. It
            should point to the last byte in the data payload.
        4. Clear EIR.TXIF, set EIE.TXIE and set EIE.INTIE
            to enable an interrupt when done (if desired).
        5. Start the transmission process by setting
            ECON1.TXRTS.
    */

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK0);

    /* setup the EWRPTL AND EWRPTH to the beginning of the transmit buffer */
    dataByte = s_ENC28J60_TRANSMIT_BUFFER_START & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_EWRPTL, dataByte);
    dataByte = (s_ENC28J60_TRANSMIT_BUFFER_START >> 8) & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_EWRPTH, dataByte);

    /* 1. */
    dataByte = s_ENC28J60_TRANSMIT_BUFFER_START & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ETXSTL, dataByte);
    dataByte = (s_ENC28J60_TRANSMIT_BUFFER_START >> 8) & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ETXSTH, dataByte);

    /* 2. */
    /* Write per byte control byte and the first byte of data */
    perPacketControlByte = (1 << ENC28J60_XMIT_CONTROL_PPADEN_BIT) | (1 << ENC28J60_XMIT_CONTROL_PCRCEN_BIT);

    // FIXME
    // irq.Release();
    pTmp = pbuf_alloc(PBUF_RAW, length + 2, PBUF_RAM);
    // FIXME
    // irq.Acquire();

    if (!pTmp)
        return ERR_MEM;

    pTx = (uint8_t *)pTmp->payload;

    pTx[0] = ENC28J60_SPI_OPCODE_ARGUMENT(
        ENC28J60_SPI_WRITE_BUFFER_MEMORY_OPCODE,
        ENC28J60_SPI_WRITE_BUFFER_MEMORY_ARGUMENT);
    pTx[1] = perPacketControlByte;

    idx = 2;

    while (pPBuf)
    {
        memcpy(&pTx[idx], pPBuf->payload, pPBuf->len);

        idx += pPBuf->len;

        pPBuf = pPBuf->next;
    }

    // CPU_SPI_nWrite8_nRead8(spiHandle, false, pTx, length+2, 0, 0, 0 );
    SPI_WRITE_READ_SETTINGS wrc{false, 0, false, 0};
    nanoSPI_Write_Read(spiHandle, wrc, pTx, length + 2, 0, 0);

    // FIXME
    // irq.Release();
    pbuf_free(pTmp);
    // FIXME
    // irq.Acquire();

    s_ENC28J60_TRANSMIT_BUFFER_START += length;

    /* 3. */
    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK0);
    dataByte = s_ENC28J60_TRANSMIT_BUFFER_START & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ETXNDL, dataByte);
    dataByte = (s_ENC28J60_TRANSMIT_BUFFER_START >> 8) & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ETXNDH, dataByte);

    /* TAKE CARE OF WRAP HERE */
    /* Leave 7 bytes for the status Vector + 1 for control byte */
    s_ENC28J60_TRANSMIT_BUFFER_START += 8;

    /* Make sure that it is on an even address */
    if ((s_ENC28J60_TRANSMIT_BUFFER_START % 2) != 0)
        s_ENC28J60_TRANSMIT_BUFFER_START++;

    /* 4. */
    dataByte = 1 << ENC28J60_EIR_TXIF_BIT;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE, ENC28J60_EIR, dataByte);

    dataByte = ((1 << ENC28J60_EIE_INTIE_BIT) | (1 << ENC28J60_EIE_TXERIE_BIT));
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_EIE, dataByte);

    /* 5. */
    dataByte = (1 << ENC28J60_ECON1_TXRTS_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_BIT_FIELD_SET_OPCODE, ENC28J60_ECON1, dataByte);

    GLOBAL_UNLOCK();

    return ERR_OK;
}

void enc28j60_lwip_setup_recv_buffer(struct netif *pNetIF, uint32_t spiHandle)
{
    (void)pNetIF;

    uint8_t byteData;

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK0);

    /* keep track of the receive pointer */
    s_ENC28J60_RECEIVE_BUFFER_START = ENC28J60_RECEIVE_BUFFER_START;

    /* Specifying the receive buffer size */
    /* First, write the low byte of the starting address*/
    byteData = ENC28J60_RECEIVE_BUFFER_START & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXSTL, byteData);

    /* Then, write the upper byte of the starting address*/
    byteData = (ENC28J60_RECEIVE_BUFFER_START >> 8) & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXSTH, byteData);

    /* First, write the low byte of the ending address*/
    byteData = ENC28J60_RECEIVE_BUFFER_END & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXNDL, byteData);
    /* Then, write the upper byte of the starting address*/
    byteData = ((ENC28J60_RECEIVE_BUFFER_END >> 8) & 0xFF);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXNDH, byteData);

    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ERXWRPTL, &byteData, 1, 0);
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ERXWRPTH, &byteData, 1, 0);

    /* The ERXRDPT register should be program with the same value
        as ERXST in the beginning */
    /* LOOK AT ERRATA */
    // byteData = (ENC28J60_RECEIVE_BUFFER_START-1) & 0xFF;
    byteData = ENC28J60_RECEIVE_BUFFER_END & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXRDPTL, byteData);

    // byteData = (((ENC28J60_RECEIVE_BUFFER_START-1)>> 8) & 0xFF);
    byteData = ((ENC28J60_RECEIVE_BUFFER_END) >> 8) & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXRDPTH, byteData);
}

bool enc28j60_lwip_setup_device(struct netif *pNetIF)
{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();
    uint8_t byteData;
    uint16_t duplex;
    uint16_t phyID1;
    uint16_t phyID2;
    uint16_t shortData;
    int16_t nLoopCnt = 0;
    uint32_t spiHandle;

    spiHandle = g_ENC28J60_LWIP_Config.DeviceConfigs[0].spiHandle;

    // Save handle
    g_ENC28J60_LWIP_Config.DeviceConfigs[0].spiHandle = spiHandle;

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                          CHECK IF THE PHY IS READY                                   */

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK0);
    do
    {
        enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ESTAT, &byteData, 1, 0);

        // either the chip doesn't return a valid status bit or the chip is not connected
        if (50 < nLoopCnt++)
        {
            debug_printf("Ethernet PHY NOT IN READY STATE\n");
            break; // try any way
        }

        OS_DELAY(1);

    } while ((0x1 != (byteData & 0x1)) || (0xFF == byteData));

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK3);
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_EREVID, &byteData, 1, 0);

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                                  SOFT RESET                                          */

    enc28j60_lwip_soft_reset(spiHandle);

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                              VERIFY THE DEVICE ID                                    */

    phyID1 = enc28j60_lwip_read_phy_register(spiHandle, ENC28J60_PHID1);
    phyID2 = enc28j60_lwip_read_phy_register(spiHandle, ENC28J60_PHID2);

    if ((phyID1 != ENC28J60_PHYID1) || (phyID2 != ENC28J60_PHYID2))
    {
        hal_printf("enc28j60_lwip_open: Wrong Device");
    }

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                          SETUP RECEIVE  BUFFER                                       */

    enc28j60_lwip_setup_recv_buffer(pNetIF, spiHandle);

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                          SETUP RECEIVE FILTER                                       */

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK1);
    /* Disable packet filtering (Promiscuous mode) */
    byteData = 0;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERXFCON, byteData);

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                          MAC INITIALIZATION SETTINGS                                 */

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK2);

    /* Clear the MARST bit in MACON2 */
    // NEW MANUAL DOESN'T DO THIS
    // enc28j60_lwip_read_spi(SpiConf, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_MACON2, &byteData, 1, 1);
    // byteData &= ~(1 << ENC28J60_MACON2_MARST_BIT);
    // enc28j60_lwip_write_spi(SpiConf,  ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE,ENC28J60_MACON2, byteData);

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK2);

    /* Set the MARXEN bit in MACON1 */
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_MACON1, &byteData, 1, 1);
    byteData = (1 << ENC28J60_MACON1_MARXEN_BIT);
#if (ENC28J60_FULL_DUPLEX)
    byteData |= (1 << ENC28J60_MACON1_TXPAUS_BIT);
    byteData |= (1 << ENC28J60_MACON1_RXPAUS_BIT);
#endif

    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MACON1, byteData);

    /* Configure the PADCFT, TXCRECEN, AND FULLDPS bits
        of MACON3 */

    byteData = (5 << ENC28J60_MACON3_PADCFG0_BIT) | ENC28J60_MACON3_TXCRCEN_BIT;
    //(1 << ENC28J60_MACON3_TXCRCEN_BIT);
#if (ENC28J60_FULL_DUPLEX)
    byteData |= (1 << ENC28J60_MACON3_FULDPX_BIT);
#endif
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MACON3, byteData);

    byteData = 0;
    /* Configure the bits in MACON4     */
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MACON4, byteData);

    /* Configure the MAMXFL registers */
    byteData = ENC28J60_MAXIMUM_FRAME_SIZE & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAMXFLL, byteData);
    byteData = (ENC28J60_MAXIMUM_FRAME_SIZE >> 8) & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAMXFLH, byteData);

    /* Configure the Back-to-back inter-packet gap */
#if (ENC28J60_FULL_DUPLEX)
    byteData = 0x15;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MABBIPG, byteData);
#else
    byteData = 0x12;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MABBIPG, byteData);
#endif

    /* Configure the non-back-to-back inter-packet gap */
    byteData = 0x12;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAIPGL, byteData);

#if (!ENC28J60_FULL_DUPLEX)
    byteData = 0xC;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAIPGH, byteData);
#endif

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK3);

    /* Setup the MAC address */
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAADR1, pNetIF->hwaddr[0]);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAADR2, pNetIF->hwaddr[1]);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAADR3, pNetIF->hwaddr[2]);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAADR4, pNetIF->hwaddr[3]);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAADR5, pNetIF->hwaddr[4]);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MAADR6, pNetIF->hwaddr[5]);

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                  CHECK DUPLEX MODE                                                   */
    duplex = enc28j60_lwip_read_phy_register(spiHandle, ENC28J60_PHCON1);

    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK2);
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_MACON3, &byteData, 1, 1);

    if (((duplex >> ENC28J60_PHCON1_PDPXMD) & 1) != ((byteData >> ENC28J60_MACON3_FULDPX_BIT) & 1))
    {
        hal_printf("enc28j60_lwip_open: check duplex setting \r\n");
    }

    /* ---------------------------------------------------------------------------------------------------- */
    /*                                                                                */

    /* The first time the ethernet is initialized, let us
        point the ETXST pointer to the beginning of the
        buffer space. Subsequent increments of this register
        will be done in the transmit function */

    s_ENC28J60_TRANSMIT_BUFFER_START = ENC28J60_TRANSMIT_BUFFER_START;
    s_ENC28J60_RECEIVE_BUFFER_START = ENC28J60_RECEIVE_BUFFER_START;

    /* enabling reception */

    /* Making sure to select the right bank */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK0);

    /* setup the ERDPTL AND ERDPTH to the beginning of the receive buffer */
    byteData = ENC28J60_RECEIVE_BUFFER_START & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERDPTL, byteData);
    byteData = (ENC28J60_RECEIVE_BUFFER_START >> 8) & 0xFF;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ERDPTH, byteData);

    /* -----------------------------------DISABLE LOOPBACK FOR HALF DUPLEX--------------------------------- */
    /*                                                                                */
#if (!ENC28J60_FULL_DUPLEX)
    shortData = enc28j60_lwip_read_phy_register(spiHandle, ENC28J60_PHCON2);
    shortData = 1 << ENC28J60_PHCON2_HDLDIS;
    enc28j60_lwip_write_phy_register(spiHandle, ENC28J60_PHCON2, shortData);
    shortData = enc28j60_lwip_read_phy_register(spiHandle, ENC28J60_PHCON2);
#endif
    /* -----------------------------------DISABLE PHY INTERRUPTS ------------------------------------------ */
    /*                                                                                */
    shortData = 0x0;
    enc28j60_lwip_write_phy_register(spiHandle, ENC28J60_PHIE, shortData);

    /* -------------------------------------- START THE DEVICE -------------------------------------------- */
    /*                                                                                */
    /* enable interrupts when a packet is received and when transmit is done */
    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_SET_OPCODE,
        ENC28J60_EIE,
        (uint8_t)((1 << ENC28J60_EIE_INTIE_BIT) | (1 << ENC28J60_EIE_PKTIE_BIT) | (1 << ENC28J60_EIE_TXERIE_BIT)));

    /* enable auto- increment */
    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_SET_OPCODE,
        ENC28J60_ECON2,
        (uint8_t)(1 << ENC28J60_ECON2_AUTOINC_BIT));

    /* enable packet reception */
    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_SET_OPCODE,
        ENC28J60_ECON1,
        (uint8_t)(1 << ENC28J60_ECON1_RXEN_BIT));

    return TRUE;
}

void enc28j60_lwip_destroy_device()
{
    uint32_t spiHandle = g_ENC28J60_LWIP_Config.DeviceConfigs[0].spiHandle;

    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE,
        ENC28J60_EIE,
        (uint8_t)(
            (1 << ENC28J60_EIE_INTIE_BIT) | (1 << ENC28J60_EIE_PKTIE_BIT) | (1 << ENC28J60_EIE_TXIE_BIT) |
            (1 << ENC28J60_EIE_TXERIE_BIT)));
}

/*
    unsigned short enc28j60_lwip_read_phy_register (SPI_DEVICE_CONFIGURATION *spiConf,
                                                unsigned long registerAddress)

    This helper function reads from a PHY register given the address of
    the register to read from.

    RETURNS - The 16bit register value

    NOTES -
        To read from a PHY register:
        1. Write the address of the PHY register to read from into
            the MIREGADR register.
        2. Set the MICMD.MIIRD bit. The read operation begins and
            the MISTAT.BUSY bit is set.
        3. Wait 10.24 ?. Poll the MISTAT.BUSY bit to be certain
            that the operation is complete. While busy, the host
            controller should not start any MIISCAN operations or
            write to the MIWRH register. When the MAC has obtained
            the register contents, the BUSY bit will clear itself.
        4. Clear the MICMD.MIIRD bit.
        5. Read the desired data from the MIRDL and MIRDH registers.
            The order that these bytes are accessed is unimportant
*/
unsigned short enc28j60_lwip_read_phy_register(uint32_t spiHandle, uint8_t registerAddress)
{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();
    unsigned char byteData;
    unsigned short returnValue;
    uint32_t retries = 100;

    /* Select Bank 2 */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK2);

    /* 1. */
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MIREGADR, registerAddress);

    /* 2. */
    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_SET_OPCODE,
        ENC28J60_MICMD,
        (uint8_t)(0x1 << ENC28J60_MICMD_MIIRD_BIT));

    /* 3. */
    /* Select Bank 3 */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK3);

    do
    {
        enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_MISTAT, &byteData, 1, 1);
        byteData &= (0x1 << ENC28J60_MISTAT_BUSY_BIT);
    } while (byteData && retries-- > 0);

    /* Select Bank 2 */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK2);

    /* 4. */
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_MICMD, &byteData, 1, 1);
    byteData = 0; //&= ~(0x1 << ENC28J60_MICMD_MIIRD_BIT);
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MICMD, byteData);

    /* Select Bank 2 */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK2);

    /* 5. */
    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_MIRDH, &byteData, 1, 1);
    returnValue = byteData << 8;

    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_MIRDL, &byteData, 1, 1);
    returnValue |= byteData;

    return (returnValue);
}

/*  void enc28j60_lwip_write_phy_register(unsigned long registerAddress,
                                     unsigned short data)

    This function write the parameter data to the register given
    by the registerAddress parameter.

    RETURNS - nothing

    NOTES -
    1. Write the address of the PHY register to write to
        into the MIREGADR register.
    2. Write the lower 8 bits of data to write into the
        MIWRL register.
    3. Write the upper 8 bits of data to write into the
        MIWRH register. Writing to this register automatically
        begins the MII transaction, so it must
        be written to after MIWRL. The MISTAT.BUSY
        bit becomes set.
*/
void enc28j60_lwip_write_phy_register(uint32_t spiHandle, uint8_t registerAddress, unsigned short data)
{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();
    unsigned char byteData;

    /* All the registers for this purpose are on bank 2 */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK2);

    /* 1. */
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MIREGADR, registerAddress);
    byteData = data & 0xFF;

    /* 2. */
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MIWRL, byteData);
    byteData = (data >> 8) & 0xFF;

    /* 3. */
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_MIWRH, byteData);
}

/*
    void enc28j60_lwip_write_spi(PENC28J60_SOFTC sc,
                            RTP_uint8_t opcode,
                            RTP_uint8_t address,
                            RTP_Puint8_t &byteData,
                            RTP_uint32_t numBytes);

    This function writes the SPI interface using the configuration parameter
    within the sc structure.  The op code parameter is used to specify which
    control register to access.  This controller has the following seven control
    register commands
        1. read control register
        2. read buffer memory
        3. write control register
        4. write buffer memory
        5. bit field set
        6. bit field clear
        7. system command (soft reset)
    The op code field selects one of the above commands.  Within each control register
    command, there are a number of registers to be accessed.  The address of a register
    is specified using the address parameter.  The data pointed by byteData field
    is written to the register
 */
void enc28j60_lwip_write_spi(uint32_t spiHandle, uint8_t opcode, uint8_t address, uint8_t byteData)
{
    uint8_t opcodeArg;
    uint8_t commandWithData[2];

    opcodeArg = ENC28J60_SPI_OPCODE_ARGUMENT(opcode, address);

    /* Combine the command and the data */
    commandWithData[0] = opcodeArg;
    commandWithData[1] = byteData;

    // CPU_SPI_nWrite8_nRead8 (spiHandle, false, commandWithData, 2, 0, 0, 0);
    SPI_WRITE_READ_SETTINGS wrc{false, 0, false, 0};
    nanoSPI_Write_Read(spiHandle, wrc, commandWithData, 2, 0, 0);
}

/* void enc28j60_lwip_soft_reset(SPI_DEVICE_CONFIGURATION *spiConf)

    A function to perform a soft reset on the Ethernet board
 */
void enc28j60_lwip_soft_reset(uint32_t spiHandle)
{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();
    uint8_t byteData;
    uint16_t shortData;
    int timeout = 1000; // 1 second

    /* First turn off RX/TX */
    enc28j60_lwip_select_bank(spiHandle, ENC28J60_CONTROL_REGISTER_BANK0);

    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE,
        ENC28J60_ECON1,
        (uint8_t)(1 << ENC28J60_ECON1_RXEN_BIT));

    /* Wait for RX to flush */
    do
    {
        OS_DELAY(1);

        enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ESTAT, &byteData, 1, 0);
    } while (timeout-- && (byteData & (1 << ENC28J60_ESTAT_RXBUSY)) != 0);

    timeout = 1000;
    /* Wait for TX to flush */
    do
    {
        OS_DELAY(1);

        enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ECON1, &byteData, 1, 0);
    } while (timeout-- && (byteData & (1 << ENC28J60_ECON1_TXRTS_BIT)) != 0);

    /* make sure voltage regulator is normal */
    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE,
        ENC28J60_ECON2,
        (uint8_t)(1 << ENC28J60_ECON2_VRPS_BIT));

    /* Reset PHY */
    enc28j60_lwip_write_phy_register(spiHandle, ENC28J60_PHCON1, (uint16_t)(1ul << ENC28J60_PHCON1_PRST));

    timeout = 1000;
    do
    {
        OS_DELAY(1);

        shortData = enc28j60_lwip_read_phy_register(spiHandle, ENC28J60_PHCON1);
    } while (timeout-- && (shortData & (1ul << ENC28J60_PHCON1_PRST)) != 0);

    enc28j60_lwip_write_spi(
        spiHandle,
        ENC28J60_SPI_BIT_FIELD_CLEAR_OPCODE,
        ENC28J60_EIE,
        (uint8_t)(
            (1 << ENC28J60_EIE_INTIE_BIT) | (1 << ENC28J60_EIE_PKTIE_BIT) | (1 << ENC28J60_EIE_TXIE_BIT) |
            (1 << ENC28J60_EIE_TXERIE_BIT)));

    /* Combine the command and the data */
    byteData = (ENC28J60_SPI_SYSTEM_COMMAND_SOFT_RESET_OPCODE << 5) | ENC28J60_SPI_SYSTEM_COMMAND_SOFT_RESET_ARGUMENT;

    SPI_WRITE_READ_SETTINGS wrc{false, 0, false, 0};
    nanoSPI_Write_Read(spiHandle, wrc, (uint8_t *)&byteData, 1, 0, 0);

    // Errata : After reset wait for 100 ms
    OS_DELAY(100);
}

/*
    void enc28j60_lwip_read_spi(PENC28J60_SOFTC sc,
                            RTP_uint8_t opcode,
                            RTP_uint8_t address,
                            RTP_Puint8_t &byteData,
                            RTP_uint32_t numBytes)

    This function reads from the SPI interface using the configuration parameter
    within the sc structure.  The opcode parameter is used to specify which
    control register to access.  This controller has the following seven control
    register commands
        1. read control register
        2. read buffer memory
        3. write control register
        4. write buffer memory
        5. bit field set
        6. bit field clear
        7. system command (soft reset)
    The opcode field selects one of the above commands.  Within each control register
    command, there are a number of registers to be accessed.  The address of a register
    is specified using the address parameter.  Contents of the register are written into
    the byteData
 */

void enc28j60_lwip_read_spi(
    uint32_t spiHandle,
    uint8_t opcode,
    uint8_t address,
    uint8_t *byteData,
    uint32_t numBytes,
    uint8_t offset)
{
    uint8_t opcodeArg;

    opcodeArg = ENC28J60_SPI_OPCODE_ARGUMENT(opcode, address);

    /* Write the command and read*/
    //    CPU_SPI_nWrite8_nRead8 (spiHandle, false, &opcodeArg, 1, byteData, numBytes+offset, offset+1);
    // Note uses offset on read data
    SPI_WRITE_READ_SETTINGS wrc{false, offset, false, 0};
    nanoSPI_Write_Read(spiHandle, wrc, &opcodeArg, 1, byteData, numBytes);
}

/*
    void enc28j60_lwip_select_bank(sc, unsigned short bankNumber)

    Given the bank number this function selects one of the
    four banks.
*/

void enc28j60_lwip_select_bank(uint32_t spiHandle, uint8_t bankNumber)
{
    NATIVE_PROFILE_HAL_DRIVERS_ETHERNET();
    uint8_t byteData = 0;

    bankNumber &= 0x3;

    enc28j60_lwip_read_spi(spiHandle, ENC28J60_SPI_READ_CONTROL_REGISTER_OPCODE, ENC28J60_ECON1, &byteData, 1, 0);
    byteData &= 0xFC;
    byteData |= bankNumber;
    enc28j60_lwip_write_spi(spiHandle, ENC28J60_SPI_WRITE_CONTROL_REGISTER_OPCODE, ENC28J60_ECON1, byteData);
}

bool enc28j60_get_link_status(uint32_t spiHandle)
{
    uint16_t phyStat;

    GLOBAL_LOCK();

    phyStat = enc28j60_lwip_read_phy_register(spiHandle, ENC28J60_PHSTAT2);

    GLOBAL_UNLOCK();

    // linkstatus bit
    return ((phyStat & (1ul << ENC28J60_PHSTAT2_LSTAT_BIT)) != 0);
}


text:
package org.apache.http.impl.cookie;

public class RFC2109Spec
  extends CookieSpecBase{
  // Constructors

  public RFC2109Spec(java.lang.String [] arg1, boolean arg2){
    super();
  }
  public RFC2109Spec(){
    super();
  }
  // Methods

  public java.util.List<org.apache.http.cookie.Cookie> parse(org.apache.http.Header arg1, org.apache.http.cookie.CookieOrigin arg2) throws org.apache.http.cookie.MalformedCookieException{
    return (java.util.List) null;
  }
  public int getVersion(){
    return 0;
  }
  public void validate(org.apache.http.cookie.Cookie arg1, org.apache.http.cookie.CookieOrigin arg2) throws org.apache.http.cookie.MalformedCookieException{
  }
  public java.util.List<org.apache.http.Header> formatCookies(java.util.List<org.apache.http.cookie.Cookie> arg1){
    return (java.util.List) null;
  }
  public org.apache.http.Header getVersionHeader(){
    return (org.apache.http.Header) null;
  }
  protected void formatParamAsVer(org.apache.http.util.CharArrayBuffer arg1, java.lang.String arg2, java.lang.String arg3, int arg4){
  }
  protected void formatCookieAsVer(org.apache.http.util.CharArrayBuffer arg1, org.apache.http.cookie.Cookie arg2, int arg3){
  }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef KVOIDPOINTERFACTORY_P_H
#define KVOIDPOINTERFACTORY_P_H

#include <vector>
#include <cstdlib>
#include <cstddef>

#define DEFAULT_BLOCK_SIZE 256

/**
 * @brief A Class for managing void pointers for use in QModelIndexes.
 *
 * This class creates void pointers pointing to individual blocks of memory.
 * The pointed-to memory contains zeros.
 *
 * Memory is allocated in blocks of size @p blockSize times sizeof(void*) at a time. The used
 * memory is automatically freed and can be cleared manually.
 *
 * The void pointers should not be dereferenced, but only used as a unique
 * identifier suitable for use with createIndex() and for comparison with other void pointers.
 */
template<std::size_t blockSize = DEFAULT_BLOCK_SIZE>
class KVoidPointerFactory
{
  // a class with size 1.
  class Bit { bool bit; };

public:
  KVoidPointerFactory()
    : m_previousPointer(0),
      m_finalPointer(0)
  {
  }

  KVoidPointerFactory(const KVoidPointerFactory<blockSize> &other)
  {
    *this = other;
  }

  KVoidPointerFactory<blockSize>& operator=(const KVoidPointerFactory<blockSize> &other)
  {
    m_previousPointer = other.m_previousPointer;
    m_finalPointer = other.m_finalPointer;
    m_blocks = other.m_blocks;
    return *this;
  }

  ~KVoidPointerFactory()
  {
    clear();
  }

  void clear()
  {
    typename std::vector<Bit*>::const_iterator it = m_blocks.begin();
    const typename std::vector<Bit*>::const_iterator end = m_blocks.end();
    for ( ; it != end; ++it)
    {
      free(*it);
    }
    m_blocks.clear();
    m_finalPointer = 0;
    m_previousPointer = 0;
  }

  void* createPointer() const
  {
    if (m_previousPointer == m_finalPointer)
    {
      static const std::size_t pointer_size = sizeof(Bit*);
      Bit * const bit = static_cast<Bit*>(calloc(blockSize, pointer_size));
      m_blocks.push_back(bit);
      m_finalPointer = bit + (blockSize * pointer_size) - 1;
      m_previousPointer = bit;
      return bit;
    }
    return ++m_previousPointer;
  }

private:
  mutable std::vector<Bit *> m_blocks;
  mutable Bit *m_previousPointer;
  mutable Bit *m_finalPointer;
};

// Disable factory with 0 blockSize
template<>
class KVoidPointerFactory<0>
{
public:
  KVoidPointerFactory();

  void clear();
  void* createPointer();
};

#endif


text:
using namespace llvm;
using namespace llvm::sys;

#define ASSERT_NO_ERROR(x) \
  if (error_code ASSERT_NO_ERROR_ec = x) { \
    SmallString<128> MessageStorage; \
    raw_svector_ostream Message(MessageStorage); \
    Message << #x ": did not return errc::success.\n" \
            << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
            << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
    GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
  } else {}

namespace {

TEST(is_separator, Works) {
  EXPECT_TRUE(path::is_separator('/'));
  EXPECT_FALSE(path::is_separator('\0'));
  EXPECT_FALSE(path::is_separator('-'));
  EXPECT_FALSE(path::is_separator(' '));

#ifdef LLVM_ON_WIN32
  EXPECT_TRUE(path::is_separator('\\'));
#else
  EXPECT_FALSE(path::is_separator('\\'));
#endif
}

TEST(Support, Path) {
  SmallVector<StringRef, 40> paths;
  paths.push_back("");
  paths.push_back(".");
  paths.push_back("..");
  paths.push_back("foo");
  paths.push_back("/");
  paths.push_back("/foo");
  paths.push_back("foo/");
  paths.push_back("/foo/");
  paths.push_back("foo/bar");
  paths.push_back("/foo/bar");
  paths.push_back("//net");
  paths.push_back("//net/foo");
  paths.push_back("///foo///");
  paths.push_back("///foo///bar");
  paths.push_back("/.");
  paths.push_back("./");
  paths.push_back("/..");
  paths.push_back("../");
  paths.push_back("foo/.");
  paths.push_back("foo/..");
  paths.push_back("foo/./");
  paths.push_back("foo/./bar");
  paths.push_back("foo/..");
  paths.push_back("foo/../");
  paths.push_back("foo/../bar");
  paths.push_back("c:");
  paths.push_back("c:/");
  paths.push_back("c:foo");
  paths.push_back("c:/foo");
  paths.push_back("c:foo/");
  paths.push_back("c:/foo/");
  paths.push_back("c:/foo/bar");
  paths.push_back("prn:");
  paths.push_back("c:\\");
  paths.push_back("c:foo");
  paths.push_back("c:\\foo");
  paths.push_back("c:foo\\");
  paths.push_back("c:\\foo\\");
  paths.push_back("c:\\foo/");
  paths.push_back("c:/foo\\bar");

  for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
                                                  e = paths.end();
                                                  i != e;
                                                  ++i) {
    for (sys::path::const_iterator ci = sys::path::begin(*i),
                                   ce = sys::path::end(*i);
                                   ci != ce;
                                   ++ci) {
      ASSERT_FALSE(ci->empty());
    }

#if 0 // Valgrind is whining about this.
    outs() << "    Reverse Iteration: [";
    for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
                                     ce = sys::path::rend(*i);
                                     ci != ce;
                                     ++ci) {
      outs() << *ci << ',';
    }
    outs() << "]\n";
#endif

    path::has_root_path(*i);
    path::root_path(*i);
    path::has_root_name(*i);
    path::root_name(*i);
    path::has_root_directory(*i);
    path::root_directory(*i);
    path::has_parent_path(*i);
    path::parent_path(*i);
    path::has_filename(*i);
    path::filename(*i);
    path::has_stem(*i);
    path::stem(*i);
    path::has_extension(*i);
    path::extension(*i);
    path::is_absolute(*i);
    path::is_relative(*i);

    SmallString<128> temp_store;
    temp_store = *i;
    ASSERT_NO_ERROR(fs::make_absolute(temp_store));
    temp_store = *i;
    path::remove_filename(temp_store);

    temp_store = *i;
    path::replace_extension(temp_store, "ext");
    StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
    stem = path::stem(filename);
    ext  = path::extension(filename);
    EXPECT_EQ(*(--sys::path::end(filename)), (stem + ext).str());

    path::native(*i, temp_store);
  }
}

class FileSystemTest : public testing::Test {
protected:
  /// Unique temporary directory in which all created filesystem entities must
  /// be placed. It is recursively removed at the end of each test.
  SmallString<128> TestDirectory;

  virtual void SetUp() {
    int fd;
    ASSERT_NO_ERROR(
      fs::unique_file("file-system-test-%%-%%-%%-%%/test-directory.anchor", fd,
                      TestDirectory));
    // We don't care about this specific file.
    ::close(fd);
    TestDirectory = path::parent_path(TestDirectory);
    errs() << "Test Directory: " << TestDirectory << '\n';
    errs().flush();
  }

  virtual void TearDown() {
    uint32_t removed;
    ASSERT_NO_ERROR(fs::remove_all(TestDirectory.str(), removed));
  }
};

TEST_F(FileSystemTest, TempFiles) {
  // Create a temp file.
  int FileDescriptor;
  SmallString<64> TempPath;
  ASSERT_NO_ERROR(
    fs::unique_file("%%-%%-%%-%%.temp", FileDescriptor, TempPath));

  // Make sure it exists.
  bool TempFileExists;
  ASSERT_NO_ERROR(sys::fs::exists(Twine(TempPath), TempFileExists));
  EXPECT_TRUE(TempFileExists);

  // Create another temp tile.
  int FD2;
  SmallString<64> TempPath2;
  ASSERT_NO_ERROR(fs::unique_file("%%-%%-%%-%%.temp", FD2, TempPath2));
  ASSERT_NE(TempPath.str(), TempPath2.str());

  fs::file_status A, B;
  ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
  ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
  EXPECT_FALSE(fs::equivalent(A, B));

  // Try to copy the first to the second.
  EXPECT_EQ(
    fs::copy_file(Twine(TempPath), Twine(TempPath2)), errc::file_exists);

  ::close(FD2);
  // Try again with the proper options.
  ASSERT_NO_ERROR(fs::copy_file(Twine(TempPath), Twine(TempPath2),
                                fs::copy_option::overwrite_if_exists));
  // Remove Temp2.
  ASSERT_NO_ERROR(fs::remove(Twine(TempPath2), TempFileExists));
  EXPECT_TRUE(TempFileExists);

  // Make sure Temp2 doesn't exist.
  ASSERT_NO_ERROR(fs::exists(Twine(TempPath2), TempFileExists));
  EXPECT_FALSE(TempFileExists);

  // Create a hard link to Temp1.
  ASSERT_NO_ERROR(fs::create_hard_link(Twine(TempPath), Twine(TempPath2)));
  bool equal;
  ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
  EXPECT_TRUE(equal);
  ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
  ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
  EXPECT_TRUE(fs::equivalent(A, B));

  // Remove Temp1.
  ::close(FileDescriptor);
  ASSERT_NO_ERROR(fs::remove(Twine(TempPath), TempFileExists));
  EXPECT_TRUE(TempFileExists);

  // Remove the hard link.
  ASSERT_NO_ERROR(fs::remove(Twine(TempPath2), TempFileExists));
  EXPECT_TRUE(TempFileExists);

  // Make sure Temp1 doesn't exist.
  ASSERT_NO_ERROR(fs::exists(Twine(TempPath), TempFileExists));
  EXPECT_FALSE(TempFileExists);

#ifdef LLVM_ON_WIN32
  // Path name > 260 chars should get an error.
  const char *Path270 =
    "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
    "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
    "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
    "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
    "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
  EXPECT_EQ(fs::unique_file(Twine(Path270), FileDescriptor, TempPath),
            windows_error::path_not_found);
#endif
}

TEST_F(FileSystemTest, DirectoryIteration) {
  error_code ec;
  for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
    ASSERT_NO_ERROR(ec);

  // Create a known hierarchy to recurse over.
  bool existed;
  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
                  + "/recursive/a0/aa1", existed));
  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
                  + "/recursive/a0/ab1", existed));
  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
                  + "/recursive/dontlookhere/da1", existed));
  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
                  + "/recursive/z0/za1", existed));
  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
                  + "/recursive/pop/p1", existed));
  typedef std::vector<std::string> v_t;
  v_t visited;
  for (fs::recursive_directory_iterator i(Twine(TestDirectory)
         + "/recursive", ec), e; i != e; i.increment(ec)){
    ASSERT_NO_ERROR(ec);
    if (path::filename(i->path()) == "p1") {
      i.pop();
      // FIXME: recursive_directory_iterator should be more robust.
      if (i == e) break;
    }
    if (path::filename(i->path()) == "dontlookhere")
      i.no_push();
    visited.push_back(path::filename(i->path()));
  }
  v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
  v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
  v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
  v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
                                               "dontlookhere");
  v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
  v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
  v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
  v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
  v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");

  // Make sure that each path was visited correctly.
  ASSERT_NE(a0, visited.end());
  ASSERT_NE(aa1, visited.end());
  ASSERT_NE(ab1, visited.end());
  ASSERT_NE(dontlookhere, visited.end());
  ASSERT_EQ(da1, visited.end()); // Not visited.
  ASSERT_NE(z0, visited.end());
  ASSERT_NE(za1, visited.end());
  ASSERT_NE(pop, visited.end());
  ASSERT_EQ(p1, visited.end()); // Not visited.

  // Make sure that parents were visited before children. No other ordering
  // guarantees can be made across siblings.
  ASSERT_LT(a0, aa1);
  ASSERT_LT(a0, ab1);
  ASSERT_LT(z0, za1);
}

const char elf[] = {0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};

TEST_F(FileSystemTest, Magic) {
  struct type {
    const char *filename;
    const char *magic_str;
    size_t magic_str_len;
    fs::file_magic magic;
  } types [] = {
    {"magic.archive", "!<arch>\x0A", 8, fs::file_magic::archive},
    {"magic.elf", elf, sizeof(elf),
     fs::file_magic::elf_relocatable}
  };

  // Create some files filled with magic.
  for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
                                                                     ++i) {
    SmallString<128> file_pathname(TestDirectory);
    path::append(file_pathname, i->filename);
    std::string ErrMsg;
    raw_fd_ostream file(file_pathname.c_str(), ErrMsg,
                        raw_fd_ostream::F_Binary);
    ASSERT_FALSE(file.has_error());
    StringRef magic(i->magic_str, i->magic_str_len);
    file << magic;
    file.close();
    bool res = false;
    ASSERT_NO_ERROR(fs::has_magic(file_pathname.c_str(), magic, res));
    EXPECT_TRUE(res);
    EXPECT_EQ(i->magic, fs::identify_magic(magic));
  }
}

#if !defined(_WIN32) // FIXME: Win32 has different permission schema.
TEST_F(FileSystemTest, Permissions) {
  // Create a temp file.
  int FileDescriptor;
  SmallString<64> TempPath;
  ASSERT_NO_ERROR(
    fs::unique_file("%%-%%-%%-%%.temp", FileDescriptor, TempPath));

  // Mark file as read-only
  const fs::perms AllWrite = fs::owner_write|fs::group_write|fs::others_write;
  ASSERT_NO_ERROR(fs::permissions(Twine(TempPath), fs::remove_perms|AllWrite));

  // Verify file is read-only
  fs::file_status Status;
  ASSERT_NO_ERROR(fs::status(Twine(TempPath), Status));
  bool AnyWriteBits = (Status.permissions() & AllWrite);
  EXPECT_FALSE(AnyWriteBits);

  // Mark file as read-write
  ASSERT_NO_ERROR(fs::permissions(Twine(TempPath), fs::add_perms|AllWrite));

  // Verify file is read-write
  ASSERT_NO_ERROR(fs::status(Twine(TempPath), Status));
  AnyWriteBits = (Status.permissions() & AllWrite);
  EXPECT_TRUE(AnyWriteBits);
}
#endif

TEST_F(FileSystemTest, FileMapping) {
  // Create a temp file.
  int FileDescriptor;
  SmallString<64> TempPath;
  ASSERT_NO_ERROR(
    fs::unique_file("%%-%%-%%-%%.temp", FileDescriptor, TempPath));
  // Map in temp file and add some content
  error_code EC;
  StringRef Val("hello there");
  {
    fs::mapped_file_region mfr(FileDescriptor,
                               true,
                               fs::mapped_file_region::readwrite,
                               4096,
                               0,
                               EC);
    ASSERT_NO_ERROR(EC);
    std::copy(Val.begin(), Val.end(), mfr.data());
    // Explicitly add a 0.
    mfr.data()[Val.size()] = 0;
    // Unmap temp file
  }

  // Map it back in read-only
  fs::mapped_file_region mfr(Twine(TempPath),
                             fs::mapped_file_region::readonly,
                             0,
                             0,
                             EC);
  ASSERT_NO_ERROR(EC);

  // Verify content
  EXPECT_EQ(StringRef(mfr.const_data()), Val);

  // Unmap temp file

#if LLVM_HAS_RVALUE_REFERENCES
  fs::mapped_file_region m(Twine(TempPath),
                             fs::mapped_file_region::readonly,
                             0,
                             0,
                             EC);
  ASSERT_NO_ERROR(EC);
  const char *Data = m.const_data();
  fs::mapped_file_region mfrrv(llvm_move(m));
  EXPECT_EQ(mfrrv.const_data(), Data);
#endif
}
} // anonymous namespace


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface com.badlogic.gdx.net.ServerSocket (libgdx API)</title>
<meta name="date" content="2016-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.badlogic.gdx.net.ServerSocket

Packages that use ServerSocket

Package
Description

com.badlogic.gdx

com.badlogic.gdx.net

Uses of ServerSocket in com.badlogic.gdx

Methods in com.badlogic.gdx that return ServerSocket

Modifier and Type
Method and Description

ServerSocket
Net.newServerSocket(Net.Protocol protocol,
               int port,
               ServerSocketHints hints)

Creates a new server socket on the given port, using the given Net.Protocol, waiting for incoming connections.

ServerSocket
Net.newServerSocket(Net.Protocol protocol,
               java.lang.String hostname,
               int port,
               ServerSocketHints hints)

Creates a new server socket on the given address and port, using the given Net.Protocol, waiting for incoming connections.

Uses of ServerSocket in com.badlogic.gdx.net

Classes in com.badlogic.gdx.net that implement ServerSocket

Modifier and Type
Class and Description

class
NetJavaServerSocketImpl

Server socket implementation using java.net.ServerSocket.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev

Next

Frames

No Frames

All Classes

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
namespace clang {

class ASTConsumer;
class CXXBaseSpecifier;
class CXXCtorInitializer;
class DeclarationName;
class ExternalSemaSource; // layering violation required for downcasting
class FieldDecl;
class Module;
class NamedDecl;
class RecordDecl;
class Selector;
class Stmt;
class TagDecl;

/// \brief Abstract interface for external sources of AST nodes.
///
/// External AST sources provide AST nodes constructed from some
/// external source, such as a precompiled header. External AST
/// sources can resolve types and declarations from abstract IDs into
/// actual type and declaration nodes, and read parts of declaration
/// contexts.
class ExternalASTSource : public RefCountedBase<ExternalASTSource> {
  /// Generation number for this external AST source. Must be increased
  /// whenever we might have added new redeclarations for existing decls.
  uint32_t CurrentGeneration;

  /// \brief Whether this AST source also provides information for
  /// semantic analysis.
  bool SemaSource;

  friend class ExternalSemaSource;

public:
  ExternalASTSource() : CurrentGeneration(0), SemaSource(false) { }

  virtual ~ExternalASTSource();

  /// \brief RAII class for safely pairing a StartedDeserializing call
  /// with FinishedDeserializing.
  class Deserializing {
    ExternalASTSource *Source;
  public:
    explicit Deserializing(ExternalASTSource *source) : Source(source) {
      assert(Source);
      Source->StartedDeserializing();
    }
    ~Deserializing() {
      Source->FinishedDeserializing();
    }
  };

  /// \brief Get the current generation of this AST source. This number
  /// is incremented each time the AST source lazily extends an existing
  /// entity.
  uint32_t getGeneration() const { return CurrentGeneration; }

  /// \brief Resolve a declaration ID into a declaration, potentially
  /// building a new declaration.
  ///
  /// This method only needs to be implemented if the AST source ever
  /// passes back decl sets as VisibleDeclaration objects.
  ///
  /// The default implementation of this method is a no-op.
  virtual Decl *GetExternalDecl(uint32_t ID);

  /// \brief Resolve a selector ID into a selector.
  ///
  /// This operation only needs to be implemented if the AST source
  /// returns non-zero for GetNumKnownSelectors().
  ///
  /// The default implementation of this method is a no-op.
  virtual Selector GetExternalSelector(uint32_t ID);

  /// \brief Returns the number of selectors known to the external AST
  /// source.
  ///
  /// The default implementation of this method is a no-op.
  virtual uint32_t GetNumExternalSelectors();

  /// \brief Resolve the offset of a statement in the decl stream into
  /// a statement.
  ///
  /// This operation is meant to be used via a LazyOffsetPtr.  It only
  /// needs to be implemented if the AST source uses methods like
  /// FunctionDecl::setLazyBody when building decls.
  ///
  /// The default implementation of this method is a no-op.
  virtual Stmt *GetExternalDeclStmt(uint64_t Offset);

  /// \brief Resolve the offset of a set of C++ constructor initializers in
  /// the decl stream into an array of initializers.
  ///
  /// The default implementation of this method is a no-op.
  virtual CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset);

  /// \brief Resolve the offset of a set of C++ base specifiers in the decl
  /// stream into an array of specifiers.
  ///
  /// The default implementation of this method is a no-op.
  virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);

  /// \brief Update an out-of-date identifier.
  virtual void updateOutOfDateIdentifier(IdentifierInfo &II) { }

  /// \brief Find all declarations with the given name in the given context,
  /// and add them to the context by calling SetExternalVisibleDeclsForName
  /// or SetNoExternalVisibleDeclsForName.
  /// \return \c true if any declarations might have been found, \c false if
  /// we definitely have no declarations with tbis name.
  ///
  /// The default implementation of this method is a no-op returning \c false.
  virtual bool
  FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name);

  /// \brief Ensures that the table of all visible declarations inside this
  /// context is up to date.
  ///
  /// The default implementation of this function is a no-op.
  virtual void completeVisibleDeclsMap(const DeclContext *DC);

  /// \brief Retrieve the module that corresponds to the given module ID.
  virtual Module *getModule(unsigned ID) { return nullptr; }

  /// Abstracts clang modules and precompiled header files and holds
  /// everything needed to generate debug info for an imported module
  /// or PCH.
  class ASTSourceDescriptor {
    StringRef PCHModuleName;
    StringRef Path;
    StringRef ASTFile;
    uint64_t Signature = 0;
    const Module *ClangModule = nullptr;

  public:
    ASTSourceDescriptor(){};
    ASTSourceDescriptor(StringRef Name, StringRef Path, StringRef ASTFile,
                        uint64_t Signature)
        : PCHModuleName(std::move(Name)), Path(std::move(Path)),
          ASTFile(std::move(ASTFile)), Signature(Signature){};
    ASTSourceDescriptor(const Module &M);
    std::string getModuleName() const;
    StringRef getPath() const { return Path; }
    StringRef getASTFile() const { return ASTFile; }
    uint64_t getSignature() const { return Signature; }
    const Module *getModuleOrNull() const { return ClangModule; }
  };

  /// Return a descriptor for the corresponding module, if one exists.
  virtual llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID);

  /// \brief Finds all declarations lexically contained within the given
  /// DeclContext, after applying an optional filter predicate.
  ///
  /// \param IsKindWeWant a predicate function that returns true if the passed
  /// declaration kind is one we are looking for.
  ///
  /// The default implementation of this method is a no-op.
  virtual void
  FindExternalLexicalDecls(const DeclContext *DC,
                           llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
                           SmallVectorImpl<Decl *> &Result);

  /// \brief Finds all declarations lexically contained within the given
  /// DeclContext.
  void FindExternalLexicalDecls(const DeclContext *DC,
                                SmallVectorImpl<Decl *> &Result) {
    FindExternalLexicalDecls(DC, [](Decl::Kind) { return true; }, Result);
  }

  /// \brief Get the decls that are contained in a file in the Offset/Length
  /// range. \p Length can be 0 to indicate a point at \p Offset instead of
  /// a range.
  virtual void FindFileRegionDecls(FileID File, unsigned Offset,
                                   unsigned Length,
                                   SmallVectorImpl<Decl *> &Decls);

  /// \brief Gives the external AST source an opportunity to complete
  /// the redeclaration chain for a declaration. Called each time we
  /// need the most recent declaration of a declaration after the
  /// generation count is incremented.
  virtual void CompleteRedeclChain(const Decl *D);

  /// \brief Gives the external AST source an opportunity to complete
  /// an incomplete type.
  virtual void CompleteType(TagDecl *Tag);

  /// \brief Gives the external AST source an opportunity to complete an
  /// incomplete Objective-C class.
  ///
  /// This routine will only be invoked if the "externally completed" bit is
  /// set on the ObjCInterfaceDecl via the function
  /// \c ObjCInterfaceDecl::setExternallyCompleted().
  virtual void CompleteType(ObjCInterfaceDecl *Class);

  /// \brief Loads comment ranges.
  virtual void ReadComments();

  /// \brief Notify ExternalASTSource that we started deserialization of
  /// a decl or type so until FinishedDeserializing is called there may be
  /// decls that are initializing. Must be paired with FinishedDeserializing.
  ///
  /// The default implementation of this method is a no-op.
  virtual void StartedDeserializing();

  /// \brief Notify ExternalASTSource that we finished the deserialization of
  /// a decl or type. Must be paired with StartedDeserializing.
  ///
  /// The default implementation of this method is a no-op.
  virtual void FinishedDeserializing();

  /// \brief Function that will be invoked when we begin parsing a new
  /// translation unit involving this external AST source.
  ///
  /// The default implementation of this method is a no-op.
  virtual void StartTranslationUnit(ASTConsumer *Consumer);

  /// \brief Print any statistics that have been gathered regarding
  /// the external AST source.
  ///
  /// The default implementation of this method is a no-op.
  virtual void PrintStats();

  /// \brief Perform layout on the given record.
  ///
  /// This routine allows the external AST source to provide an specific
  /// layout for a record, overriding the layout that would normally be
  /// constructed. It is intended for clients who receive specific layout
  /// details rather than source code (such as LLDB). The client is expected
  /// to fill in the field offsets, base offsets, virtual base offsets, and
  /// complete object size.
  ///
  /// \param Record The record whose layout is being requested.
  ///
  /// \param Size The final size of the record, in bits.
  ///
  /// \param Alignment The final alignment of the record, in bits.
  ///
  /// \param FieldOffsets The offset of each of the fields within the record,
  /// expressed in bits. All of the fields must be provided with offsets.
  ///
  /// \param BaseOffsets The offset of each of the direct, non-virtual base
  /// classes. If any bases are not given offsets, the bases will be laid
  /// out according to the ABI.
  ///
  /// \param VirtualBaseOffsets The offset of each of the virtual base classes
  /// (either direct or not). If any bases are not given offsets, the bases will be laid
  /// out according to the ABI.
  ///
  /// \returns true if the record layout was provided, false otherwise.
  virtual bool layoutRecordType(
      const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
      llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets,
      llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets,
      llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets);

  //===--------------------------------------------------------------------===//
  // Queries for performance analysis.
  //===--------------------------------------------------------------------===//

  struct MemoryBufferSizes {
    size_t malloc_bytes;
    size_t mmap_bytes;

    MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
    : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
  };

  /// Return the amount of memory used by memory buffers, breaking down
  /// by heap-backed versus mmap'ed memory.
  MemoryBufferSizes getMemoryBufferSizes() const {
    MemoryBufferSizes sizes(0, 0);
    getMemoryBufferSizes(sizes);
    return sizes;
  }

  virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;

protected:
  static DeclContextLookupResult
  SetExternalVisibleDeclsForName(const DeclContext *DC,
                                 DeclarationName Name,
                                 ArrayRef<NamedDecl*> Decls);

  static DeclContextLookupResult
  SetNoExternalVisibleDeclsForName(const DeclContext *DC,
                                   DeclarationName Name);

  /// \brief Increment the current generation.
  uint32_t incrementGeneration(ASTContext &C);
};

/// \brief A lazy pointer to an AST node (of base type T) that resides
/// within an external AST source.
///
/// The AST node is identified within the external AST source by a
/// 63-bit offset, and can be retrieved via an operation on the
/// external AST source itself.
template<typename T, typename OffsT, T* (ExternalASTSource::*Get)(OffsT Offset)>
struct LazyOffsetPtr {
  /// \brief Either a pointer to an AST node or the offset within the
  /// external AST source where the AST node can be found.
  ///
  /// If the low bit is clear, a pointer to the AST node. If the low
  /// bit is set, the upper 63 bits are the offset.
  mutable uint64_t Ptr;

public:
  LazyOffsetPtr() : Ptr(0) { }

  explicit LazyOffsetPtr(T *Ptr) : Ptr(reinterpret_cast<uint64_t>(Ptr)) { }
  explicit LazyOffsetPtr(uint64_t Offset) : Ptr((Offset << 1) | 0x01) {
    assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
    if (Offset == 0)
      Ptr = 0;
  }

  LazyOffsetPtr &operator=(T *Ptr) {
    this->Ptr = reinterpret_cast<uint64_t>(Ptr);
    return *this;
  }

  LazyOffsetPtr &operator=(uint64_t Offset) {
    assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
    if (Offset == 0)
      Ptr = 0;
    else
      Ptr = (Offset << 1) | 0x01;

    return *this;
  }

  /// \brief Whether this pointer is non-NULL.
  ///
  /// This operation does not require the AST node to be deserialized.
  explicit operator bool() const { return Ptr != 0; }

  /// \brief Whether this pointer is non-NULL.
  ///
  /// This operation does not require the AST node to be deserialized.
  bool isValid() const { return Ptr != 0; }

  /// \brief Whether this pointer is currently stored as an offset.
  bool isOffset() const { return Ptr & 0x01; }

  /// \brief Retrieve the pointer to the AST node that this lazy pointer
  ///
  /// \param Source the external AST source.
  ///
  /// \returns a pointer to the AST node.
  T* get(ExternalASTSource *Source) const {
    if (isOffset()) {
      assert(Source &&
             "Cannot deserialize a lazy pointer without an AST source");
      Ptr = reinterpret_cast<uint64_t>((Source->*Get)(Ptr >> 1));
    }
    return reinterpret_cast<T*>(Ptr);
  }
};

/// \brief A lazy value (of type T) that is within an AST node of type Owner,
/// where the value might change in later generations of the external AST
/// source.
template<typename Owner, typename T, void (ExternalASTSource::*Update)(Owner)>
struct LazyGenerationalUpdatePtr {
  /// A cache of the value of this pointer, in the most recent generation in
  /// which we queried it.
  struct LazyData {
    LazyData(ExternalASTSource *Source, T Value)
        : ExternalSource(Source), LastGeneration(0), LastValue(Value) {}
    ExternalASTSource *ExternalSource;
    uint32_t LastGeneration;
    T LastValue;
  };

  // Our value is represented as simply T if there is no external AST source.
  typedef llvm::PointerUnion<T, LazyData*> ValueType;
  ValueType Value;

  LazyGenerationalUpdatePtr(ValueType V) : Value(V) {}

  // Defined in ASTContext.h
  static ValueType makeValue(const ASTContext &Ctx, T Value);

public:
  explicit LazyGenerationalUpdatePtr(const ASTContext &Ctx, T Value = T())
      : Value(makeValue(Ctx, Value)) {}

  /// Create a pointer that is not potentially updated by later generations of
  /// the external AST source.
  enum NotUpdatedTag { NotUpdated };
  LazyGenerationalUpdatePtr(NotUpdatedTag, T Value = T())
      : Value(Value) {}

  /// Forcibly set this pointer (which must be lazy) as needing updates.
  void markIncomplete() {
    Value.template get<LazyData *>()->LastGeneration = 0;
  }

  /// Set the value of this pointer, in the current generation.
  void set(T NewValue) {
    if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>()) {
      LazyVal->LastValue = NewValue;
      return;
    }
    Value = NewValue;
  }

  /// Set the value of this pointer, for this and all future generations.
  void setNotUpdated(T NewValue) { Value = NewValue; }

  /// Get the value of this pointer, updating its owner if necessary.
  T get(Owner O) {
    if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>()) {
      if (LazyVal->LastGeneration != LazyVal->ExternalSource->getGeneration()) {
        LazyVal->LastGeneration = LazyVal->ExternalSource->getGeneration();
        (LazyVal->ExternalSource->*Update)(O);
      }
      return LazyVal->LastValue;
    }
    return Value.template get<T>();
  }

  /// Get the most recently computed value of this pointer without updating it.
  T getNotUpdated() const {
    if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>())
      return LazyVal->LastValue;
    return Value.template get<T>();
  }

  void *getOpaqueValue() { return Value.getOpaqueValue(); }
  static LazyGenerationalUpdatePtr getFromOpaqueValue(void *Ptr) {
    return LazyGenerationalUpdatePtr(ValueType::getFromOpaqueValue(Ptr));
  }
};
} // end namespace clang

/// Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be
/// placed into a PointerUnion.
namespace llvm {
template<typename Owner, typename T,
         void (clang::ExternalASTSource::*Update)(Owner)>
struct PointerLikeTypeTraits<
    clang::LazyGenerationalUpdatePtr<Owner, T, Update>> {
  typedef clang::LazyGenerationalUpdatePtr<Owner, T, Update> Ptr;
  static void *getAsVoidPointer(Ptr P) { return P.getOpaqueValue(); }
  static Ptr getFromVoidPointer(void *P) { return Ptr::getFromOpaqueValue(P); }
  enum {
    NumLowBitsAvailable = PointerLikeTypeTraits<T>::NumLowBitsAvailable - 1
  };
};
}

namespace clang {
/// \brief Represents a lazily-loaded vector of data.
///
/// The lazily-loaded vector of data contains data that is partially loaded
/// from an external source and partially added by local translation. The
/// items loaded from the external source are loaded lazily, when needed for
/// iteration over the complete vector.
template<typename T, typename Source,
         void (Source::*Loader)(SmallVectorImpl<T>&),
         unsigned LoadedStorage = 2, unsigned LocalStorage = 4>
class LazyVector {
  SmallVector<T, LoadedStorage> Loaded;
  SmallVector<T, LocalStorage> Local;

public:
  /// Iteration over the elements in the vector.
  ///
  /// In a complete iteration, the iterator walks the range [-M, N),
  /// where negative values are used to indicate elements
  /// loaded from the external source while non-negative values are used to
  /// indicate elements added via \c push_back().
  /// However, to provide iteration in source order (for, e.g., chained
  /// precompiled headers), dereferencing the iterator flips the negative
  /// values (corresponding to loaded entities), so that position -M
  /// corresponds to element 0 in the loaded entities vector, position -M+1
  /// corresponds to element 1 in the loaded entities vector, etc. This
  /// gives us a reasonably efficient, source-order walk.
  ///
  /// We define this as a wrapping iterator around an int. The
  /// iterator_adaptor_base class forwards the iterator methods to basic integer
  /// arithmetic.
  class iterator : public llvm::iterator_adaptor_base<
                       iterator, int, std::random_access_iterator_tag, T, int> {
    LazyVector *Self;

    iterator(LazyVector *Self, int Position)
        : iterator::iterator_adaptor_base(Position), Self(Self) {}

    bool isLoaded() const { return this->I < 0; }
    friend class LazyVector;

  public:
    iterator() : iterator(nullptr, 0) {}

    typename iterator::reference operator*() const {
      if (isLoaded())
        return Self->Loaded.end()[this->I];
      return Self->Local.begin()[this->I];
    }
  };

  iterator begin(Source *source, bool LocalOnly = false) {
    if (LocalOnly)
      return iterator(this, 0);

    if (source)
      (source->*Loader)(Loaded);
    return iterator(this, -(int)Loaded.size());
  }

  iterator end() {
    return iterator(this, Local.size());
  }

  void push_back(const T& LocalValue) {
    Local.push_back(LocalValue);
  }

  void erase(iterator From, iterator To) {
    if (From.isLoaded() && To.isLoaded()) {
      Loaded.erase(&*From, &*To);
      return;
    }

    if (From.isLoaded()) {
      Loaded.erase(&*From, Loaded.end());
      From = begin(nullptr, true);
    }

    Local.erase(&*From, &*To);
  }
};

/// \brief A lazy pointer to a statement.
typedef LazyOffsetPtr<Stmt, uint64_t, &ExternalASTSource::GetExternalDeclStmt>
  LazyDeclStmtPtr;

/// \brief A lazy pointer to a declaration.
typedef LazyOffsetPtr<Decl, uint32_t, &ExternalASTSource::GetExternalDecl>
  LazyDeclPtr;

/// \brief A lazy pointer to a set of CXXCtorInitializers.
typedef LazyOffsetPtr<CXXCtorInitializer *, uint64_t,
                      &ExternalASTSource::GetExternalCXXCtorInitializers>
  LazyCXXCtorInitializersPtr;

/// \brief A lazy pointer to a set of CXXBaseSpecifiers.
typedef LazyOffsetPtr<CXXBaseSpecifier, uint64_t,
                      &ExternalASTSource::GetExternalCXXBaseSpecifiers>
  LazyCXXBaseSpecifiersPtr;

} // end namespace clang

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/btn_crop_pressed"/>
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/btn_crop_pressed"/>
    <item android:state_focused="true" android:drawable="@drawable/btn_crop_pressed"/>
    <item android:state_focused="false" android:state_pressed="false" android:drawable="@drawable/btn_crop_operator"/>
</selector>
<!-- From: file:/F:/Workspace/CommonSDK/Multidots/android/simplecropimagelib/src/main/res/drawable/selector_crop_button.xml -->


text:
import { Vehicle } from 'vehicle';

class Truck extends Vehicle {
    constructor(manufacturer, model, year, kilometers, price, fuel, transmission, horsepower, type, maxLoadCapacity, numberOfWheels) {
        super(manufacturer, model, year, kilometers, price, fuel, transmission, horsepower);

        this.type = type;
        this.maxLoadCapacity = maxLoadCapacity;
        this.numberOfWheels = numberOfWheels;
    }

    get type() {
        return this._type;
    }
    set type(value) {
        this._type = value;
    }

    get maxLoadCapacity() {
        return this._maxLoadCapacity;
    }
    set maxLoadCapacity(value) {
        this._maxLoadCapacity = value;
    }

    get numberOfWheels() {
        return this._numberOfWheels;
    }
    set numberOfWheels(value) {
        this._numberOfWheels = value;
    }
}

export { Truck };


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
	<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
	<link rel="stylesheet" type="text/css" href="../../../examples/resources/syntax/shCore.css">
	<link rel="stylesheet" type="text/css" href="../../../examples/resources/demo.css">

	<title>Select examples - Select for DataTables</title>

Select example Select for DataTables

Select adds item selection capabilities to a DataTable. Items can be rows, columns or cells, which can be selected independently, or together. Item selection
				can be particularly useful in interactive tables where users can perform some action on the table such as editing.

Initialisation

								Simple initialisation

								Single item selection

								Multi item selection

								Cell selection

								Checkbox selection

								Internationalisation

								Blur selection

								Defer rendering

								Buttons

								Retain selection on reload

Styling

								jQuery UI styling

								Bootstrap styling

								Foundation styling

API

								Select items

								Events

								Get selected items

Please refer to the DataTables documentation for full information about its API properties and methods.

					Additionally, there are a wide range of extensions and plug-ins which extend the capabilities of DataTables.

DataTables designed and created by SpryMedia Ltd © 2007-2016

					DataTables is licensed under the MIT license.


text:
module FileScraper

  class Filter
    ## Constants
    SEPERATOR  = '[-\._ ]'
    def SEPERATOR?
      "#{SEPERATOR}?"
    end

    def initialize( rss_data, path, search_path, block_path, options={})
      @rss_data      = rss_data
      @download_path = path
      @quiet         = options[:quiet] || false

      @search        = open_file_or_url( search_path )

      ## Validate source (non nill check)
      if @rss_data.nil?
        $stderr.puts "rss_data not supplied"
        exit -1
      end

    end

    def run
      matched_data = Array.new
      @rss_data.each do |item|
        name          = "#{item.title}" #This does not include file extension

        matched = @search.any? do |regexp|
          name.match(regexp)
        end
        if matched
          matched_data << item
        end

        ## Debugging info
        puts name
      end

      return matched_data
    end

    def open_file_or_url path
      require 'open-uri'
      if path.nil?
        return []
      end
      if path.match(/^http/)
        open( path, "rb").map{ |line| parse_regexp( line.strip ) }
      else
        ::File.open( path, "rb").map{ |line| parse_regexp( line.strip ) }
      end
    end

    def parse_regexp( a_string )
      arr     = a_string.split('/')
      if  arr == ''
        $stderr.puts "Blank Regular expression '#{a_string}'"
      end
      main    = arr[1]
      options = arr[2]

      main.gsub!('#{SEPERATOR}', '[-\._ ]')
      main.gsub!('#{SEPERATOR?}', '[-\._ ]?')

      Regexp.new(main, Regexp::IGNORECASE)
    end

  end
end


text:
Full-featured example of publishing platform built with
[React](http://facebook.github.io/react/),
[Redux](http://rackt.github.io/redux/),
[React Router](http://rackt.github.io/react-router/),
[Babel](https://babeljs.io/) and
[Webpack](http://webpack.github.io/).

Some features:
- Server-side rendering
- Token-based authorization with [JWT](https://www.npmjs.com/package/jsonwebtoken) (for paywall in the future, but not currently working)
- Modular CSS with [React CSS Modules](https://github.com/gajus/react-css-modules)
- API mock with [JSON server](https://www.npmjs.com/package/json-server)

## Running
```bash
npm install
```

### Production
```bash
make # build assets and server
npm start # start the server
```

Open [http://localhost:3000/](http://localhost:3000/) in the browser.

### Development
```bash
make dev # start development server with hot reloading
```

It will automatically open your default browser with project loaded.

### you can

- View list of posts
- View single post

## How it works

All data stored in API implemented with `jsonServer`. There're pre-populated `users` and `posts` entities. This implementation is example-only and you can easily drop-in your own backend solution. We aim just to show the direction.


text:
@protocol AddButtonPressedDelegate

- (void)didPressAddButton:(NSString *)addedBucketId;

@end

@interface AddBucketTableViewCell : UITableViewCell <LoadedUpdateResultDelegate> {

	UITextField *textField;

	id<AddButtonPressedDelegate> delegate;

}

- (void)buttonSelected:(id)sender;

@property(nonatomic,assign) id<AddButtonPressedDelegate> delegate;

@end


text:
#ifndef ImageLoader_h
#define ImageLoader_h

#include "core/loader/cache/ImageResource.h"
#include "core/loader/cache/ImageResourceClient.h"
#include "core/loader/cache/ResourcePtr.h"
#include "wtf/HashSet.h"
#include "wtf/text/AtomicString.h"

namespace WebCore {

class ImageLoaderClient {
public:
    virtual void notifyImageSourceChanged() = 0;

    // Determines whether the observed ImageResource should have higher priority in the decoded resources cache.
    virtual bool requestsHighLiveResourceCachePriority() { return false; }

protected:
    ImageLoaderClient() { }
};

class Element;
class ImageLoader;
class RenderImageResource;

template<typename T> class EventSender;
typedef EventSender<ImageLoader> ImageEventSender;

class ImageLoader : public ImageResourceClient {
public:
    explicit ImageLoader(Element*);
    virtual ~ImageLoader();

    // This function should be called when the element is attached to a document; starts
    // loading if a load hasn't already been started.
    void updateFromElement();

    // This function should be called whenever the 'src' attribute is set, even if its value
    // doesn't change; starts new load unconditionally (matches Firefox and Opera behavior).
    void updateFromElementIgnoringPreviousError();

    void elementDidMoveToNewDocument();

    Element* element() const { return m_element; }
    bool imageComplete() const { return m_imageComplete; }

    ImageResource* image() const { return m_image.get(); }
    void setImage(ImageResource*); // Cancels pending beforeload and load events, and doesn't dispatch new ones.

    void setLoadManually(bool loadManually) { m_loadManually = loadManually; }

    bool hasPendingBeforeLoadEvent() const { return m_hasPendingBeforeLoadEvent; }
    bool hasPendingActivity() const { return m_hasPendingLoadEvent || m_hasPendingErrorEvent; }

    void dispatchPendingEvent(ImageEventSender*);

    static void dispatchPendingBeforeLoadEvents();
    static void dispatchPendingLoadEvents();
    static void dispatchPendingErrorEvents();

    void addClient(ImageLoaderClient*);
    void removeClient(ImageLoaderClient*);

protected:
    virtual void notifyFinished(Resource*);

private:
    virtual void dispatchLoadEvent() = 0;
    virtual String sourceURI(const AtomicString&) const = 0;

    void updatedHasPendingEvent();

    void dispatchPendingBeforeLoadEvent();
    void dispatchPendingLoadEvent();
    void dispatchPendingErrorEvent();

    RenderImageResource* renderImageResource();
    void updateRenderer();

    void setImageWithoutConsideringPendingLoadEvent(ImageResource*);
    void sourceImageChanged();
    void clearFailedLoadURL();

    void timerFired(Timer<ImageLoader>*);

    Element* m_element;
    ResourcePtr<ImageResource> m_image;
    HashSet<ImageLoaderClient*> m_clients;
    Timer<ImageLoader> m_derefElementTimer;
    AtomicString m_failedLoadURL;
    bool m_hasPendingBeforeLoadEvent : 1;
    bool m_hasPendingLoadEvent : 1;
    bool m_hasPendingErrorEvent : 1;
    bool m_imageComplete : 1;
    bool m_loadManually : 1;
    bool m_elementIsProtected : 1;
    unsigned m_highPriorityClientCount;
};

}

#endif


text:
const ngtools = require('@ngtools/webpack');
const webpack = require('webpack');

// Añadido para saltarnos un error de webpack
const path=require('path');

module.exports = {
    devtool: 'source-map',
    entry: {
        main: './src/main-aot.ts'
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    target: 'node',
    output: {
        //  No funciona
        // path: 'src/dist',
        path: path.resolve(__dirname, 'src/dist'),
        filename: 'build.js'
    },
    plugins: [
        new ngtools.AotPlugin({
            tsConfigPath: './tsconfig-aot.json'
        }),
        new webpack.optimize.UglifyJsPlugin({ sourceMap: true })
    ],
    module: {
        rules: [
            { test: /\.css$/, loader: 'raw-loader' },
            { test: /\.html$/, loader: 'raw-loader' },
            { test: /\.ts$/, loader: '@ngtools/webpack' }
        ]
    }
}


text:
<?php

namespace App\App\Stages\Notify;

use App\Campaign\Domain\Classes\CommandKey;
use App\Campaign\Notifications\CommanderSendToGroup;
use App\Campaign\Domain\Repositories\GroupRepository;

class NotifyGroupStage extends NotifyContextStage
{
    protected $repository = GroupRepository::class;

    protected $notifications = [
        CommandKey::SEND => CommanderSendToGroup::class,
    ];

    protected function getRepository()
    {
        return $this->repository;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cortinarius multicolor M.M. Moser ex M.M. Moser

### Remarks
null