Exemple #1
0
/*
 * This writes out a char * string with attributes.
 */
void writeCharAttrib (WINDOW *window,
		      int xpos,
		      int ypos,
		      char *string,
		      chtype attr,
		      int align,
		      int start,
		      int end)
{
   int display = end - start;
   int x;

   if (align == HORIZONTAL)
   {
      /* Draw the message on a horizontal axis. */
      display = MINIMUM (display, getmaxx (window) - 1);
      for (x = 0; x < display; x++)
      {
	 mvwaddch (window, ypos, xpos + x, CharOf (string[x + start]) | attr);
      }
   }
   else
   {
      /* Draw the message on a vertical axis. */
      display = MINIMUM (display, getmaxy (window) - 1);
      for (x = 0; x < display; x++)
      {
	 mvwaddch (window, ypos + x, xpos, CharOf (string[x + start]) | attr);
      }
   }
}
Exemple #2
0
void main()
{
  int a=10,b=20;

  #ifdef MAX
  printf ("the larger one is %d\n",MAXIMUM(a,b));
  #else
  printf ("the lower one is %d\n",MINIMUM(a,b));
  #endif

  #ifndef MIN
  printf ("the lower one is %d\n",MINIMUM(a,b));
  #else
  printf ("the larger one is %d\n",MAXIMUM(a,b));
  #endif

  #undef MAX
  #ifdef MAX
  printf ("the larger one is %d\n",MAXIMUM(a,b));
  #else
  printf ("the lower one is %d\n",MINIMUM(a,b));
  #endif

  #ifndef MIN
  printf ("the lower one is %d\n",MINIMUM(a,b));
  #else
  printf ("the larger one is %d\n",MAXIMUM(a,b));
  #endif
}
Exemple #3
0
/*
 * Copy and nul-terminate a ringbuffer to a string.
 */
ssize_t
ringbuf_to_string(char *buf, size_t len, struct ringbuf *rb)
{
	size_t copy_len, n;

	if (buf == NULL || rb == NULL || len == 0)
		return (-1);

	copy_len = MINIMUM(len - 1, ringbuf_used(rb));

	if (copy_len == 0)
		return (copy_len);

	if (rb->start < rb->end)
		memcpy(buf, rb->buf + rb->start, copy_len);
	else {
		/* If the buffer is wrapped, copy each hunk separately */
		n = rb->len - rb->start;
		memcpy(buf, rb->buf + rb->start, MINIMUM(n, copy_len));
		if (copy_len > n)
			memcpy(buf + n, rb->buf,
			    MINIMUM(rb->end, copy_len - n));
	}
	buf[copy_len] = '\0';

	return (ringbuf_used(rb));
}
Exemple #4
0
/*
 * This writes out a chtype * string * with the given attributes added.
 */
void writeChtypeAttrib (WINDOW *window,
			int xpos,
			int ypos,
			chtype *string,
			chtype attr,
			int align,
			int start,
			int end)
{
   /* *INDENT-EQLS* */
   int diff             = end - start;
   int display          = 0;
   int x                = 0;

   if (align == HORIZONTAL)
   {
      /* Draw the message on a horizontal axis. */
      display = MINIMUM (diff, getmaxx (window) - xpos);
      for (x = 0; x < display; x++)
      {
	 mvwaddch (window, ypos, xpos + x, string[x + start] | attr);
      }
   }
   else
   {
      /* Draw the message on a vertical axis. */
      display = MINIMUM (diff, getmaxy (window) - ypos);
      for (x = 0; x < display; x++)
      {
	 mvwaddch (window, ypos + x, xpos, string[x + start] | attr);
      }
   }
}
Exemple #5
0
static void
do_geometry(const char *name, const char *spec)
{
	double re_1, im_1;
	double re_2, im_2;
	char comma;
	char sg_1;
	char sg_2;
	char ii_1;
	char ii_2;
	char ch;

#define PLUS_OR_MINUS(c)  ((c) == '+' || (c) == '-')
#define IMAGINARY_UNIT(x) ((x) == 'i' || (x) == 'j')

	if (sscanf(spec, 
	           "%lf %c %lf %c %c %lf %c %lf %c %c", 
	           &re_1,
	           &sg_1,
	           &im_1,
	           &ii_1,
	           &comma,
	           &re_2,
	           &sg_2,
	           &im_2,
	           &ii_2,
	           &ch) != 9
	    || !PLUS_OR_MINUS(sg_1)
	    || !PLUS_OR_MINUS(sg_2)
	    || !IMAGINARY_UNIT(ii_1)
	    || !IMAGINARY_UNIT(ii_2)
	    || comma != ',') {
		fprintf(stderr, "invalid geometry specification.\n");
		exit(1);
	}

#define MINIMUM(x, y) ((x) <= (y) ? (x) : (y))
#define MAXIMUM(x, y) ((x) >= (y) ? (x) : (y))
#define SIGN(c) ((c) == '-' ? -1.0 : +1.0)

	/* Sign-adjust. */
	im_1 *= SIGN(sg_1);
	im_2 *= SIGN(sg_2);

	/*
	 * We have two edges of the rectangle. Now, find the upper-left 
	 * (i.e. the one with minimum real part and maximum imaginary
	 * part) and lower-right (maximum real part, minimum imaginary)
	 * corners of the rectangle.
	 */
	upper_left_re = MINIMUM(re_1, re_2);
	upper_left_im = MAXIMUM(im_1, im_2);
	lower_right_re = MAXIMUM(re_1, re_2);
	lower_right_im = MINIMUM(im_1, im_2);
}
Exemple #6
0
dropout_result digibeta_dropout(YUV_frame* in_frame, int xOffset, int yOffset,
                                int* workSpace)
{
    int     h, w, y;
    BYTE*   inLine;
    int*    outLine;
    int*    work[2];

    work[0] = workSpace;
    work[1] = work[0] + (WIDTH * HEIGHT / 2);
    // high pass filter input to workspace
    memset(work[0], 0, sizeof(int) * WIDTH * HEIGHT / 2);
    inLine = in_frame->Y.buff;
    outLine = work[0];
    if (xOffset >= 0)
    {
        inLine += xOffset * in_frame->Y.pixelStride;
        w = MINIMUM(in_frame->Y.w - xOffset, WIDTH);
    }
    else
    {
        outLine -= xOffset;
        w = MINIMUM(in_frame->Y.w, WIDTH + xOffset);
    }
    if (yOffset >= 0)
    {
        inLine += yOffset * in_frame->Y.lineStride;
        h = MINIMUM(in_frame->Y.h - yOffset, HEIGHT);
    }
    else
    {
        h = in_frame->Y.h;
        if ((yOffset % 2) != 0)
        {
            inLine += in_frame->Y.lineStride;
            yOffset -= 1;
            h -= 1;
        }
        outLine -= (yOffset / 2) * WIDTH;
        h = MINIMUM(h, HEIGHT + yOffset);
    }
    for (y = 0; y < (h + 1) / 2; y++)
    {
        hpf_line(inLine, outLine, in_frame->Y.pixelStride, w);
        inLine += 2 * in_frame->Y.lineStride;
        outLine += WIDTH;
    }
    // block average high pass filtered input
    block_average(work[0], work[1]);
    // high pass filter it to isolate dropout spikes
    spatial_hpf(work[1], work[0]);
    // process data in workspace to find dropouts
    return detect_dropout(work[0]);
}
Exemple #7
0
static int
input_kex_dh_gex_request(int type, u_int32_t seq, struct ssh *ssh)
{
	struct kex *kex = ssh->kex;
	int r;
	u_int min = 0, max = 0, nbits = 0;

	debug("SSH2_MSG_KEX_DH_GEX_REQUEST received");
	if ((r = sshpkt_get_u32(ssh, &min)) != 0 ||
	    (r = sshpkt_get_u32(ssh, &nbits)) != 0 ||
	    (r = sshpkt_get_u32(ssh, &max)) != 0 ||
	    (r = sshpkt_get_end(ssh)) != 0)
		goto out;
	kex->nbits = nbits;
	kex->min = min;
	kex->max = max;
	min = MAXIMUM(DH_GRP_MIN, min);
	max = MINIMUM(DH_GRP_MAX, max);
	nbits = MAXIMUM(DH_GRP_MIN, nbits);
	nbits = MINIMUM(DH_GRP_MAX, nbits);

	if (kex->max < kex->min || kex->nbits < kex->min ||
	    kex->max < kex->nbits || kex->max < DH_GRP_MIN) {
		r = SSH_ERR_DH_GEX_OUT_OF_RANGE;
		goto out;
	}

	/* Contact privileged parent */
	kex->dh = PRIVSEP(choose_dh(min, nbits, max));
	if (kex->dh == NULL) {
		sshpkt_disconnect(ssh, "no matching DH grp found");
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	debug("SSH2_MSG_KEX_DH_GEX_GROUP sent");
	if ((r = sshpkt_start(ssh, SSH2_MSG_KEX_DH_GEX_GROUP)) != 0 ||
	    (r = sshpkt_put_bignum2(ssh, kex->dh->p)) != 0 ||
	    (r = sshpkt_put_bignum2(ssh, kex->dh->g)) != 0 ||
	    (r = sshpkt_send(ssh)) != 0)
		goto out;

	/* Compute our exchange value in parallel with the client */
	if ((r = dh_gen_key(kex->dh, kex->we_need * 8)) != 0)
		goto out;

	debug("expecting SSH2_MSG_KEX_DH_GEX_INIT");
	ssh_dispatch_set(ssh, SSH2_MSG_KEX_DH_GEX_INIT, &input_kex_dh_gex_init);
	r = 0;
 out:
	return r;
}
Exemple #8
0
struct TREE_NODE* MINIMUM(struct TREE_NODE *N)
{
	if(N == NULL) return NULL;
	if(N->L == NULL && N->R == NULL) return N;
	int min = N->K;
	struct TREE_NODE *X = MINIMUM(N->L);
	struct TREE_NODE *Y = MINIMUM(N->R);
	if(X != NULL)
	{
		if(X->K < min) return X;
	}
	if(Y != NULL)
	{
		if(Y->K < min) return Y;
	}
}
const TreeNode<T>* BST<T>::predecessor (const T &v) const {
  const TreeNode<T> *n = search (v);
  if (n == NULL) 
   throw std::runtime_error ("the searched value does not exsit in the tree");

  //if the node has a left child, it's the predecessor
  if (n->left != NULL) 
    return n->left->v;

  //else find the ancestor such that the node is on the ancestor's RHS, find the minimum value rooted at the ancestor
  else {
    const TreeNode<T> *c = n;	//current node
    const TreeNode<T> *p = n->p;	//the parent of n
    while ((p!=NULL) && (p->right!=c)) {
      c = p;
      p = p->p;
    }

    if (p == NULL) {
      throw std::runtime_error ("the value is the minimum in the tree, node predecessor");
    }
    else {
      return MINIMUM(p);
    }
  }
}
void BST<T>::remove (const T &v) throw (std::runtime_error) {
  //find the node with the value 
  TreeNode<T> *n = search (v);
  if (n == NULL) {
    throw std::runtime_error("the deleted value does not exist in the BST");
  }
  //if both left and right are NULL, just delete n
  if ((n->left==NULL) && (n->right==NULL)) {
    if (n->p == NULL) {
      delete root;
      root = NULL;
    }
    else {
      if (n == n->p->left)
        n->p->left = NULL;
      else 
        n->p->right = NULL;
      delete n;
      n = NULL;
    }
  }
  //if n->right == NULL, lift n->left
  else {
    if (n->right == NULL) 
      TRANSPOSE (n, n->right);
  
    //else lift the minimum node on the right
    else {
      TreeNode<T> *r = MINIMUM(n->right);
      ////std::cout << "r: " << r->v << std::endl;
      TRANSPOSE (n, r);
    }
  }
}
Exemple #11
0
int
kexgex_client(struct ssh *ssh)
{
	struct kex *kex = ssh->kex;
	int r;
	u_int nbits;

	nbits = dh_estimate(kex->dh_need * 8);

	kex->min = DH_GRP_MIN;
	kex->max = DH_GRP_MAX;
	kex->nbits = nbits;
	if (datafellows & SSH_BUG_DHGEX_LARGE)
		kex->nbits = MINIMUM(kex->nbits, 4096);
	/* New GEX request */
	if ((r = sshpkt_start(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST)) != 0 ||
	    (r = sshpkt_put_u32(ssh, kex->min)) != 0 ||
	    (r = sshpkt_put_u32(ssh, kex->nbits)) != 0 ||
	    (r = sshpkt_put_u32(ssh, kex->max)) != 0 ||
	    (r = sshpkt_send(ssh)) != 0)
		goto out;
	debug("SSH2_MSG_KEX_DH_GEX_REQUEST(%u<%u<%u) sent",
	    kex->min, kex->nbits, kex->max);
#ifdef DEBUG_KEXDH
	fprintf(stderr, "\nmin = %d, nbits = %d, max = %d\n",
	    kex->min, kex->nbits, kex->max);
#endif
	ssh_dispatch_set(ssh, SSH2_MSG_KEX_DH_GEX_GROUP,
	    &input_kex_dh_gex_group);
	r = 0;
 out:
	return r;
}
Exemple #12
0
static libcouchbase_ssize_t
read_common(lcb_luv_socket_t sock, void *buffer, libcouchbase_size_t len,
            int *errno_out)
{
    struct lcb_luv_evstate_st *evstate = sock->evstate + LCB_LUV_EV_READ;
    libcouchbase_ssize_t ret;
    size_t read_offset, toRead;

    log_read_debug("%d: Requested to read %d bytes. have %d",
                sock->idx, len, sock->read.nb);


    /* basic error checking */
    if (evstate->err) {
        *errno_out = evstate->err;
        evstate->err = 0;
        return -1;
    }

    if (sock->eof) {
        return 0;
    }

    /* Check how much data we can send back, and where do we read from */
    toRead = MINIMUM(len, sock->read.nb);
    read_offset = sock->read.pos;

    /* copy the data */
    if (toRead) {
        memcpy(buffer, sock->read.data + read_offset, toRead);
        ret = toRead;
        *errno_out = 0;
    } else {
        *errno_out = EWOULDBLOCK;
        ret = -1;
    }

    /**
     * Buffer positioning is somewhat complicated. If we are in middle of a partial
     * read (readahead is active), then the next bytes will still happen from within
     * the position of our current buffer, so we want to maintain our position.
     *
     * On the other hand, if readahead is not active, then the next read will begin
     * from the beginning of the buffer
     */
    sock->read.nb -= toRead;
    sock->read.pos += toRead;

    if (sock->read.nb == 0 && sock->read.readhead_active == 0) {
        sock->read.pos = 0;
    }


    if (toRead < len) {
        evstate->flags &= ~(LCB_LUV_EVf_PENDING);
        lcb_luv_read_nudge(sock);
    }

    return ret;
}
void ViewBase::set_viewport_dims(ushort2 dims, float scale) {
	view.dims.x = (unsigned short) (dims.x * scale);
	view.dims.y = (unsigned short) (dims.y * scale);
	pixel_ratio_rotation = 180.0f / (MINIMUM(dims.x, dims.y));	
	pixel_ratio_translation = (distance_limits.y - distance_limits.x) / (dims.y / 2);
	update_view();
}
static fpos_t
wmemstream_seek(void *v, fpos_t off, int whence)
{
	struct state	*st = v;
	ssize_t		 base = 0;

	switch (whence) {
	case SEEK_SET:
		break;
	case SEEK_CUR:
		base = st->pos;
		break;
	case SEEK_END:
		base = st->len;
		break;
	}

	if (off > (SIZE_MAX / sizeof(wchar_t)) - base || off < -base) {
		errno = EOVERFLOW;
		return (-1);
	}

	/*
	 * XXX Clearing mbs here invalidates shift state for state-
	 * dependent encodings, but they are not (yet) supported.
	 */
	bzero(&st->mbs, sizeof(st->mbs));

	st->pos = base + off;
	*st->psize = MINIMUM(st->pos, st->len);

	return (st->pos);
}
Exemple #15
0
/*
 * This draws the widget.
 */
static void drawCDKDScaleField (CDKDSCALE *widget)
{
   char temp[256];

   werase (widget->fieldWin);

   /* Draw the value in the field. */
   {
      char format[256];
      int digits = MINIMUM(widget->digits, 30);
      sprintf (format, "%%.%if", digits);
      sprintf (temp, format, widget->current);
   }
   writeCharAttrib (widget->fieldWin,
		    widget->fieldWidth - (int)strlen(temp) - 1,
		    0,
		    temp,
		    widget->fieldAttr,
		    HORIZONTAL,
		    0,
		    (int)strlen(temp));

   moveToEditPosition(widget, widget->fieldEdit);
   wrefresh (widget->fieldWin);
}
void ViewBase::update_view() {										//biggest cube edge is 2 and center == [0,0,0]
    view.origin = vector_rotate(cam_pos, cam_matrix);
	view.direction = vector_normalize(-view.origin);	
	float step_px = virtual_view_size / MINIMUM(view.dims.x, view.dims.y);
	view.right_plane = vector_rotate(make_float4(1, 0, 0, 0), cam_matrix) * step_px;
    view.up_plane = vector_rotate(make_float4(0, 1, 0, 0), cam_matrix) * step_px;
}
Exemple #17
0
static int formattedSize (CDKFSLIDER *widget, float value)
{
   char temp[256];
   char format[256];
   int digits = MINIMUM(widget->digits, 30);
   sprintf (format, "%%.%if", digits);
   sprintf (temp, format, value);
   return strlen (temp);
}
Exemple #18
0
static struct passwd *
_pwhashbyname(const char *name, char *buf, size_t buflen, struct passwd *pw,
    int *flagsp)
{
	char bf[1 + _PW_NAME_LEN];
	size_t len;
	DBT key;
	int r;

	len = strlen(name);
	if (len > _PW_NAME_LEN)
		return (NULL);
	bf[0] = _PW_KEYBYNAME;
	bcopy(name, &bf[1], MINIMUM(len, _PW_NAME_LEN));
	key.data = (u_char *)bf;
	key.size = 1 + MINIMUM(len, _PW_NAME_LEN);
	r = __hashpw(&key, buf, buflen, pw, flagsp);
	if (r)
		return (pw);
	return (NULL);
}
Exemple #19
0
  void SkillSet::trajectory2D(const Vector2D<int>&   startPos,
                              const Vector2D<int>&   finalPos,
                              const Vector2D<float>& startVel,
                              const Vector2D<float>& finalVel,
                              const float            startAng,
                              const float            finalAng,
                              const float            startAngVel,
                              const float            finalAngVel,
                              const float            frameRate,
                              const float            maxAcc,
                              const float            maxVel,
                              const float            maxAngAcc,
                              const float            maxAngVel,
                              Vector2D<float>&       trajVel,
                              float&                 angVel)
  {
    Vector2D<float> acc;
    float timeX, timeY;
    Vector2D<int> delta = finalPos - startPos;

    float u = PI / 2;
    float du = -PI / 2;
    // Performing binary search for the optimum value of alpha which will result in
    for (int i = 0; i < 10; ++i)
    {
      float alpha = u + (du /= 2);
      Vector2D<float> aTransMax, vTransMax;
      aTransMax.fromPolar(maxAcc, alpha);
      vTransMax.fromPolar(maxVel, alpha);

      trajectory1D(delta.x, startVel.x, finalVel.x, frameRate, aTransMax.x, vTransMax.x, acc.x, timeX);
      trajectory1D(delta.y, startVel.y, finalVel.y, frameRate, aTransMax.y, vTransMax.y, acc.y, timeY);

      if (timeX <= timeY)
        u = alpha;
    }

    float trajTime = MAXIMUM(timeX, timeY);
    float deltaAng = MINIMUM(finalAng - startAng, 0); // forcing deltaAng to lie in (-pi, pi]

    float angAcc = 0 , timeAng = INFINITY;
    for (float factor = 0.1f; factor <= 1.05f; factor += 0.1f)   // using 1.05f instead of 1.0f to account for errors due to floating point precision
    {
      trajectory1D(deltaAng, startAngVel, finalAngVel, frameRate, maxAngAcc * factor, maxAngVel, angAcc, timeAng);
      if (timeAng < trajTime)
        break;
    }

    trajVel.x = startVel.x + acc.x / frameRate;
    trajVel.y = startVel.y + acc.y / frameRate;
    angVel = startAngVel + angAcc / frameRate;
  } // trajectory2D
int effective_utilization(struct TASK_SET t,int task)	//get effective utilization given by f formula in slides
{							
int i;
int Hn=0;
int H1=0;
int N;
float Hn_sum=0.0;
float H1_sum=0.0;
float utilization=0.0;
	
		for(i=0;i<task;i++)
		{	
			if(t.task[i].period<=t.task[task].deadline)
			{
			Hn_sum+=(t.task[i].WCET/(MINIMUM(t.task[i].deadline,t.task[i].period)));
			Hn++;
			}
			else
			H1_sum+=t.task[i].WCET;
		}

	N=Hn+1;	//U(n)=num(Hn)+1

	utilization=Hn_sum+(t.task[task].WCET/(MINIMUM(t.task[task].deadline,t.task[task].period)))+(H1_sum/(MINIMUM(t.task[task].deadline,t.task[task].period)));

float root=1.0/N;
float utilization_bound=N*(pow(2.0,root)-1);	//the sufficient condition for the utilization

//	printf("\nFor task %d\n",task);	
//	printf("N=%d\n",N);
//	printf("Utilization=%f\n",utilization);
//	printf("Utilization bound=%f\n",utilization_bound);

		if(utilization>utilization_bound)	//We fail the sufficient condition
		return -FAILURE;

return SUCCESS;
		
}
Exemple #21
0
static void
pap_response(pap *_this, int authok, const char *mes)
{
	int lpktp, lmes;
	u_char *pktp, *pktp1;
	const char *realm;

	pktp = ppp_packetbuf(_this->ppp, PPP_PROTO_PAP) + HEADERLEN;
	lpktp = _this->ppp->mru - HEADERLEN;
	realm = npppd_ppp_get_realm_name(_this->ppp->pppd, _this->ppp);

	pktp1 = pktp;
	if (mes == NULL)
		lmes = 0;
	else
		lmes = strlen(mes);
	lmes = MINIMUM(lmes, lpktp - 1);

	PUTCHAR(lmes, pktp1);
	if (lmes > 0)
		memcpy(pktp1, mes, lmes);
	lpktp = lmes + 1;

	if (authok)
		ppp_output(_this->ppp, PPP_PROTO_PAP, AUTHACK, _this->auth_id,
		    pktp, lpktp);
	else
		ppp_output(_this->ppp, PPP_PROTO_PAP, AUTHNAK, _this->auth_id,
		    pktp, lpktp);

	if (!authok) {
		pap_log(_this, LOG_ALERT,
		    "logtype=Failure username=\"%s\" realm=%s", _this->name,
		    realm);
		pap_stop(_this);
		ppp_set_disconnect_cause(_this->ppp, 
		    PPP_DISCON_AUTH_FAILED, PPP_PROTO_PAP, 1 /* peer */, NULL);
		ppp_stop(_this->ppp, "Authentication Required");
	} else {
		strlcpy(_this->ppp->username, _this->name,
		    sizeof(_this->ppp->username));
		pap_log(_this, LOG_INFO,
		    "logtype=Success username=\"%s\" realm=%s", _this->name,
		    realm);
		pap_stop(_this);
		ppp_auth_ok(_this->ppp);
		/* reset the state to response request of retransmision. */
		_this->state = PAP_STATE_SENT_RESPONSE;
	}
}
Exemple #22
0
void print_if_necessary(INT k)
{
	if ((dlx_nb_backtrack_nodes & ((1 << 21) - 1)) == 0) {
		INT a;

		a = dlx_nb_backtrack_nodes >> 21;
		cout << "DlxSearch: " << a << " * 2^21 nodes, " << " nb_sol=" << dlx_nb_sol << " position ";
		for (int i = 0; i < MINIMUM(DLX_TRACKING_DEPTH, k); i++) {
			cout << Cur_choice[i] << " / " << Nb_choices[i];
			if (i < DLX_TRACKING_DEPTH - 1) {
				cout << ", ";
				}
			}
		cout << endl;
		}
Exemple #23
0
int rbs_seek(rbstream_p rbsp, ssize_t offset, int whence)
{
	medvdbg("[%s] offset %ld, whence %d\n", __FUNCTION__, offset, whence);
	RETURN_VAL_IF_FAIL(rbsp != NULL, ERROR);

	switch (whence) {
	case SEEK_SET:
		// checking underflow
		RETURN_VAL_IF_FAIL(((size_t) offset >= rbsp->rd_size), ERROR);

		while ((size_t) offset > rbsp->wr_size) {
			size_t least = (size_t) offset - rbsp->wr_size;
			size_t wlen;

			// pull stream data, then wr_size will be increased
			wlen = _pull(rb_avail(rbsp->rbp), least, rbsp);

			if ((size_t) offset > rbsp->wr_size) {
				// not enough
				if (rb_avail(rbsp->rbp) == SIZE_ZERO) {
					// ring-buffer is full
					RETURN_VAL_IF_FAIL((RBS_OPTION_TEST(rbsp, OPTION_ALLOW_TO_DEQUEUE)), ERROR); // overflow

					// dequeue minimal data from ring-buffer
					size_t len = rbsp->wr_size - rbsp->rd_size;
					least = (size_t) offset - rbsp->wr_size;
					len = MINIMUM(len, least);
					size_t rlen = rb_read(rbsp->rbp, NULL, len);
					assert(rlen == len);
					rbsp->rd_size += rlen;
				} else {
					RETURN_VAL_IF_FAIL((wlen != SIZE_ZERO), ERROR);    // EOS
				}

				// request more data
				continue;
			}
			// got enough data
			break;
		}

		rbsp->cur_pos = (size_t) offset;
		break;
	}

	return OK;
}
Exemple #24
0
size_t rbs_read(void *ptr, size_t size, size_t nmemb, rbstream_p rbsp)
{
	medvdbg("[%s] ptr %p nmemb %lu\n", __FUNCTION__, ptr, nmemb);
	RETURN_VAL_IF_FAIL(ptr != NULL, SIZE_ZERO);
	RETURN_VAL_IF_FAIL(rbsp != NULL, SIZE_ZERO);

	// only size:1 supported
	assert(size == 1);

	size_t len = size * nmemb;
	size_t read = SIZE_ZERO;

	while (read < len) {
		void *_ptr = (void *) ((uint8_t *) ptr + read);
		size_t need = len - read;
		size_t offset = rbsp->cur_pos - rbsp->rd_size;
		// read data desired
		size_t rlen = rb_read_ext(rbsp->rbp, _ptr, need, offset);
		read += rlen;
		rbsp->cur_pos += rlen; // increase cur_pos

		if (read < len) {
			// need to read more data
			size_t least = len - read;
			size_t avail = rb_avail(rbsp->rbp);
			if (least > avail) {
				// need to dequeue data
				if (RBS_OPTION_TEST(rbsp, OPTION_ALLOW_TO_DEQUEUE)) {
					offset = rbsp->cur_pos - rbsp->rd_size;
					size_t _len = MINIMUM(offset, (least - avail));
					size_t _rlen = rb_read(rbsp->rbp, NULL, _len);
					assert(_rlen == _len);
					rbsp->rd_size += _rlen;
				}
			}

			// pull stream data, then it's available to read more.
			if (_pull(rb_avail(rbsp->rbp), least, rbsp) == SIZE_ZERO) {
				// pull data failed
				break;
			}
		}
	}

	medvdbg("[%s] done, read %lu\n", __FUNCTION__, read);
	return read;
}
Exemple #25
0
/*
 * __OVFL_GET -- Get an overflow key/data item.
 *
 * Parameters:
 *	t:	tree
 *	p:	pointer to { pgno_t, u_int32_t }
 *	buf:	storage address
 *	bufsz:	storage size
 *
 * Returns:
 *	RET_ERROR, RET_SUCCESS
 */
int
__ovfl_get(BTREE *t, void *p, size_t *ssz, void **buf, size_t *bufsz)
{
	PAGE *h;
	pgno_t pg;
	size_t nb, plen;
	u_int32_t sz;
	void *tp;

	memmove(&pg, p, sizeof(pgno_t));
	memmove(&sz, (char *)p + sizeof(pgno_t), sizeof(u_int32_t));
	*ssz = sz;

#ifdef DEBUG
	if (pg == P_INVALID || sz == 0)
		abort();
#endif
	/* Make the buffer bigger as necessary. */
	if (*bufsz < sz) {
		tp = realloc(*buf, sz);
		if (tp == NULL)
			return (RET_ERROR);
		*buf = tp;
		*bufsz = sz;
	}

	/*
	 * Step through the linked list of pages, copying the data on each one
	 * into the buffer.  Never copy more than the data's length.
	 */
	plen = t->bt_psize - BTDATAOFF;
	for (p = *buf;; p = (char *)p + nb, pg = h->nextpg) {
		if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
			return (RET_ERROR);

		nb = MINIMUM(sz, plen);
		memmove(p, (char *)h + BTDATAOFF, nb);
		mpool_put(t->bt_mp, h, 0);

		if ((sz -= nb) == 0)
			break;
	}
	return (RET_SUCCESS);
}
Exemple #26
0
/*
 * __OVFL_PUT -- Store an overflow key/data item.
 *
 * Parameters:
 *	t:	tree
 *	data:	DBT to store
 *	pgno:	storage page number
 *
 * Returns:
 *	RET_ERROR, RET_SUCCESS
 */
int
__ovfl_put(BTREE *t, const DBT *dbt, pgno_t *pg)
{
	PAGE *h, *last;
	void *p;
	pgno_t npg;
	size_t nb, plen;
	u_int32_t sz;

	/*
	 * Allocate pages and copy the key/data record into them.  Store the
	 * number of the first page in the chain.
	 */
	plen = t->bt_psize - BTDATAOFF;
	for (last = NULL, p = dbt->data, sz = dbt->size;;
	    p = (char *)p + plen, last = h) {
		if ((h = __bt_new(t, &npg)) == NULL)
			return (RET_ERROR);

		h->pgno = npg;
		h->nextpg = h->prevpg = P_INVALID;
		h->flags = P_OVERFLOW;
		h->lower = h->upper = 0;

		nb = MINIMUM(sz, plen);
		memmove((char *)h + BTDATAOFF, p, nb);

		if (last) {
			last->nextpg = h->pgno;
			mpool_put(t->bt_mp, last, MPOOL_DIRTY);
		} else
			*pg = h->pgno;

		if ((sz -= nb) == 0) {
			mpool_put(t->bt_mp, h, MPOOL_DIRTY);
			break;
		}
	}
	return (RET_SUCCESS);
}
Exemple #27
0
char *
HASHFileChunk(const char *filename, char *buf, off_t off, off_t len)
{
	struct stat sb;
	u_char buffer[BUFSIZ];
	HASH_CTX ctx;
	int fd, save_errno;
	ssize_t nr;

	HASHInit(&ctx);

	if ((fd = open(filename, O_RDONLY)) < 0)
		return (NULL);
	if (len == 0) {
		if (fstat(fd, &sb) == -1) {
			save_errno = errno;
			close(fd);
			errno = save_errno;
			return (NULL);
		}
		len = sb.st_size;
	}
	if (off > 0 && lseek(fd, off, SEEK_SET) < 0) {
		save_errno = errno;
		close(fd);
		errno = save_errno;
		return (NULL);
	}

	while ((nr = read(fd, buffer, MINIMUM(sizeof(buffer), len))) > 0) {
		HASHUpdate(&ctx, buffer, nr);
		if (len > 0 && (len -= nr) == 0)
			break;
	}

	save_errno = errno;
	close(fd);
	errno = save_errno;
	return (nr < 0 ? NULL : HASHEnd(&ctx, buf));
}
Exemple #28
0
static lcb_ssize_t write_common(lcb_luv_socket_t sock,
                                const void *buf,
                                size_t len,
                                int *errno_out)
{
    lcb_ssize_t ret;
    struct lcb_luv_evstate_st *evstate = EVSTATE_FIND(sock, WRITE);

    log_write_debug("%d: Requested to write %d bytes from %p",
                    sock->idx, len, buf);

    if (evstate->err) {
        log_write_warn("Socket has pending error %d", evstate->err);
        *errno_out = evstate->err;
        evstate->err = 0;
        return -1;
    }

    if (EVSTATE_IS(evstate, FLUSHING)) {
        log_write_info("Will not write because we are inside a flush");
        *errno_out = EWOULDBLOCK;
        return -1;
    }

    ret = MINIMUM(len, sizeof(sock->write.data) - sock->write.nb);
    if (ret == 0) {
        log_write_info("We have no more space inside the buffer");
        *errno_out = EWOULDBLOCK;
        return -1;
    }



    memcpy(sock->write.data + sock->write.pos, buf, ret);
    //    lcb_luv_hexdump(sock->write.data + sock->write.pos, ret);
    sock->write.pos += ret;
    sock->write.nb += ret;
    log_write_trace("Returning %d", ret);
    return ret;
}
Exemple #29
0
int
buffer_add_range(int fd, struct evbuffer *evb, struct range *range)
{
    char	buf[BUFSIZ];
    size_t	n, range_sz;
    ssize_t	nread;

    if (lseek(fd, range->start, SEEK_SET) == -1)
        return (0);

    range_sz = range->end - range->start + 1;
    while (range_sz) {
        n = MINIMUM(range_sz, sizeof(buf));
        if ((nread = read(fd, buf, n)) == -1)
            return (0);

        evbuffer_add(evb, buf, nread);
        range_sz -= nread;
    }

    return (1);
}
Exemple #30
0
int
dh_gen_key(DH *dh, int need)
{
	int pbits;

	if (need < 0 || dh->p == NULL ||
	    (pbits = BN_num_bits(dh->p)) <= 0 ||
	    need > INT_MAX / 2 || 2 * need > pbits)
		return SSH_ERR_INVALID_ARGUMENT;
	if (need < 256)
		need = 256;
	/*
	 * Pollard Rho, Big step/Little Step attacks are O(sqrt(n)),
	 * so double requested need here.
	 */
	dh->length = MINIMUM(need * 2, pbits - 1);
	if (DH_generate_key(dh) == 0 ||
	    !dh_pub_is_valid(dh, dh->pub_key)) {
		BN_clear_free(dh->priv_key);
		return SSH_ERR_LIBCRYPTO_ERROR;
	}
	return 0;
}