/*
 * call-seq:
 *   PGConn.escape_bytea( obj )
 *
 * Escapes binary data for use within an SQL command with the type +bytea+.
 * 
 * Certain byte values must be escaped (but all byte values may be escaped)
 * when used as part of a +bytea+ literal in an SQL statement. In general, to
 * escape a byte, it is converted into the three digit octal number equal to
 * the octet value, and preceded by two backslashes. The single quote (') and
 * backslash (\) characters have special alternative escape sequences.
 * #escape_bytea performs this operation, escaping only the minimally required bytes.
 * 
 * For more information, see
 * PQescapeBytea[http://www.postgresql.org/docs/7.4/static/libpq-exec.html#LIBPQ-EXEC-ESCAPE-BYTEA]
 * which is called internally by this method.
 */
 
static VALUE
pgconn_s_escape_bytea(self, obj)
  VALUE self;
  VALUE obj;
{
  unsigned char c;
  char *from, *to;
  long idx;
  size_t from_len, to_len;
  VALUE ret;
  
  Check_Type(obj, T_STRING);
  from    = RSTRING(obj)->ptr;
  from_len  = RSTRING(obj)->len;
  
  to = (char *)PQescapeBytea(from, from_len, &to_len);
  
  ret = rb_str_new(to, to_len - 1);
  OBJ_INFECT(ret, obj);
  
  free(to);
  
  return ret;
}