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

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

#include <grpc/compression.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpc/support/useful.h>

#include "test/core/util/test_config.h"

static void test_compression_algorithm_parse(void) {
  size_t i;
  const char* valid_names[] = {"identity", "message/gzip", "message/deflate",
                               "stream/gzip"};
  const grpc_compression_algorithm valid_algorithms[] = {
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_MESSAGE_GZIP,
      GRPC_COMPRESS_MESSAGE_DEFLATE, GRPC_COMPRESS_STREAM_GZIP};
  const char* invalid_names[] = {"gzip2", "foo", "", "2gzip"};

  gpr_log(GPR_DEBUG, "test_compression_algorithm_parse");

  for (i = 0; i < GPR_ARRAY_SIZE(valid_names); i++) {
    const char* valid_name = valid_names[i];
    grpc_compression_algorithm algorithm;
    const int success = grpc_compression_algorithm_parse(
        grpc_slice_from_static_string(valid_name), &algorithm);
    GPR_ASSERT(success != 0);
    GPR_ASSERT(algorithm == valid_algorithms[i]);
  }

  for (i = 0; i < GPR_ARRAY_SIZE(invalid_names); i++) {
    const char* invalid_name = invalid_names[i];
    grpc_compression_algorithm algorithm;
    int success;
    success = grpc_compression_algorithm_parse(
        grpc_slice_from_static_string(invalid_name), &algorithm);
    GPR_ASSERT(success == 0);
    /* the value of "algorithm" is undefined upon failure */
  }
}

static void test_compression_algorithm_name(void) {
  int success;
  const char* name;
  size_t i;
  const char* valid_names[] = {"identity", "message/gzip", "message/deflate",
                               "stream/gzip"};
  const grpc_compression_algorithm valid_algorithms[] = {
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_MESSAGE_GZIP,
      GRPC_COMPRESS_MESSAGE_DEFLATE, GRPC_COMPRESS_STREAM_GZIP};

  gpr_log(GPR_DEBUG, "test_compression_algorithm_name");

  for (i = 0; i < GPR_ARRAY_SIZE(valid_algorithms); i++) {
    success = grpc_compression_algorithm_name(valid_algorithms[i], &name);
    GPR_ASSERT(success != 0);
    GPR_ASSERT(strcmp(name, valid_names[i]) == 0);
  }

  success =
      grpc_compression_algorithm_name(GRPC_COMPRESS_ALGORITHMS_COUNT, &name);
  GPR_ASSERT(success == 0);
  /* the value of "name" is undefined upon failure */
}

static void test_compression_algorithm_for_level(void) {
  gpr_log(GPR_DEBUG, "test_compression_algorithm_for_level");

  {
    /* accept only identity (aka none) */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_HIGH, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_HIGH, accepted_encodings));
  }

  {
    /* accept only gzip */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_GZIP);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_HIGH, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_HIGH, accepted_encodings));
  }

  {
    /* accept only deflate */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_DEFLATE);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_HIGH, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_HIGH, accepted_encodings));
  }

  {
    /* accept gzip and deflate */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_GZIP);
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_DEFLATE);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_HIGH, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_HIGH, accepted_encodings));
  }

  {
    /* accept stream gzip */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_STREAM_GZIP);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_HIGH, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_STREAM_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_STREAM_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_STREAM_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_HIGH, accepted_encodings));
  }

  {
    /* accept all algorithms */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_GZIP);
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_DEFLATE);
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_STREAM_GZIP);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MESSAGE_HIGH, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_STREAM_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_STREAM_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_STREAM_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_STREAM_HIGH, accepted_encodings));
  }
}

static void test_compression_enable_disable_algorithm(void) {
  grpc_compression_options options;
  grpc_compression_algorithm algorithm;

  gpr_log(GPR_DEBUG, "test_compression_enable_disable_algorithm");

  grpc_compression_options_init(&options);
  for (algorithm = GRPC_COMPRESS_NONE;
       algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT;
       algorithm = static_cast<grpc_compression_algorithm>(
           static_cast<int>(algorithm) + 1)) {
    /* all algorithms are enabled by default */
    GPR_ASSERT(grpc_compression_options_is_algorithm_enabled(&options,
                                                             algorithm) != 0);
  }
  /* disable one by one */
  for (algorithm = GRPC_COMPRESS_NONE;
       algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT;
       algorithm = static_cast<grpc_compression_algorithm>(
           static_cast<int>(algorithm) + 1)) {
    grpc_compression_options_disable_algorithm(&options, algorithm);
    GPR_ASSERT(grpc_compression_options_is_algorithm_enabled(&options,
                                                             algorithm) == 0);
  }
  /* re-enable one by one */
  for (algorithm = GRPC_COMPRESS_NONE;
       algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT;
       algorithm = static_cast<grpc_compression_algorithm>(
           static_cast<int>(algorithm) + 1)) {
    grpc_compression_options_enable_algorithm(&options, algorithm);
    GPR_ASSERT(grpc_compression_options_is_algorithm_enabled(&options,
                                                             algorithm) != 0);
  }
}

int main(int argc, char** argv) {
  grpc_init();
  test_compression_algorithm_parse();
  test_compression_algorithm_name();
  test_compression_algorithm_for_level();
  test_compression_enable_disable_algorithm();
  grpc_shutdown();

  return 0;
}
<commit_msg>Fix build error in compression_test.cc<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

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

#include <grpc/compression.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpc/support/useful.h>

#include "test/core/util/test_config.h"

static void test_compression_algorithm_parse(void) {
  size_t i;
  const char* valid_names[] = {"identity", "message/gzip", "message/deflate",
                               "stream/gzip"};
  const grpc_compression_algorithm valid_algorithms[] = {
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_MESSAGE_GZIP,
      GRPC_COMPRESS_MESSAGE_DEFLATE, GRPC_COMPRESS_STREAM_GZIP};
  const char* invalid_names[] = {"gzip2", "foo", "", "2gzip"};

  gpr_log(GPR_DEBUG, "test_compression_algorithm_parse");

  for (i = 0; i < GPR_ARRAY_SIZE(valid_names); i++) {
    const char* valid_name = valid_names[i];
    grpc_compression_algorithm algorithm;
    const int success = grpc_compression_algorithm_parse(
        grpc_slice_from_static_string(valid_name), &algorithm);
    GPR_ASSERT(success != 0);
    GPR_ASSERT(algorithm == valid_algorithms[i]);
  }

  for (i = 0; i < GPR_ARRAY_SIZE(invalid_names); i++) {
    const char* invalid_name = invalid_names[i];
    grpc_compression_algorithm algorithm;
    int success;
    success = grpc_compression_algorithm_parse(
        grpc_slice_from_static_string(invalid_name), &algorithm);
    GPR_ASSERT(success == 0);
    /* the value of "algorithm" is undefined upon failure */
  }
}

static void test_compression_algorithm_name(void) {
  int success;
  const char* name;
  size_t i;
  const char* valid_names[] = {"identity", "message/gzip", "message/deflate",
                               "stream/gzip"};
  const grpc_compression_algorithm valid_algorithms[] = {
      GRPC_COMPRESS_NONE, GRPC_COMPRESS_MESSAGE_GZIP,
      GRPC_COMPRESS_MESSAGE_DEFLATE, GRPC_COMPRESS_STREAM_GZIP};

  gpr_log(GPR_DEBUG, "test_compression_algorithm_name");

  for (i = 0; i < GPR_ARRAY_SIZE(valid_algorithms); i++) {
    success = grpc_compression_algorithm_name(valid_algorithms[i], &name);
    GPR_ASSERT(success != 0);
    GPR_ASSERT(strcmp(name, valid_names[i]) == 0);
  }

  success =
      grpc_compression_algorithm_name(GRPC_COMPRESS_ALGORITHMS_COUNT, &name);
  GPR_ASSERT(success == 0);
  /* the value of "name" is undefined upon failure */
}

static void test_compression_algorithm_for_level(void) {
  gpr_log(GPR_DEBUG, "test_compression_algorithm_for_level");

  {
    /* accept only identity (aka none) */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_HIGH, accepted_encodings));
  }

  {
    /* accept only gzip */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_GZIP);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_HIGH, accepted_encodings));
  }

  {
    /* accept only deflate */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_DEFLATE);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_HIGH, accepted_encodings));
  }

  {
    /* accept gzip and deflate */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_GZIP);
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_DEFLATE);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_HIGH, accepted_encodings));
  }

  {
    /* accept stream gzip */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_STREAM_GZIP);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_HIGH, accepted_encodings));
  }

  {
    /* accept all algorithms */
    uint32_t accepted_encodings = 0;
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_NONE); /* always */
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_GZIP);
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_MESSAGE_DEFLATE);
    GPR_BITSET(&accepted_encodings, GRPC_COMPRESS_STREAM_GZIP);

    GPR_ASSERT(GRPC_COMPRESS_NONE ==
               grpc_compression_algorithm_for_level(GRPC_COMPRESS_LEVEL_NONE,
                                                    accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_GZIP ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_LOW, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_MED, accepted_encodings));

    GPR_ASSERT(GRPC_COMPRESS_MESSAGE_DEFLATE ==
               grpc_compression_algorithm_for_level(
                   GRPC_COMPRESS_LEVEL_HIGH, accepted_encodings));
  }
}

static void test_compression_enable_disable_algorithm(void) {
  grpc_compression_options options;
  grpc_compression_algorithm algorithm;

  gpr_log(GPR_DEBUG, "test_compression_enable_disable_algorithm");

  grpc_compression_options_init(&options);
  for (algorithm = GRPC_COMPRESS_NONE;
       algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT;
       algorithm = static_cast<grpc_compression_algorithm>(
           static_cast<int>(algorithm) + 1)) {
    /* all algorithms are enabled by default */
    GPR_ASSERT(grpc_compression_options_is_algorithm_enabled(&options,
                                                             algorithm) != 0);
  }
  /* disable one by one */
  for (algorithm = GRPC_COMPRESS_NONE;
       algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT;
       algorithm = static_cast<grpc_compression_algorithm>(
           static_cast<int>(algorithm) + 1)) {
    grpc_compression_options_disable_algorithm(&options, algorithm);
    GPR_ASSERT(grpc_compression_options_is_algorithm_enabled(&options,
                                                             algorithm) == 0);
  }
  /* re-enable one by one */
  for (algorithm = GRPC_COMPRESS_NONE;
       algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT;
       algorithm = static_cast<grpc_compression_algorithm>(
           static_cast<int>(algorithm) + 1)) {
    grpc_compression_options_enable_algorithm(&options, algorithm);
    GPR_ASSERT(grpc_compression_options_is_algorithm_enabled(&options,
                                                             algorithm) != 0);
  }
}

int main(int argc, char** argv) {
  grpc_init();
  test_compression_algorithm_parse();
  test_compression_algorithm_name();
  test_compression_algorithm_for_level();
  test_compression_enable_disable_algorithm();
  grpc_shutdown();

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: core_resource.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-25 16:26:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "core_resource.hxx"

#ifndef _TOOLS_SIMPLERESMGR_HXX_
#include <tools/simplerm.hxx>
#endif

// ---- needed as long as we have no contexts for components ---
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//---------------------------------------------------
#ifndef _COMPHELPER_CONFIGURATIONHELPER_HXX_
#include <comphelper/configurationhelper.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMACROEXPANDER_HPP_
#include <com/sun/star/util/XMacroExpander.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _RTL_URI_HXX_
#include <rtl/uri.hxx>
#endif

#ifndef _SOLAR_HRC
#include <svtools/solar.hrc>
#endif
#ifndef _RPTUI_MODULE_HELPER_RPT_HXX_
#include "ModuleHelper.hxx"
#endif
//.........................................................................
namespace reportdesign
{
    using namespace ::com::sun::star;
    //==================================================================
    //= ResourceManager
    //==================================================================
    SimpleResMgr* ResourceManager::m_pImpl = NULL;

    //------------------------------------------------------------------
    ResourceManager::EnsureDelete::~EnsureDelete()
    {
        delete ResourceManager::m_pImpl;
    }

    //------------------------------------------------------------------
    void ResourceManager::ensureImplExists(const uno::Reference< lang::XMultiComponentFactory >& /* _rM */)
    {
        if (!m_pImpl)
        {
            // now that we have an impl class make sure it's deleted on unloading the library
            static ResourceManager::EnsureDelete    s_aDeleteTheImplClass;

            ::com::sun::star::lang::Locale aLocale = Application::GetSettings().GetUILocale();

            rtl::OString sResLibName = rtl::OString( "rpt" );
            m_pImpl = SimpleResMgr::Create(sResLibName, aLocale);
        }
    }

    //------------------------------------------------------------------
    ::rtl::OUString ResourceManager::loadString(sal_uInt16 _nResId,const uno::Reference< lang::XMultiComponentFactory >& _rM)
    {
        ::rtl::OUString sReturn;

        ensureImplExists(_rM);
        if (m_pImpl)
            sReturn = m_pImpl->ReadString(_nResId);

        return sReturn;
    }

//.........................................................................
}
//.........................................................................

<commit_msg>INTEGRATION: CWS changefileheader (1.3.16); FILE MERGED 2008/04/01 15:23:35 thb 1.3.16.3: #i85898# Stripping all external header guards 2008/04/01 12:33:07 thb 1.3.16.2: #i85898# Stripping all external header guards 2008/03/31 13:32:04 rt 1.3.16.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: core_resource.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "core_resource.hxx"
#include <tools/simplerm.hxx>

// ---- needed as long as we have no contexts for components ---
#include <vcl/svapp.hxx>
//---------------------------------------------------
#include <comphelper/configurationhelper.hxx>
#include <osl/thread.h>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <rtl/uri.hxx>

#ifndef _SOLAR_HRC
#include <svtools/solar.hrc>
#endif
#include "ModuleHelper.hxx"
//.........................................................................
namespace reportdesign
{
    using namespace ::com::sun::star;
    //==================================================================
    //= ResourceManager
    //==================================================================
    SimpleResMgr* ResourceManager::m_pImpl = NULL;

    //------------------------------------------------------------------
    ResourceManager::EnsureDelete::~EnsureDelete()
    {
        delete ResourceManager::m_pImpl;
    }

    //------------------------------------------------------------------
    void ResourceManager::ensureImplExists(const uno::Reference< lang::XMultiComponentFactory >& /* _rM */)
    {
        if (!m_pImpl)
        {
            // now that we have an impl class make sure it's deleted on unloading the library
            static ResourceManager::EnsureDelete    s_aDeleteTheImplClass;

            ::com::sun::star::lang::Locale aLocale = Application::GetSettings().GetUILocale();

            rtl::OString sResLibName = rtl::OString( "rpt" );
            m_pImpl = SimpleResMgr::Create(sResLibName, aLocale);
        }
    }

    //------------------------------------------------------------------
    ::rtl::OUString ResourceManager::loadString(sal_uInt16 _nResId,const uno::Reference< lang::XMultiComponentFactory >& _rM)
    {
        ::rtl::OUString sReturn;

        ensureImplExists(_rM);
        if (m_pImpl)
            sReturn = m_pImpl->ReadString(_nResId);

        return sReturn;
    }

//.........................................................................
}
//.........................................................................

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CheckTokenMembership.cpp,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2007-08-20 13:35:59 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "macros.h"

DEFINE_DEFAULT_THUNK( advapi32, TRYLOAD, BOOL, WINAPI, CheckTokenMembership, (HANDLE TokenHandle, PSID SidToCheck, PBOOL IsMember) )
<commit_msg>#i10000# warning with Windows Vista SDK<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CheckTokenMembership.cpp,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2007-09-14 12:02:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#if defined(_MSC_VER) && (_MSC_VER>=1400)
#pragma warning(disable : 4273)
#endif
#include "macros.h"

DEFINE_DEFAULT_THUNK( advapi32, TRYLOAD, BOOL, WINAPI, CheckTokenMembership, (HANDLE TokenHandle, PSID SidToCheck, PBOOL IsMember) )
<|endoftext|>


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

#include "modules/control/common/trajectory_analyzer.h"

#include <algorithm>
#include <cmath>
#include <utility>

#include "modules/common/log.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/search.h"

namespace math = apollo::common::math;
using apollo::common::PathPoint;
using apollo::common::TrajectoryPoint;

namespace apollo {
namespace control {
namespace {

// Squared distance from the point to (x, y).
double PointDistanceSquare(const TrajectoryPoint &point, const double x,
                           const double y) {
  const double dx = point.path_point().x() - x;
  const double dy = point.path_point().y() - y;
  return dx * dx + dy * dy;
}

PathPoint TrajectoryPointToPathPoint(const TrajectoryPoint &point) {
  if (point.has_path_point()) {
    return point.path_point();
  } else {
    return PathPoint();
  }
}

}  // namespace

TrajectoryAnalyzer::TrajectoryAnalyzer(
    const planning::ADCTrajectory *planning_published_trajectory) {
  header_time_ = planning_published_trajectory->header().timestamp_sec();
  seq_num_ = planning_published_trajectory->header().sequence_num();

  for (int i = 0; i < planning_published_trajectory->trajectory_point_size();
       ++i) {
    trajectory_points_.push_back(
        planning_published_trajectory->trajectory_point(i));
  }
}

PathPoint TrajectoryAnalyzer::QueryMatchedPathPoint(const double x,
                                                    const double y) const {
  CHECK(trajectory_points_.size() > 0);

  double d_min = PointDistanceSquare(trajectory_points_.front(), x, y);
  size_t index_min = 0;

  for (size_t i = 1; i < trajectory_points_.size(); ++i) {
    double d_temp = PointDistanceSquare(trajectory_points_[i], x, y);
    if (d_temp < d_min) {
      d_min = d_temp;
      index_min = i;
    }
  }

  size_t index_start = index_min == 0 ? index_min : index_min - 1;
  size_t index_end =
      index_min + 1 == trajectory_points_.size() ? index_min : index_min + 1;

  const double kEpsilon = 0.001;
  if (index_start == index_end ||
      std::fabs(trajectory_points_[index_start].path_point().s() -
                trajectory_points_[index_end].path_point().s()) <= kEpsilon) {
    return TrajectoryPointToPathPoint(trajectory_points_[index_start]);
  }

  return FindMinDistancePoint(trajectory_points_[index_start],
                              trajectory_points_[index_end], x, y);
}

// reference: Optimal trajectory generation for dynamic street scenarios in a
// Frenét Frame,
// Moritz Werling, Julius Ziegler, Sören Kammel and Sebastian Thrun, ICRA 2010
// similar to the method in this paper without the assumption the "normal"
// vector
// (from vehicle position to ref_point position) and reference heading are
// perpendicular.
void TrajectoryAnalyzer::ToTrajectoryFrame(const double x, const double y,
                                           const double theta, const double v,
                                           const PathPoint &ref_point,
                                           double *ptr_s, double *ptr_s_dot,
                                           double *ptr_d,
                                           double *ptr_d_dot) const {
  double dx = x - ref_point.x();
  double dy = y - ref_point.y();

  double cos_ref_theta = std::cos(ref_point.theta());
  double sin_ref_theta = std::sin(ref_point.theta());

  // the sin of diff angle between vector (cos_ref_theta, sin_ref_theta) and
  // (dx, dy)
  double cross_rd_nd = cos_ref_theta * dy - sin_ref_theta * dx;
  *ptr_d = cross_rd_nd;

  // the cos of diff angle between vector (cos_ref_theta, sin_ref_theta) and
  // (dx, dy)
  double dot_rd_nd = dx * cos_ref_theta + dy * sin_ref_theta;
  *ptr_s = ref_point.s() + dot_rd_nd;

  double delta_theta = theta - ref_point.theta();
  double cos_delta_theta = std::cos(delta_theta);
  double sin_delta_theta = std::sin(delta_theta);

  *ptr_d_dot = v * sin_delta_theta;

  double one_minus_kappa_r_d = 1 - ref_point.kappa() * (*ptr_d);
  if (one_minus_kappa_r_d <= 0.0) {
    AERROR << "TrajectoryAnalyzer::ToTrajectoryFrame "
              "found fatal reference and actual difference. "
              "Control output might be unstable:"
           << " ref_point.kappa:" << ref_point.kappa()
           << " ref_point.x:" << ref_point.x()
           << " ref_point.y:" << ref_point.y() << " car x:" << x
           << " car y:" << y << " *ptr_d:" << *ptr_d
           << " one_minus_kappa_r_d:" << one_minus_kappa_r_d;
    // currently set to a small value to avoid control crash.
    one_minus_kappa_r_d = 0.01;
  }

  *ptr_s_dot = v * cos_delta_theta / one_minus_kappa_r_d;
}

TrajectoryPoint TrajectoryAnalyzer::QueryNearestPointByAbsoluteTime(
    const double t) const {
  return QueryNearestPointByRelativeTime(t - header_time_);
}

TrajectoryPoint TrajectoryAnalyzer::QueryNearestPointByRelativeTime(
    const double t) const {
  auto func_comp = [](const TrajectoryPoint &point,
                      const double relative_time) {
    return point.relative_time() < relative_time;
  };

  auto it_low = std::lower_bound(trajectory_points_.begin(),
                                 trajectory_points_.end(), t, func_comp);

  if (it_low == trajectory_points_.begin()) {
    return trajectory_points_.front();
  }

  if (it_low == trajectory_points_.end()) {
    return trajectory_points_.back();
  }

  auto it_lower = it_low - 1;
  if (it_low->relative_time() - t < t - it_lower->relative_time()) {
    return *it_low;
  }
  return *it_lower;
}

TrajectoryPoint TrajectoryAnalyzer::QueryNearestPointByPosition(
    const double x, const double y) const {
  double d_min = PointDistanceSquare(trajectory_points_.front(), x, y);
  size_t index_min = 0;

  for (size_t i = 1; i < trajectory_points_.size(); ++i) {
    double d_temp = PointDistanceSquare(trajectory_points_[i], x, y);
    if (d_temp < d_min) {
      d_min = d_temp;
      index_min = i;
    }
  }
  return trajectory_points_[index_min];
}

const std::vector<TrajectoryPoint> &TrajectoryAnalyzer::trajectory_points()
    const {
  return trajectory_points_;
}

PathPoint TrajectoryAnalyzer::FindMinDistancePoint(const TrajectoryPoint &p0,
                                                   const TrajectoryPoint &p1,
                                                   const double x,
                                                   const double y) const {
  // given the fact that the discretized trajectory is dense enough,
  // we assume linear trajectory between consecutive trajectory points.
  auto dist_square = [&p0, &p1, &x, &y](const double s) {
    double px = math::lerp(p0.path_point().x(), p0.path_point().s(),
                           p1.path_point().x(), p1.path_point().s(), s);
    double py = math::lerp(p0.path_point().y(), p0.path_point().s(),
                           p1.path_point().y(), p1.path_point().s(), s);
    double dx = px - x;
    double dy = py - y;
    return dx * dx + dy * dy;
  };

  PathPoint p = p0.path_point();
  double s = math::GoldenSectionSearch(dist_square, p0.path_point().s(),
                                       p1.path_point().s());
  p.set_s(s);
  p.set_x(math::lerp(p0.path_point().x(), p0.path_point().s(),
                     p1.path_point().x(), p1.path_point().s(), s));
  p.set_y(math::lerp(p0.path_point().y(), p0.path_point().s(),
                     p1.path_point().y(), p1.path_point().s(), s));
  p.set_theta(math::slerp(p0.path_point().theta(), p0.path_point().s(),
                          p1.path_point().theta(), p1.path_point().s(), s));
  // approximate the curvature at the intermediate point
  p.set_kappa(math::lerp(p0.path_point().kappa(), p0.path_point().s(),
                         p1.path_point().kappa(), p1.path_point().s(), s));
  return p;
}

}  // namespace control
}  // namespace apollo
<commit_msg>Control: lint fix (#5171)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/control/common/trajectory_analyzer.h"

#include <algorithm>
#include <cmath>
#include <utility>

#include "modules/common/log.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/search.h"

namespace math = apollo::common::math;
using apollo::common::PathPoint;
using apollo::common::TrajectoryPoint;

namespace apollo {
namespace control {
namespace {

// Squared distance from the point to (x, y).
double PointDistanceSquare(const TrajectoryPoint &point, const double x,
                           const double y) {
  const double dx = point.path_point().x() - x;
  const double dy = point.path_point().y() - y;
  return dx * dx + dy * dy;
}

PathPoint TrajectoryPointToPathPoint(const TrajectoryPoint &point) {
  if (point.has_path_point()) {
    return point.path_point();
  } else {
    return PathPoint();
  }
}

}  // namespace

TrajectoryAnalyzer::TrajectoryAnalyzer(
    const planning::ADCTrajectory *planning_published_trajectory) {
  header_time_ = planning_published_trajectory->header().timestamp_sec();
  seq_num_ = planning_published_trajectory->header().sequence_num();

  for (int i = 0; i < planning_published_trajectory->trajectory_point_size();
       ++i) {
    trajectory_points_.push_back(
        planning_published_trajectory->trajectory_point(i));
  }
}

PathPoint TrajectoryAnalyzer::QueryMatchedPathPoint(const double x,
                                                    const double y) const {
  CHECK_GT(trajectory_points_.size(), 0);

  double d_min = PointDistanceSquare(trajectory_points_.front(), x, y);
  size_t index_min = 0;

  for (size_t i = 1; i < trajectory_points_.size(); ++i) {
    double d_temp = PointDistanceSquare(trajectory_points_[i], x, y);
    if (d_temp < d_min) {
      d_min = d_temp;
      index_min = i;
    }
  }

  size_t index_start = index_min == 0 ? index_min : index_min - 1;
  size_t index_end =
      index_min + 1 == trajectory_points_.size() ? index_min : index_min + 1;

  const double kEpsilon = 0.001;
  if (index_start == index_end ||
      std::fabs(trajectory_points_[index_start].path_point().s() -
                trajectory_points_[index_end].path_point().s()) <= kEpsilon) {
    return TrajectoryPointToPathPoint(trajectory_points_[index_start]);
  }

  return FindMinDistancePoint(trajectory_points_[index_start],
                              trajectory_points_[index_end], x, y);
}

// reference: Optimal trajectory generation for dynamic street scenarios in a
// Frenét Frame,
// Moritz Werling, Julius Ziegler, Sören Kammel and Sebastian Thrun, ICRA 2010
// similar to the method in this paper without the assumption the "normal"
// vector
// (from vehicle position to ref_point position) and reference heading are
// perpendicular.
void TrajectoryAnalyzer::ToTrajectoryFrame(const double x, const double y,
                                           const double theta, const double v,
                                           const PathPoint &ref_point,
                                           double *ptr_s, double *ptr_s_dot,
                                           double *ptr_d,
                                           double *ptr_d_dot) const {
  double dx = x - ref_point.x();
  double dy = y - ref_point.y();

  double cos_ref_theta = std::cos(ref_point.theta());
  double sin_ref_theta = std::sin(ref_point.theta());

  // the sin of diff angle between vector (cos_ref_theta, sin_ref_theta) and
  // (dx, dy)
  double cross_rd_nd = cos_ref_theta * dy - sin_ref_theta * dx;
  *ptr_d = cross_rd_nd;

  // the cos of diff angle between vector (cos_ref_theta, sin_ref_theta) and
  // (dx, dy)
  double dot_rd_nd = dx * cos_ref_theta + dy * sin_ref_theta;
  *ptr_s = ref_point.s() + dot_rd_nd;

  double delta_theta = theta - ref_point.theta();
  double cos_delta_theta = std::cos(delta_theta);
  double sin_delta_theta = std::sin(delta_theta);

  *ptr_d_dot = v * sin_delta_theta;

  double one_minus_kappa_r_d = 1 - ref_point.kappa() * (*ptr_d);
  if (one_minus_kappa_r_d <= 0.0) {
    AERROR << "TrajectoryAnalyzer::ToTrajectoryFrame "
              "found fatal reference and actual difference. "
              "Control output might be unstable:"
           << " ref_point.kappa:" << ref_point.kappa()
           << " ref_point.x:" << ref_point.x()
           << " ref_point.y:" << ref_point.y() << " car x:" << x
           << " car y:" << y << " *ptr_d:" << *ptr_d
           << " one_minus_kappa_r_d:" << one_minus_kappa_r_d;
    // currently set to a small value to avoid control crash.
    one_minus_kappa_r_d = 0.01;
  }

  *ptr_s_dot = v * cos_delta_theta / one_minus_kappa_r_d;
}

TrajectoryPoint TrajectoryAnalyzer::QueryNearestPointByAbsoluteTime(
    const double t) const {
  return QueryNearestPointByRelativeTime(t - header_time_);
}

TrajectoryPoint TrajectoryAnalyzer::QueryNearestPointByRelativeTime(
    const double t) const {
  auto func_comp = [](const TrajectoryPoint &point,
                      const double relative_time) {
    return point.relative_time() < relative_time;
  };

  auto it_low = std::lower_bound(trajectory_points_.begin(),
                                 trajectory_points_.end(), t, func_comp);

  if (it_low == trajectory_points_.begin()) {
    return trajectory_points_.front();
  }

  if (it_low == trajectory_points_.end()) {
    return trajectory_points_.back();
  }

  auto it_lower = it_low - 1;
  if (it_low->relative_time() - t < t - it_lower->relative_time()) {
    return *it_low;
  }
  return *it_lower;
}

TrajectoryPoint TrajectoryAnalyzer::QueryNearestPointByPosition(
    const double x, const double y) const {
  double d_min = PointDistanceSquare(trajectory_points_.front(), x, y);
  size_t index_min = 0;

  for (size_t i = 1; i < trajectory_points_.size(); ++i) {
    double d_temp = PointDistanceSquare(trajectory_points_[i], x, y);
    if (d_temp < d_min) {
      d_min = d_temp;
      index_min = i;
    }
  }
  return trajectory_points_[index_min];
}

const std::vector<TrajectoryPoint> &TrajectoryAnalyzer::trajectory_points()
    const {
  return trajectory_points_;
}

PathPoint TrajectoryAnalyzer::FindMinDistancePoint(const TrajectoryPoint &p0,
                                                   const TrajectoryPoint &p1,
                                                   const double x,
                                                   const double y) const {
  // given the fact that the discretized trajectory is dense enough,
  // we assume linear trajectory between consecutive trajectory points.
  auto dist_square = [&p0, &p1, &x, &y](const double s) {
    double px = math::lerp(p0.path_point().x(), p0.path_point().s(),
                           p1.path_point().x(), p1.path_point().s(), s);
    double py = math::lerp(p0.path_point().y(), p0.path_point().s(),
                           p1.path_point().y(), p1.path_point().s(), s);
    double dx = px - x;
    double dy = py - y;
    return dx * dx + dy * dy;
  };

  PathPoint p = p0.path_point();
  double s = math::GoldenSectionSearch(dist_square, p0.path_point().s(),
                                       p1.path_point().s());
  p.set_s(s);
  p.set_x(math::lerp(p0.path_point().x(), p0.path_point().s(),
                     p1.path_point().x(), p1.path_point().s(), s));
  p.set_y(math::lerp(p0.path_point().y(), p0.path_point().s(),
                     p1.path_point().y(), p1.path_point().s(), s));
  p.set_theta(math::slerp(p0.path_point().theta(), p0.path_point().s(),
                          p1.path_point().theta(), p1.path_point().s(), s));
  // approximate the curvature at the intermediate point
  p.set_kappa(math::lerp(p0.path_point().kappa(), p0.path_point().s(),
                         p1.path_point().kappa(), p1.path_point().s(), s));
  return p;
}

}  // namespace control
}  // namespace apollo
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/repo_controller.h>
#include <repo/error_codes.h>
#include "../repo_test_database_info.h"
#include "../repo_test_fileservice_info.h"
#include "../repo_test_utils.h"

using namespace repo;

static std::shared_ptr<RepoController> getController()
{
	static std::shared_ptr<RepoController> controller =
		std::make_shared<RepoController>();

	return controller;
}

TEST(RepoControllerTest, CommitScene) {
	auto controller = getController();
	auto token = initController(controller.get());
	//Try to commit a scene without setting db/project name
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	EXPECT_EQ(REPOERR_OK, errCode);
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Trying to commit a scene with empty db and project name should also fail
	scene->setDatabaseAndProjectName("", "");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("balh", "");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("", "blah");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Setting the db name and project name should allow commit successfully
	scene->setDatabaseAndProjectName("commitSceneTest", "commitCube");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene));
	EXPECT_TRUE(scene->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube"));
	EXPECT_EQ(scene->getOwner(), REPO_GTEST_DBUSER);

	auto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	std::string owner = "dog";
	EXPECT_EQ(errCode, 0);
	scene2->setDatabaseAndProjectName("commitSceneTest", "commitCube2");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene2, owner));
	EXPECT_TRUE(scene2->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube2"));
	EXPECT_EQ(scene2->getOwner(), owner);

	//null pointer checks
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, nullptr));
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(nullptr, scene));
}

TEST(RepoControllerTest, LoadSceneFromFile) {
	auto controller = getController();
	auto defaultG = core::model::RepoScene::GraphType::DEFAULT;
	auto optG = core::model::RepoScene::GraphType::OPTIMIZED;

	//standard import
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	ASSERT_TRUE(scene);
	EXPECT_EQ(errCode, 0);
	ASSERT_TRUE(scene->getRoot(defaultG));
	ASSERT_TRUE(scene->getRoot(optG));
	EXPECT_FALSE(scene->isMissingTexture());
	EXPECT_FALSE(scene->isRevisioned());
	EXPECT_TRUE(dynamic_cast<core::model::TransformationNode*>(scene->getRoot(defaultG))->isIdentity());

	//Import the scene with no transformation reduction
	auto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(false));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoReduction);
	EXPECT_TRUE(sceneNoReduction->getRoot(defaultG));
	EXPECT_TRUE(sceneNoReduction->getRoot(optG));
	EXPECT_FALSE(sceneNoReduction->isMissingTexture());
	//There should be more transformations in the non-reduced scene than the standard scene
	EXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size()
			> scene->getAllTransformations(defaultG).size());

	//Import the scene with root trans rotated
	auto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(true, true, true));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneRotated);
	ASSERT_TRUE(sceneRotated->getRoot(defaultG));
	EXPECT_TRUE(sceneRotated->getRoot(optG));
	EXPECT_FALSE(sceneRotated->isMissingTexture());
	//The root transformation should not be an identity
	core::model::TransformationNode *rootTrans = dynamic_cast<core::model::TransformationNode*>(sceneRotated->getRoot(defaultG));
	EXPECT_FALSE(rootTrans->isIdentity());

	//Import the scene with non existant file
	auto sceneNoFile = controller->loadSceneFromFile("thisFileDoesntExist.obj", errCode);
	EXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ);
	EXPECT_FALSE(sceneNoFile);

	//Import the scene with bad Extension
	auto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode);
	EXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED);
	EXPECT_FALSE(sceneBadExt);

	//Import the scene with texture but not found
	auto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoTex);
	EXPECT_TRUE(sceneNoTex->getRoot(defaultG));
	EXPECT_TRUE(sceneNoTex->getRoot(optG));
	EXPECT_TRUE(sceneNoTex->isMissingTexture());

	//Import the scene with texture but not found
	auto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneTex);
	EXPECT_TRUE(sceneTex->getRoot(defaultG));
	EXPECT_TRUE(sceneTex->getRoot(optG));
	EXPECT_FALSE(sceneTex->isMissingTexture());

	//FIXME: need to test with change of config, but this is probably not trival.
}<commit_msg>ISSUE #381 more changes.<commit_after>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/repo_controller.h>
#include <repo/error_codes.h>
#include "../repo_test_database_info.h"
#include "../repo_test_fileservice_info.h"
#include "../repo_test_utils.h"

using namespace repo;

static std::shared_ptr<RepoController> getController()
{
	static std::shared_ptr<RepoController> controller =
		std::make_shared<RepoController>();

	return controller;
}

TEST(RepoControllerTest, CommitScene) {
	auto controller = getController();
	auto token = initController(controller.get());
	//Try to commit a scene without setting db/project name
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	EXPECT_EQ(REPOERR_OK, errCode);
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Trying to commit a scene with empty db and project name should also fail
	scene->setDatabaseAndProjectName("", "");
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("balh", "");
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("", "blah");
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Setting the db name and project name should allow commit successfully
	scene->setDatabaseAndProjectName("commitSceneTest", "commitCube");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene));
	EXPECT_TRUE(scene->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube"));
	EXPECT_EQ(scene->getOwner(), REPO_GTEST_DBUSER);

	auto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	std::string owner = "dog";
	EXPECT_EQ(errCode, 0);
	scene2->setDatabaseAndProjectName("commitSceneTest", "commitCube2");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene2, owner));
	EXPECT_TRUE(scene2->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube2"));
	EXPECT_EQ(scene2->getOwner(), owner);

	//null pointer checks
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, nullptr));
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(nullptr, scene));
}

TEST(RepoControllerTest, LoadSceneFromFile) {
	auto controller = getController();
	auto defaultG = core::model::RepoScene::GraphType::DEFAULT;
	auto optG = core::model::RepoScene::GraphType::OPTIMIZED;

	//standard import
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	ASSERT_TRUE(scene);
	EXPECT_EQ(errCode, 0);
	ASSERT_TRUE(scene->getRoot(defaultG));
	ASSERT_TRUE(scene->getRoot(optG));
	EXPECT_FALSE(scene->isMissingTexture());
	EXPECT_FALSE(scene->isRevisioned());
	EXPECT_TRUE(dynamic_cast<core::model::TransformationNode*>(scene->getRoot(defaultG))->isIdentity());

	//Import the scene with no transformation reduction
	auto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(false));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoReduction);
	EXPECT_TRUE(sceneNoReduction->getRoot(defaultG));
	EXPECT_TRUE(sceneNoReduction->getRoot(optG));
	EXPECT_FALSE(sceneNoReduction->isMissingTexture());
	//There should be more transformations in the non-reduced scene than the standard scene
	EXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size()
			> scene->getAllTransformations(defaultG).size());

	//Import the scene with root trans rotated
	auto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(true, true, true));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneRotated);
	ASSERT_TRUE(sceneRotated->getRoot(defaultG));
	EXPECT_TRUE(sceneRotated->getRoot(optG));
	EXPECT_FALSE(sceneRotated->isMissingTexture());
	//The root transformation should not be an identity
	core::model::TransformationNode *rootTrans = dynamic_cast<core::model::TransformationNode*>(sceneRotated->getRoot(defaultG));
	EXPECT_FALSE(rootTrans->isIdentity());

	//Import the scene with non existant file
	auto sceneNoFile = controller->loadSceneFromFile("thisFileDoesntExist.obj", errCode);
	EXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ);
	EXPECT_FALSE(sceneNoFile);

	//Import the scene with bad Extension
	auto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode);
	EXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED);
	EXPECT_FALSE(sceneBadExt);

	//Import the scene with texture but not found
	auto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoTex);
	EXPECT_TRUE(sceneNoTex->getRoot(defaultG));
	EXPECT_TRUE(sceneNoTex->getRoot(optG));
	EXPECT_TRUE(sceneNoTex->isMissingTexture());

	//Import the scene with texture but not found
	auto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneTex);
	EXPECT_TRUE(sceneTex->getRoot(defaultG));
	EXPECT_TRUE(sceneTex->getRoot(optG));
	EXPECT_FALSE(sceneTex->isMissingTexture());

	//FIXME: need to test with change of config, but this is probably not trival.
}<|endoftext|>