Plan 9 from Bell Labs’s /usr/web/sources/contrib/de0u/root/sys/src/cmd/divergefs/string.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include "common.h"
#include "string.h"

enum { STRING_HASH_MULTIPLIER = 31 };

static char string_escaped_character(char ch)
{
  switch(ch)
  {
    case 'n':
      return '\n';
    case 'r':
      return '\r';
    case 't':
      return '\t';
  }
  return ch;
}

char *string_convert_escaped(char *str)
{
  char *output = str;
  char *input = str;
  assert_valid(str);

  while(*input != '\0')
  {
    if(*input == '\\')
    {
      ++input;
      *output = string_escaped_character(*input);
    }
    else if(output != input)
    {
      *output = *input;
    }

    ++input;
    ++output;
  }

  *output = '\0';
  return str;
}

char *string_convert_single_escaped(char *str, char escaped, char replace)
{
  char *output = str;
  char *input = str;
  assert_valid(str);

  while(*input != '\0')
  {
    if(*input == '\\')
    {
      ++input;
      if(*input == escaped)
      {
        *output = replace;
      }
      else
      {
        *output = '\\';
        *(++output) = *input;
      }
    }
    else if(output != input)
    {
      *output = *input;
    }

    ++input;
    ++output;
  }

  *output = '\0';
  return str;
}

char *string_skip_leading(char *str, char leading)
{
  assert_valid(str);

  if(*str != leading)
  {
    return str;
  }
  return str + 1;

}

char *string_nullify_if_found(char *str, char ch)
{
  char *pos;
  assert_valid(str);

  pos = strchr(str, ch);
  if(pos != nil)
  {
    *pos = '\0';
  }
  return pos;
}

uint string_hash(void *p)
{
  char *c;
  uint hash = 0;
  assert_valid(p);

  for(c = (char *)p; *c != '\0'; ++c)
  {
    hash = STRING_HASH_MULTIPLIER * hash + *c;
  }
  return hash;
}

bool string_isequal(void *p1, void *p2)
{
  assert_valid(p1);
  assert_valid(p2);

  return strcmp((char *)p1, (char *)p2) == 0;
}

char *string_after_last(char *str, char last)
{
  char *lastpos;
  assert_valid(str);
  
  lastpos = strrchr(str, last);
  if(lastpos != nil)
  {
    ++lastpos;
  }
  return lastpos;
}


Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.