SVGNumberList.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "mozilla/ArrayUtils.h"
  6. #include "SVGNumberList.h"
  7. #include "nsCharSeparatedTokenizer.h"
  8. #include "nsString.h"
  9. #include "nsTextFormatter.h"
  10. #include "SVGContentUtils.h"
  11. namespace mozilla {
  12. nsresult
  13. SVGNumberList::CopyFrom(const SVGNumberList& rhs)
  14. {
  15. if (!mNumbers.Assign(rhs.mNumbers, fallible)) {
  16. return NS_ERROR_OUT_OF_MEMORY;
  17. }
  18. return NS_OK;
  19. }
  20. void
  21. SVGNumberList::GetValueAsString(nsAString& aValue) const
  22. {
  23. aValue.Truncate();
  24. char16_t buf[24];
  25. uint32_t last = mNumbers.Length() - 1;
  26. for (uint32_t i = 0; i < mNumbers.Length(); ++i) {
  27. // Would like to use aValue.AppendPrintf("%f", mNumbers[i]), but it's not
  28. // possible to always avoid trailing zeros.
  29. nsTextFormatter::snprintf(buf, ArrayLength(buf),
  30. u"%g",
  31. double(mNumbers[i]));
  32. // We ignore OOM, since it's not useful for us to return an error.
  33. aValue.Append(buf);
  34. if (i != last) {
  35. aValue.Append(' ');
  36. }
  37. }
  38. }
  39. nsresult
  40. SVGNumberList::SetValueFromString(const nsAString& aValue)
  41. {
  42. SVGNumberList temp;
  43. nsCharSeparatedTokenizerTemplate<IsSVGWhitespace>
  44. tokenizer(aValue, ',', nsCharSeparatedTokenizer::SEPARATOR_OPTIONAL);
  45. while (tokenizer.hasMoreTokens()) {
  46. float num;
  47. if (!SVGContentUtils::ParseNumber(tokenizer.nextToken(), num)) {
  48. return NS_ERROR_DOM_SYNTAX_ERR;
  49. }
  50. if (!temp.AppendItem(num)) {
  51. return NS_ERROR_OUT_OF_MEMORY;
  52. }
  53. }
  54. if (tokenizer.separatorAfterCurrentToken()) {
  55. return NS_ERROR_DOM_SYNTAX_ERR; // trailing comma
  56. }
  57. return CopyFrom(temp);
  58. }
  59. } // namespace mozilla